diff --git a/android/app/build.gradle.kts b/android/app/build.gradle.kts index aaabc9e..97346f0 100644 --- a/android/app/build.gradle.kts +++ b/android/app/build.gradle.kts @@ -42,12 +42,6 @@ kotlin { } dependencies { - val cameraxVersion = "1.4.1" - implementation("androidx.camera:camera-core:$cameraxVersion") - implementation("androidx.camera:camera-camera2:$cameraxVersion") - implementation("androidx.camera:camera-lifecycle:$cameraxVersion") - implementation("androidx.camera:camera-video:$cameraxVersion") - implementation("androidx.camera:camera-view:$cameraxVersion") implementation("androidx.lifecycle:lifecycle-service:2.8.7") implementation("androidx.core:core-ktx:1.15.0") } diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xml index 9d726ae..efaaff5 100644 --- a/android/app/src/main/AndroidManifest.xml +++ b/android/app/src/main/AndroidManifest.xml @@ -21,7 +21,8 @@ + android:icon="@mipmap/ic_launcher" + android:usesCleartextTraffic="true"> ? = null - private var camera: Camera? = null - private var mainCameraId: String? = null - private var ultraWideCameraId: String? = null - private var ultraWideZoomRatio: Float = DEFAULT_ULTRA_WIDE_ZOOM_RATIO - private var currentLensMode: LensMode = LensMode.MAIN - private var activeRecording: Recording? = null - private var boundLifecycleOwner: LifecycleOwner? = null - private var currentZoomRatio: Float = 1f - private var activeWithAudio: Boolean = true - private var activeDisplayName: String? = null - private var currentSegmentFile: File? = null - private val segmentFiles = mutableListOf() - private var nextSegmentIndex: Int = 1 - private var isSwitchingLens: Boolean = false - - var status: RecordingStatus = RecordingStatus(RecordingState.IDLE) - private set - - var statusListener: ((RecordingStatus) -> Unit)? = null - - private var recordingStartedAt: Long = 0L - private var latestOutputPath: String? = null - private var latestSegmentOutputPaths: List = emptyList() - private var pendingStopCallback: ((String?) -> Unit)? = null - private var pendingSegmentSwitch: PendingSegmentSwitch? = null - - fun bindPreview( - lifecycleOwner: LifecycleOwner, - previewView: PreviewView, - onReady: (Boolean) -> Unit, - ) { - val future = ProcessCameraProvider.getInstance(appContext) - future.addListener( - { - try { - val provider = future.get() - cameraProvider = provider - boundLifecycleOwner = lifecycleOwner - - preview = - Preview.Builder().build().also { - it.surfaceProvider = previewView.surfaceProvider - } - - val recorder = - Recorder.Builder() - .setQualitySelector(QualitySelector.from(Quality.HD)) - .build() - videoCapture = VideoCapture.withOutput(recorder) - - discoverBackCameras(provider) - bindUseCases(provider, lifecycleOwner, selectorForCurrentLensMode()) - applyCurrentZoom() - - updateStatus(RecordingStatus(RecordingState.PREVIEWING)) - onReady(true) - } catch (error: Exception) { - Log.e(TAG, "bindPreview failed", error) - updateStatus( - RecordingStatus( - RecordingState.ERROR, - message = error.message, - ), - ) - onReady(false) - } - }, - mainExecutor, - ) - } - - fun rebindForRecording( - lifecycleOwner: LifecycleOwner, - previewView: PreviewView, - onReady: (Boolean) -> Unit, - ) { - val provider = cameraProvider - if (provider == null) { - bindPreview(lifecycleOwner, previewView, onReady) - return - } - - if ( - boundLifecycleOwner === lifecycleOwner && - preview != null && - videoCapture != null - ) { - onReady(true) - return - } - - try { - boundLifecycleOwner = lifecycleOwner - bindUseCases(provider, lifecycleOwner, selectorForCurrentLensMode()) - applyCurrentZoom() - onReady(true) - } catch (error: Exception) { - Log.e(TAG, "rebindForRecording failed", error) - onReady(false) - } - } - - fun startRecording( - withAudio: Boolean, - displayName: String?, - onStarted: (Boolean, String?) -> Unit, - ) { - val capture = videoCapture - if (capture == null || boundLifecycleOwner == null) { - onStarted(false, "Camera not ready") - return - } - - if (activeRecording != null || isSwitchingLens) { - onStarted(false, "Already recording") - return - } - - activeWithAudio = withAudio - activeDisplayName = displayName - segmentFiles.clear() - nextSegmentIndex = 1 - latestOutputPath = null - latestSegmentOutputPaths = emptyList() - - recordingStartedAt = System.currentTimeMillis() - updateStatus( - RecordingStatus( - RecordingState.RECORDING, - outputPath = latestOutputPath, - ), - ) - - startNewSegment(updateStatusOnStart = false, onStarted = onStarted) - } - - private fun startNewSegment( - updateStatusOnStart: Boolean, - onStarted: (Boolean, String?) -> Unit, - ) { - val capture = videoCapture - if (capture == null || boundLifecycleOwner == null) { - onStarted(false, "Camera not ready") - return - } - if (activeRecording != null) { - onStarted(false, "Already recording") - return - } - - val segmentFile = - RecordingOutputFactory.createSegmentFile( - appContext, - activeDisplayName, - nextSegmentIndex++, - ) - currentSegmentFile = segmentFile - val outputOptions = RecordingOutputFactory.buildSegmentOutputOptions(segmentFile) - - val pending = - capture.output.prepareRecording(appContext, outputOptions).apply { - if (activeWithAudio) { - val granted = - ContextCompat.checkSelfPermission( - appContext, - android.Manifest.permission.RECORD_AUDIO, - ) == android.content.pm.PackageManager.PERMISSION_GRANTED - if (granted) { - withAudioEnabled() - } - } - } - - if (updateStatusOnStart) { - updateStatus( - RecordingStatus( - RecordingState.RECORDING, - outputPath = latestOutputPath, - elapsedMillis = elapsedMillis(), - ), - ) - } - - activeRecording = - pending.start(mainExecutor) { event -> - when (event) { - is VideoRecordEvent.Start -> Unit - is VideoRecordEvent.Finalize -> handleFinalize(event, segmentFile) - } - } - - onStarted(true, segmentFile.absolutePath) - } - - fun stopRecording(onStopped: (String?) -> Unit) { - val recording = activeRecording - if (recording == null) { - onStopped(latestOutputPath) - return - } - if (isSwitchingLens) { - onStopped(null) - return - } - - pendingStopCallback = onStopped - val elapsed = elapsedMillis() - updateStatus( - RecordingStatus( - RecordingState.STOPPING, - outputPath = latestOutputPath, - elapsedMillis = elapsed, - ), - ) - - recording.stop() - activeRecording = null - } - - private fun handleFinalize( - event: VideoRecordEvent.Finalize, - segmentFile: File, - ) { - activeRecording = null - if (!event.hasError() && segmentFile.exists() && segmentFile.length() > 0L) { - segmentFiles.add(segmentFile) - } - - val segmentSwitch = pendingSegmentSwitch - if (segmentSwitch != null) { - pendingSegmentSwitch = null - if (event.hasError()) { - isSwitchingLens = false - val message = event.cause?.message ?: "Recording segment failed" - updateStatus(RecordingStatus(RecordingState.ERROR, message = message)) - segmentSwitch.onComplete(false, zoomCapabilitiesMap(), message) - return - } - continueSegmentSwitch(segmentSwitch) - return - } - - val stopCallback = pendingStopCallback - pendingStopCallback = null - if (stopCallback == null) { - return - } - - if (event.hasError()) { - val message = event.cause?.message ?: "Recording failed" - updateStatus(RecordingStatus(RecordingState.ERROR, message = message)) - stopCallback.invoke(null) - return - } - - finalizeRecordingOutput(stopCallback) - } - - private fun finalizeRecordingOutput(stopCallback: (String?) -> Unit) { - val segments = segmentFiles.toList() - val displayName = activeDisplayName - ioExecutor.execute { - try { - val mergedFile = RecordingOutputFactory.createMergeFile(appContext, displayName) - RecordingSegmentMuxer.mergeOrCopy(segments, mergedFile) - val outputUri = - RecordingOutputFactory.publishToMediaStore( - appContext, - displayName, - mergedFile, - ) - latestOutputPath = outputUri - latestSegmentOutputPaths = emptyList() - cleanupSegmentFiles(segments + mergedFile) - mainExecutor.execute { - val elapsed = System.currentTimeMillis() - recordingStartedAt - updateStatus( - RecordingStatus( - RecordingState.PREVIEWING, - outputPath = latestOutputPath, - elapsedMillis = elapsed, - ), - ) - stopCallback.invoke(latestOutputPath) - } - } catch (error: Exception) { - Log.e(TAG, "finalizeRecordingOutput failed", error) - val publishedParts = publishSegmentsAfterMergeFailure(segments, displayName) - latestOutputPath = publishedParts.firstOrNull() - latestSegmentOutputPaths = publishedParts - mainExecutor.execute { - updateStatus( - RecordingStatus( - RecordingState.ERROR, - outputPath = latestOutputPath, - message = error.message ?: "保存到文件夹失败", - ), - ) - stopCallback.invoke(latestOutputPath) - } - } - } - } - - private fun publishSegmentsAfterMergeFailure( - segments: List, - displayName: String?, - ): List { - return segments.mapIndexedNotNull { index, segment -> - try { - RecordingOutputFactory.publishPartToMediaStore( - appContext, - displayName, - segment, - index + 1, - ) - } catch (error: Exception) { - Log.e(TAG, "publish segment after merge failure failed", error) - null - } - } - } - - private fun cleanupSegmentFiles(files: List) { - files.forEach { file -> - try { - file.delete() - } catch (_: Exception) { - } - } - } - - fun zoomCapabilitiesMap(): Map { - val zoomState = camera?.cameraInfo?.zoomState?.value - val cameraXMin = zoomState?.minZoomRatio ?: 1f - val cameraXMax = zoomState?.maxZoomRatio ?: 3f - val camera2Range = mainCameraZoomRatioRange() - val logicalMin = camera2Range?.lower?.let { minOf(cameraXMin, it) } ?: cameraXMin - val logicalMax = camera2Range?.upper?.let { maxOf(cameraXMax, it) } ?: cameraXMax - val minZoom = - if (hasUltraWideCamera()) { - minOf(ultraWideZoomRatio, logicalMin) - } else { - logicalMin - } - val maxZoom = logicalMax - val zoom = - if (currentLensMode == LensMode.ULTRA_WIDE) { - ultraWideZoomRatio - } else { - currentZoomRatio.coerceIn(minZoom, maxZoom) - } - currentZoomRatio = zoom - Log.d( - TAG, - "zoomCapabilities hasUltraWide=${hasUltraWideCamera()} cameraXMin=$cameraXMin " + - "cameraXMax=$cameraXMax camera2Range=${camera2Range?.description()} " + - "ultraWideZoomRatio=$ultraWideZoomRatio minZoom=$minZoom maxZoom=$maxZoom zoom=$zoom", - ) - return mapOf( - "zoomRatio" to zoom.toDouble(), - "minZoomRatio" to minZoom.toDouble(), - "maxZoomRatio" to maxZoom.toDouble(), - ) - } - - fun setZoomRatio( - ratio: Double, - onComplete: (Boolean, Map, String?) -> Unit, - ) { - val boundCamera = camera - if (boundCamera == null) { - if (isSwitchingLens) { - onComplete(false, zoomCapabilitiesMap(), "Camera lens switch is already in progress") - return - } - val clamped = - if (ratio < 1.0 && hasUltraWideCamera()) { - ultraWideZoomRatio - } else { - ratio.toFloat().coerceAtLeast(1f) - } - currentZoomRatio = clamped - onComplete(true, zoomCapabilitiesMap(), null) - return - } - - if (ratio < 1.0 && hasUltraWideCamera()) { - val logicalRange = mainCameraZoomRatioRange() - if (logicalRange == null || !logicalRange.contains(ratio.toFloat())) { - switchToUltraWide(onComplete) - return - } - } - - if (currentLensMode == LensMode.ULTRA_WIDE) { - switchToMainAndZoom(ratio, onComplete) - return - } - - val zoomState = boundCamera.cameraInfo.zoomState.value - val camera2Range = mainCameraZoomRatioRange() - val minZoom = camera2Range?.lower ?: zoomState?.minZoomRatio ?: 1f - val maxZoom = camera2Range?.upper ?: zoomState?.maxZoomRatio ?: clampedMaxZoom() - val nextZoom = ratio.toFloat().coerceIn(minZoom, maxZoom) - currentZoomRatio = nextZoom - - val future = - if ( - Build.VERSION.SDK_INT >= Build.VERSION_CODES.R && - camera2Range?.contains(nextZoom) == true - ) { - applyCamera2ZoomRatio(boundCamera, nextZoom) - } else { - boundCamera.cameraControl.setZoomRatio(nextZoom) - } - future.addListener( - { - try { - future.get() - val capabilities = zoomCapabilitiesMap() - logSetZoomResult(ratio, nextZoom, capabilities) - onComplete(true, capabilities, null) - } catch (error: Exception) { - if (isSupersededCamera2ZoomRequest(error)) { - Log.d(TAG, "setZoomRatio superseded by newer Camera2 options") - val capabilities = zoomCapabilitiesMap() - logSetZoomResult(ratio, nextZoom, capabilities) - onComplete(true, capabilities, null) - return@addListener - } - Log.e(TAG, "setZoomRatio failed", error) - onComplete(false, zoomCapabilitiesMap(), error.message) - } - }, - mainExecutor, - ) - } - - fun unbind() { - activeRecording?.stop() - activeRecording = null - pendingSegmentSwitch = null - pendingStopCallback = null - isSwitchingLens = false - cameraProvider?.unbindAll() - cameraProvider = null - preview = null - videoCapture = null - camera = null - boundLifecycleOwner = null - currentSegmentFile = null - cleanupSegmentFiles(segmentFiles) - segmentFiles.clear() - nextSegmentIndex = 1 - activeDisplayName = null - currentLensMode = LensMode.MAIN - currentZoomRatio = 1f - ultraWideZoomRatio = DEFAULT_ULTRA_WIDE_ZOOM_RATIO - updateStatus(RecordingStatus(RecordingState.IDLE)) - } - - fun elapsedMillis(): Long { - if (status.state != RecordingState.RECORDING) return 0L - return System.currentTimeMillis() - recordingStartedAt - } - - fun segmentOutputPaths(): List = latestSegmentOutputPaths - - private fun updateStatus(next: RecordingStatus) { - status = next - statusListener?.invoke(next) - } - - private fun applyCurrentZoom() { - val boundCamera = camera ?: return - if (currentLensMode == LensMode.ULTRA_WIDE) { - currentZoomRatio = ultraWideZoomRatio - boundCamera.cameraControl.setZoomRatio(1f) - return - } - val zoomState = boundCamera.cameraInfo.zoomState.value - val camera2Range = mainCameraZoomRatioRange() - val minZoom = camera2Range?.lower ?: zoomState?.minZoomRatio ?: 1f - val maxZoom = camera2Range?.upper ?: zoomState?.maxZoomRatio ?: clampedMaxZoom() - currentZoomRatio = currentZoomRatio.coerceIn(minZoom, maxZoom) - if ( - Build.VERSION.SDK_INT >= Build.VERSION_CODES.R && - camera2Range?.contains(currentZoomRatio) == true - ) { - applyCamera2ZoomRatio(boundCamera, currentZoomRatio) - } else { - boundCamera.cameraControl.setZoomRatio(currentZoomRatio) - } - } - - private fun clampedMaxZoom(): Float { - return camera?.cameraInfo?.zoomState?.value?.maxZoomRatio ?: 3f - } - - private fun discoverBackCameras(provider: ProcessCameraProvider) { - val manager = appContext.getSystemService(Context.CAMERA_SERVICE) as CameraManager - if (mainCameraId == null) { - mainCameraId = cameraIdForSelector(provider, CameraSelector.DEFAULT_BACK_CAMERA) - } - logPublicCameraDiagnostics(provider, manager, mainCameraId) - val ultraWideCamera = findUltraWideCamera(provider, mainCameraId) - ultraWideCameraId = ultraWideCamera?.cameraId - ultraWideZoomRatio = ultraWideCamera?.zoomRatio ?: DEFAULT_ULTRA_WIDE_ZOOM_RATIO - if (ultraWideCamera == null && currentLensMode == LensMode.ULTRA_WIDE) { - currentLensMode = LensMode.MAIN - currentZoomRatio = 1f - } - Log.d( - TAG, - "mainCameraId=$mainCameraId ultraWideCameraId=$ultraWideCameraId " + - "ultraWideZoomRatio=$ultraWideZoomRatio", - ) - } - - private fun cameraIdForSelector( - provider: ProcessCameraProvider, - selector: CameraSelector, - ): String? { - return try { - val infos = selector.filter(provider.availableCameraInfos) - infos.firstOrNull()?.let { Camera2CameraInfo.from(it).cameraId } - } catch (error: Exception) { - Log.w(TAG, "cameraIdForSelector failed", error) - null - } - } - - private fun findUltraWideCamera( - provider: ProcessCameraProvider, - excludedCameraId: String?, - ): UltraWideCamera? { - val manager = appContext.getSystemService(Context.CAMERA_SERVICE) as CameraManager - val candidates = - manager.cameraIdList - .mapNotNull { cameraId -> backCameraProfile(manager, cameraId) } - .onEach { profile -> - Log.d( - TAG, - "backCamera ${profile.description()} " + - "bindable=${provider.hasCameraSafely(selectorForCameraId(profile.cameraId))}", - ) - } - .filter { it.cameraId != excludedCameraId } - .filter { provider.hasCameraSafely(selectorForCameraId(it.cameraId)) } - .sortedWith( - compareByDescending { it.horizontalFov } - .thenBy { it.minFocalLength }, - ) - - val mainProfile = excludedCameraId?.let { backCameraProfile(manager, it) } - val widest = - candidates.firstOrNull() - ?: run { - logPhysicalOnlyUltraWideDiagnostics(manager, mainProfile, excludedCameraId) - return null - } - val candidatesDesc = - candidates.joinToString { it.description() } - val mainDesc = - mainProfile?.description() - Log.d(TAG, "ultraWide candidates=[$candidatesDesc] main=$mainDesc") - if (mainProfile == null) { - return UltraWideCamera(widest.cameraId, DEFAULT_ULTRA_WIDE_ZOOM_RATIO) - } - - val meaningfullyWider = - widest.horizontalFov > mainProfile.horizontalFov * ULTRA_WIDE_FOV_FACTOR || - widest.minFocalLength < mainProfile.minFocalLength * ULTRA_WIDE_FOCAL_FACTOR - Log.d( - TAG, - "ultraWide decision widest=${widest.cameraId} meaningfullyWider=$meaningfullyWider " + - "(fovFactor=$ULTRA_WIDE_FOV_FACTOR focalFactor=$ULTRA_WIDE_FOCAL_FACTOR)", - ) - if (!meaningfullyWider) { - logPhysicalOnlyUltraWideDiagnostics(manager, mainProfile, excludedCameraId) - return null - } - - return UltraWideCamera(widest.cameraId, estimateUltraWideZoomRatio(widest, mainProfile)) - } - - private fun logPublicCameraDiagnostics( - provider: ProcessCameraProvider, - manager: CameraManager, - mainCameraId: String?, - ) { - Log.d(TAG, "publicCameraIds=[${manager.cameraIdList.joinToString()}] mainCameraId=$mainCameraId") - manager.cameraIdList.forEach { cameraId -> - try { - val characteristics = manager.getCameraCharacteristics(cameraId) - val bindable = provider.hasCameraSafely(selectorForCameraId(cameraId)) - val physicalIds = physicalCameraIds(characteristics) - Log.d( - TAG, - "publicCamera id=$cameraId facing=${lensFacingDescription(characteristics)} " + - "physicalIds=[${physicalIds.joinToString()}] " + - "capabilities=[${capabilitiesDescription(characteristics)}] " + - "zoomRange=${zoomRatioRangeFromCharacteristics(characteristics)?.description()} " + - "focals=${focalLengthsDescription(characteristics)} " + - "sensor=${sensorSizeDescription(characteristics)} bindable=$bindable", - ) - if (cameraId == mainCameraId) { - logMainPhysicalCameraDiagnostics(manager, cameraId, physicalIds) - } - } catch (error: Exception) { - Log.w(TAG, "publicCamera diagnostics failed for cameraId=$cameraId", error) - } - } - } - - private fun logMainPhysicalCameraDiagnostics( - manager: CameraManager, - mainCameraId: String, - physicalIds: Set, - ) { - Log.d(TAG, "mainCamera id=$mainCameraId physicalIds=[${physicalIds.joinToString()}]") - physicalIds.forEach { physicalId -> - try { - val characteristics = manager.getCameraCharacteristics(physicalId) - Log.d( - TAG, - "mainPhysicalCamera id=$physicalId facing=${lensFacingDescription(characteristics)} " + - "zoomRange=${zoomRatioRangeFromCharacteristics(characteristics)?.description()} " + - "focals=${focalLengthsDescription(characteristics)} " + - "sensor=${sensorSizeDescription(characteristics)}", - ) - } catch (error: Exception) { - Log.w(TAG, "mainPhysicalCamera diagnostics failed for physicalId=$physicalId", error) - } - } - } - - private fun logPhysicalOnlyUltraWideDiagnostics( - manager: CameraManager, - mainProfile: CameraProfile?, - mainCameraId: String?, - ) { - if (mainProfile == null || mainCameraId == null) { - return - } - val characteristics = - try { - manager.getCameraCharacteristics(mainCameraId) - } catch (error: Exception) { - Log.w(TAG, "physicalOnlyUltraWide diagnostics failed for mainCameraId=$mainCameraId", error) - return - } - val physicalProfiles = - physicalCameraIds(characteristics) - .mapNotNull { physicalId -> backCameraProfile(manager, physicalId) } - .filter { it.cameraId != mainCameraId } - .sortedBy { it.minFocalLength } - val widestPhysical = physicalProfiles.firstOrNull() - if (widestPhysical == null) { - Log.d(TAG, "physicalOnlyUltraWide none main=${mainProfile.description()}") - return - } - val meaningfullyWider = - widestPhysical.horizontalFov > mainProfile.horizontalFov * ULTRA_WIDE_FOV_FACTOR || - widestPhysical.minFocalLength < mainProfile.minFocalLength * ULTRA_WIDE_FOCAL_FACTOR - Log.d( - TAG, - "physicalOnlyUltraWide widest=${widestPhysical.description()} " + - "main=${mainProfile.description()} meaningfullyWider=$meaningfullyWider " + - "exposedAsBindableCamera=false action=diagnostic_only", - ) - } - - private fun backCameraProfile( - manager: CameraManager, - cameraId: String, - ): CameraProfile? { - return try { - val characteristics = manager.getCameraCharacteristics(cameraId) - val facing = characteristics.get(CameraCharacteristics.LENS_FACING) - if (facing != CameraCharacteristics.LENS_FACING_BACK) { - return null - } - val focalLengths = - characteristics.get(CameraCharacteristics.LENS_INFO_AVAILABLE_FOCAL_LENGTHS) - ?: return null - val physicalSize = - characteristics.get(CameraCharacteristics.SENSOR_INFO_PHYSICAL_SIZE) - ?: return null - val minFocalLength = focalLengths.minOrNull() ?: return null - val horizontalFov = - 2.0 * atan((physicalSize.width / (2.0f * minFocalLength)).toDouble()) - CameraProfile( - cameraId, - minFocalLength, - horizontalFov, - zoomRatioRangeFromCharacteristics(characteristics), - ) - } catch (error: Exception) { - Log.w(TAG, "backCameraProfile failed for cameraId=$cameraId", error) - null - } - } - - private fun mainCameraZoomRatioRange(): ZoomRatioRange? { - val cameraId = mainCameraId ?: activeCameraId() - return zoomRatioRangeForCamera(cameraId) - } - - private fun activeCameraId(): String? { - val boundCamera = camera ?: return null - return try { - Camera2CameraInfo.from(boundCamera.cameraInfo).cameraId - } catch (error: Exception) { - null - } - } - - private fun zoomRatioRangeForCamera(cameraId: String?): ZoomRatioRange? { - if (cameraId == null) return null - return try { - val manager = appContext.getSystemService(Context.CAMERA_SERVICE) as CameraManager - zoomRatioRangeFromCharacteristics(manager.getCameraCharacteristics(cameraId)) - } catch (error: Exception) { - Log.w(TAG, "zoomRatioRangeForCamera failed for cameraId=$cameraId", error) - null - } - } - - private fun zoomRatioRangeFromCharacteristics( - characteristics: CameraCharacteristics, - ): ZoomRatioRange? { - if (Build.VERSION.SDK_INT < Build.VERSION_CODES.R) { - return null - } - val range = characteristics.get(CameraCharacteristics.CONTROL_ZOOM_RATIO_RANGE) - ?: return null - return ZoomRatioRange(range.lower, range.upper) - } - - private fun physicalCameraIds(characteristics: CameraCharacteristics): Set { - if (Build.VERSION.SDK_INT < Build.VERSION_CODES.P) { - return emptySet() - } - return characteristics.physicalCameraIds - } - - private fun lensFacingDescription(characteristics: CameraCharacteristics): String { - return when (val facing = characteristics.get(CameraCharacteristics.LENS_FACING)) { - CameraCharacteristics.LENS_FACING_BACK -> "BACK" - CameraCharacteristics.LENS_FACING_FRONT -> "FRONT" - CameraCharacteristics.LENS_FACING_EXTERNAL -> "EXTERNAL" - null -> "null" - else -> "UNKNOWN($facing)" - } - } - - private fun capabilitiesDescription(characteristics: CameraCharacteristics): String { - val capabilities = - characteristics.get(CameraCharacteristics.REQUEST_AVAILABLE_CAPABILITIES) - ?: return "null" - return capabilities.joinToString { capabilityDescription(it) } - } - - private fun capabilityDescription(capability: Int): String { - return when (capability) { - CameraCharacteristics.REQUEST_AVAILABLE_CAPABILITIES_BACKWARD_COMPATIBLE -> - "BACKWARD_COMPATIBLE" - CameraCharacteristics.REQUEST_AVAILABLE_CAPABILITIES_MANUAL_SENSOR -> "MANUAL_SENSOR" - CameraCharacteristics.REQUEST_AVAILABLE_CAPABILITIES_MANUAL_POST_PROCESSING -> - "MANUAL_POST_PROCESSING" - CameraCharacteristics.REQUEST_AVAILABLE_CAPABILITIES_RAW -> "RAW" - CameraCharacteristics.REQUEST_AVAILABLE_CAPABILITIES_PRIVATE_REPROCESSING -> - "PRIVATE_REPROCESSING" - CameraCharacteristics.REQUEST_AVAILABLE_CAPABILITIES_READ_SENSOR_SETTINGS -> - "READ_SENSOR_SETTINGS" - CameraCharacteristics.REQUEST_AVAILABLE_CAPABILITIES_BURST_CAPTURE -> "BURST_CAPTURE" - CameraCharacteristics.REQUEST_AVAILABLE_CAPABILITIES_YUV_REPROCESSING -> - "YUV_REPROCESSING" - CameraCharacteristics.REQUEST_AVAILABLE_CAPABILITIES_DEPTH_OUTPUT -> "DEPTH_OUTPUT" - CameraCharacteristics.REQUEST_AVAILABLE_CAPABILITIES_CONSTRAINED_HIGH_SPEED_VIDEO -> - "CONSTRAINED_HIGH_SPEED_VIDEO" - CameraCharacteristics.REQUEST_AVAILABLE_CAPABILITIES_MOTION_TRACKING -> "MOTION_TRACKING" - CameraCharacteristics.REQUEST_AVAILABLE_CAPABILITIES_LOGICAL_MULTI_CAMERA -> - "LOGICAL_MULTI_CAMERA" - CameraCharacteristics.REQUEST_AVAILABLE_CAPABILITIES_MONOCHROME -> "MONOCHROME" - CameraCharacteristics.REQUEST_AVAILABLE_CAPABILITIES_SECURE_IMAGE_DATA -> "SECURE_IMAGE_DATA" - else -> "UNKNOWN($capability)" - } - } - - private fun focalLengthsDescription(characteristics: CameraCharacteristics): String { - val focalLengths = - characteristics.get(CameraCharacteristics.LENS_INFO_AVAILABLE_FOCAL_LENGTHS) - ?: return "null" - return focalLengths.joinToString(prefix = "[", postfix = "]") - } - - private fun sensorSizeDescription(characteristics: CameraCharacteristics): String { - val size = characteristics.get(CameraCharacteristics.SENSOR_INFO_PHYSICAL_SIZE) - ?: return "null" - return "${size.width}x${size.height}" - } - - private fun estimateUltraWideZoomRatio( - ultraWide: CameraProfile, - main: CameraProfile, - ): Float { - if (main.minFocalLength <= 0f) { - return DEFAULT_ULTRA_WIDE_ZOOM_RATIO - } - val rawRatio = ultraWide.minFocalLength / main.minFocalLength - val roundedRatio = round(rawRatio * 10f) / 10f - return roundedRatio.coerceIn(MIN_ULTRA_WIDE_ZOOM_RATIO, MAX_ULTRA_WIDE_ZOOM_RATIO) - } - - @androidx.annotation.OptIn(ExperimentalCamera2Interop::class) - private fun applyCamera2ZoomRatio( - boundCamera: Camera, - zoomRatio: Float, - ) = - Camera2CameraControl.from(boundCamera.cameraControl) - .setCaptureRequestOptions( - CaptureRequestOptions.Builder() - .setCaptureRequestOption( - CaptureRequest.CONTROL_ZOOM_RATIO, - zoomRatio, - ) - .build(), - ) - - private fun isSupersededCamera2ZoomRequest(error: Exception): Boolean { - val cause = - if (error is ExecutionException) { - error.cause - } else { - error - } - return cause is CameraControl.OperationCanceledException && - cause.message?.contains("updated with new options") == true - } - - private fun logSetZoomResult( - requestedRatio: Double, - nextZoom: Float, - capabilities: Map, - ) { - Log.d( - TAG, - "setZoomRatio result requestedRatio=$requestedRatio nextZoom=$nextZoom " + - "currentZoomRatio=$currentZoomRatio returnedZoom=${capabilities["zoomRatio"]}", - ) - } - - private fun selectorForCurrentLensMode(): CameraSelector { - val cameraId = - if (currentLensMode == LensMode.ULTRA_WIDE) { - ultraWideCameraId - } else { - mainCameraId - } - return if (cameraId != null) { - selectorForCameraId(cameraId) - } else { - CameraSelector.DEFAULT_BACK_CAMERA - } - } - - private fun selectorForCameraId(cameraId: String): CameraSelector { - return CameraSelector.Builder() - .addCameraFilter { cameraInfos -> - cameraInfos.filter { Camera2CameraInfo.from(it).cameraId == cameraId } - } - .build() - } - - private fun bindUseCases( - provider: ProcessCameraProvider, - lifecycleOwner: LifecycleOwner, - selector: CameraSelector, - ) { - val boundPreview = preview ?: throw IllegalStateException("Preview is not ready") - val boundVideoCapture = - videoCapture ?: throw IllegalStateException("Video capture is not ready") - provider.unbindAll() - camera = - provider.bindToLifecycle( - lifecycleOwner, - selector, - boundPreview, - boundVideoCapture, - ) - } - - private fun switchToUltraWide( - onComplete: (Boolean, Map, String?) -> Unit, - ) { - val ultraWideId = ultraWideCameraId - if (ultraWideId == null) { - onComplete(false, zoomCapabilitiesMap(), "Ultra-wide camera is unavailable") - return - } - if (currentLensMode == LensMode.ULTRA_WIDE) { - currentZoomRatio = ultraWideZoomRatio - onComplete(true, zoomCapabilitiesMap(), null) - return - } - if (activeRecording != null) { - switchRecordingSegmentToLens( - LensMode.ULTRA_WIDE, - ultraWideZoomRatio.toDouble(), - onComplete, - ) - return - } - val provider = cameraProvider - val lifecycleOwner = boundLifecycleOwner - if (provider == null || lifecycleOwner == null) { - onComplete(false, zoomCapabilitiesMap(), "Camera is not ready") - return - } - try { - currentLensMode = LensMode.ULTRA_WIDE - currentZoomRatio = ultraWideZoomRatio - bindUseCases(provider, lifecycleOwner, selectorForCameraId(ultraWideId)) - applyCurrentZoom() - onComplete(true, zoomCapabilitiesMap(), null) - } catch (error: Exception) { - Log.e(TAG, "switchToUltraWide failed", error) - currentLensMode = LensMode.MAIN - currentZoomRatio = 1f - try { - bindUseCases(provider, lifecycleOwner, selectorForCurrentLensMode()) - applyCurrentZoom() - } catch (restoreError: Exception) { - Log.e(TAG, "restore main camera after ultra-wide failure failed", restoreError) - } - onComplete(false, zoomCapabilitiesMap(), error.message) - } - } - - private fun switchToMainAndZoom( - ratio: Double, - onComplete: (Boolean, Map, String?) -> Unit, - ) { - if (activeRecording != null) { - switchRecordingSegmentToLens(LensMode.MAIN, ratio, onComplete) - return - } - val provider = cameraProvider - val lifecycleOwner = boundLifecycleOwner - if (provider == null || lifecycleOwner == null) { - onComplete(false, zoomCapabilitiesMap(), "Camera is not ready") - return - } - try { - currentLensMode = LensMode.MAIN - currentZoomRatio = ratio.toFloat().coerceAtLeast(1f) - bindUseCases(provider, lifecycleOwner, selectorForCurrentLensMode()) - setZoomRatio(ratio, onComplete) - } catch (error: Exception) { - Log.e(TAG, "switchToMainAndZoom failed", error) - onComplete(false, zoomCapabilitiesMap(), error.message) - } - } - - private fun hasUltraWideCamera(): Boolean { - return ultraWideCameraId != null - } - - private fun switchRecordingSegmentToLens( - targetLensMode: LensMode, - targetRatio: Double, - onComplete: (Boolean, Map, String?) -> Unit, - ) { - val recording = activeRecording - if (recording == null) { - onComplete(false, zoomCapabilitiesMap(), "Recording is not active") - return - } - if (isSwitchingLens || pendingSegmentSwitch != null) { - onComplete(false, zoomCapabilitiesMap(), "Camera lens switch is already in progress") - return - } - pendingSegmentSwitch = PendingSegmentSwitch(targetLensMode, targetRatio, onComplete) - isSwitchingLens = true - recording.stop() - activeRecording = null - } - - private fun continueSegmentSwitch(request: PendingSegmentSwitch) { - val provider = cameraProvider - val lifecycleOwner = boundLifecycleOwner - if (provider == null || lifecycleOwner == null) { - isSwitchingLens = false - request.onComplete(false, zoomCapabilitiesMap(), "Camera is not ready") - return - } - - try { - currentLensMode = request.targetLensMode - currentZoomRatio = - if (request.targetLensMode == LensMode.ULTRA_WIDE) { - ultraWideZoomRatio - } else { - request.targetRatio.toFloat().coerceAtLeast(1f) - } - bindUseCases(provider, lifecycleOwner, selectorForCurrentLensMode()) - applyCurrentZoom() - startNewSegment(updateStatusOnStart = true) { started, message -> - isSwitchingLens = false - if (started) { - request.onComplete(true, zoomCapabilitiesMap(), null) - } else { - updateStatus(RecordingStatus(RecordingState.ERROR, message = message)) - request.onComplete(false, zoomCapabilitiesMap(), message) - } - } - } catch (error: Exception) { - Log.e(TAG, "continueSegmentSwitch failed", error) - isSwitchingLens = false - updateStatus(RecordingStatus(RecordingState.ERROR, message = error.message)) - request.onComplete(false, zoomCapabilitiesMap(), error.message) - } - } - - private fun ProcessCameraProvider.hasCameraSafely(selector: CameraSelector): Boolean { - return try { - hasCamera(selector) - } catch (error: Exception) { - false - } - } - - private enum class LensMode { - MAIN, - ULTRA_WIDE, - } - - private data class CameraProfile( - val cameraId: String, - val minFocalLength: Float, - val horizontalFov: Double, - val zoomRatioRange: ZoomRatioRange?, - ) { - fun description(): String { - return "id=$cameraId fov=$horizontalFov focal=$minFocalLength " + - "zoomRange=${zoomRatioRange?.description()}" - } - } - - private data class ZoomRatioRange( - val lower: Float, - val upper: Float, - ) { - fun contains(ratio: Float): Boolean { - return ratio >= lower && ratio <= upper - } - - fun description(): String { - return "$lower..$upper" - } - } - - private data class UltraWideCamera( - val cameraId: String, - val zoomRatio: Float, - ) - - private data class PendingSegmentSwitch( - val targetLensMode: LensMode, - val targetRatio: Double, - val onComplete: (Boolean, Map, String?) -> Unit, - ) - - companion object { - private const val TAG = "RecordingCamera" - private const val DEFAULT_ULTRA_WIDE_ZOOM_RATIO = 0.6f - private const val MIN_ULTRA_WIDE_ZOOM_RATIO = 0.3f - private const val MAX_ULTRA_WIDE_ZOOM_RATIO = 0.99f - // 适度放宽判定宽容度,覆盖更多机型(更小的 FOV/焦距差异也视为超广角)。 - private const val ULTRA_WIDE_FOV_FACTOR = 1.04 - private const val ULTRA_WIDE_FOCAL_FACTOR = 0.96 - } -} diff --git a/android/app/src/main/kotlin/com/dronex/rec/recording/RecordingOutputFactory.kt b/android/app/src/main/kotlin/com/dronex/rec/recording/RecordingOutputFactory.kt deleted file mode 100644 index f5f25ad..0000000 --- a/android/app/src/main/kotlin/com/dronex/rec/recording/RecordingOutputFactory.kt +++ /dev/null @@ -1,106 +0,0 @@ -package com.dronex.rec.recording - -import android.content.ContentValues -import android.content.Context -import android.os.Build -import android.provider.MediaStore -import androidx.camera.video.FileOutputOptions -import java.io.File -import java.io.FileInputStream -import java.text.SimpleDateFormat -import java.util.Date -import java.util.Locale - -object RecordingOutputFactory { - private const val RELATIVE_PATH = "Movies/飞行极控录像工作台" - private const val MIME_TYPE = "video/mp4" - - fun buildSegmentOutputOptions(segmentFile: File): FileOutputOptions { - return FileOutputOptions.Builder(segmentFile).build() - } - - fun createSegmentFile( - context: Context, - displayName: String?, - index: Int, - ): File { - val directory = File(context.cacheDir, "recording_segments") - if (!directory.exists()) { - directory.mkdirs() - } - val baseName = resolveFileName(displayName).removeSuffix(".mp4") - return File(directory, "${baseName}_${System.currentTimeMillis()}_part$index.mp4") - } - - fun createMergeFile(context: Context, displayName: String?): File { - val directory = File(context.cacheDir, "recording_segments") - if (!directory.exists()) { - directory.mkdirs() - } - val baseName = resolveFileName(displayName).removeSuffix(".mp4") - return File(directory, "${baseName}_${System.currentTimeMillis()}_merged.mp4") - } - - fun publishToMediaStore( - context: Context, - displayName: String?, - sourceFile: File, - ): String? { - val fileName = resolveFileName(displayName) - val contentValues = - ContentValues().apply { - put(MediaStore.MediaColumns.DISPLAY_NAME, fileName) - put(MediaStore.MediaColumns.MIME_TYPE, MIME_TYPE) - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { - put(MediaStore.Video.Media.RELATIVE_PATH, RELATIVE_PATH) - put(MediaStore.Video.Media.IS_PENDING, 1) - } - } - - val resolver = context.contentResolver - val uri = - resolver.insert(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, contentValues) - ?: return null - try { - val outputStream = - resolver.openOutputStream(uri) - ?: throw IllegalStateException("Cannot open MediaStore output stream") - outputStream.use { output -> - FileInputStream(sourceFile).use { input -> input.copyTo(output) } - } - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { - val publishedValues = - ContentValues().apply { put(MediaStore.Video.Media.IS_PENDING, 0) } - resolver.update(uri, publishedValues, null, null) - } - return uri.toString() - } catch (error: Exception) { - resolver.delete(uri, null, null) - throw error - } - } - - fun publishPartToMediaStore( - context: Context, - displayName: String?, - sourceFile: File, - partIndex: Int, - ): String? { - val resolvedName = resolveFileName(displayName) - val partName = resolvedName.replace(".mp4", "_part$partIndex.mp4") - return publishToMediaStore(context, partName, sourceFile) - } - - fun resolveFileName(displayName: String?): String { - val trimmed = displayName?.trim().orEmpty() - if (trimmed.isNotEmpty()) { - return if (trimmed.lowercase(Locale.US).endsWith(".mp4")) { - trimmed - } else { - "$trimmed.mp4" - } - } - val timestamp = SimpleDateFormat("yyyyMMdd_HHmmss", Locale.US).format(Date()) - return "REC_$timestamp.mp4" - } -} diff --git a/android/app/src/main/kotlin/com/dronex/rec/recording/RecordingPlatformHandler.kt b/android/app/src/main/kotlin/com/dronex/rec/recording/RecordingPlatformHandler.kt index 9bf22f2..5c94a57 100644 --- a/android/app/src/main/kotlin/com/dronex/rec/recording/RecordingPlatformHandler.kt +++ b/android/app/src/main/kotlin/com/dronex/rec/recording/RecordingPlatformHandler.kt @@ -1,64 +1,30 @@ package com.dronex.rec.recording -import android.os.Handler -import android.os.Looper import androidx.core.view.WindowCompat import androidx.core.view.WindowInsetsCompat import androidx.core.view.WindowInsetsControllerCompat import com.dronex.rec.AppConstants import com.dronex.rec.MainActivity import io.flutter.plugin.common.BinaryMessenger -import io.flutter.plugin.common.EventChannel import io.flutter.plugin.common.MethodCall import io.flutter.plugin.common.MethodChannel class RecordingPlatformHandler( private val activity: MainActivity, messenger: BinaryMessenger, -) : MethodChannel.MethodCallHandler, EventChannel.StreamHandler { +) : MethodChannel.MethodCallHandler { private val methodChannel = MethodChannel(messenger, AppConstants.RECORDING_METHOD_CHANNEL) - private val eventChannel = EventChannel(messenger, AppConstants.RECORDING_EVENT_CHANNEL) - - private val mainHandler = Handler(Looper.getMainLooper()) - private var eventSink: EventChannel.EventSink? = null - private var elapsedTicker: Runnable? = null - - private val controller by lazy { RecordingSession.controller(activity.applicationContext) } init { methodChannel.setMethodCallHandler(this) - eventChannel.setStreamHandler(this) - controller.statusListener = { status -> - mainHandler.post { eventSink?.success(status.toMap()) } - } } fun dispose() { - stopElapsedTicker() methodChannel.setMethodCallHandler(null) - eventChannel.setStreamHandler(null) - controller.statusListener = null } override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) { when (call.method) { - "initializePreview" -> initializePreview(result) - "startRecording" -> { - val withAudio = call.argument("withAudio") ?: true - val enableDnd = call.argument("enableDoNotDisturb") ?: true - val displayName = call.argument("displayName") - startRecording(withAudio, enableDnd, displayName, result) - } - "stopRecording" -> stopRecording(result) - "getZoomCapabilities" -> result.success(controller.zoomCapabilitiesMap()) - "setZoomRatio" -> { - val ratio = call.argument("zoomRatio") ?: 1.0 - setZoomRatio(ratio, result) - } - "disposePreview" -> { - controller.unbind() - result.success(null) - } "hasNotificationPolicyAccess" -> result.success(DoNotDisturbHelper.hasAccess(activity)) "openNotificationPolicySettings" -> { DoNotDisturbHelper.openAccessSettings(activity) @@ -80,130 +46,11 @@ class RecordingPlatformHandler( setImmersiveMode(enabled) result.success(null) } - "getStatus" -> result.success(controller.status.toMap()) "isForegroundServiceRunning" -> result.success(RecordingForegroundService.isRunning) else -> result.notImplemented() } } - private fun initializePreview(result: MethodChannel.Result) { - val previewView = activity.recordingPreviewView - if (previewView == null) { - result.error("NO_PREVIEW", "Camera preview is not attached", null) - return - } - - controller.bindPreview(activity, previewView) { ready -> - mainHandler.post { - if (ready) { - result.success(controller.status.toMap()) - } else { - result.error("PREVIEW_FAILED", "Failed to bind camera preview", null) - } - } - } - } - - private fun startRecording( - withAudio: Boolean, - enableDnd: Boolean, - displayName: String?, - result: MethodChannel.Result, - ) { - val previewView = activity.recordingPreviewView - if (previewView == null) { - result.error("NO_PREVIEW", "Camera preview is not attached", null) - return - } - - RecordingSession.startForeground(activity) - - fun beginCapture() { - if (enableDnd && DoNotDisturbHelper.hasAccess(activity)) { - DoNotDisturbHelper.enable(activity) - } - - controller.startRecording(withAudio, displayName) { started, message -> - mainHandler.post { - if (started) { - startElapsedTicker() - result.success( - mapOf( - "outputPath" to message, - "status" to controller.status.toMap(), - ), - ) - } else { - RecordingSession.stopForeground(activity) - DoNotDisturbHelper.disable(activity) - result.error("START_FAILED", message, null) - } - } - } - } - - fun rebindAndCapture() { - val lifecycleOwner = RecordingForegroundService.instance ?: activity - controller.rebindForRecording(lifecycleOwner, previewView) { ready -> - if (ready) { - beginCapture() - } else { - RecordingSession.stopForeground(activity) - result.error("REBIND_FAILED", "Failed to bind camera for recording", null) - } - } - } - - if (RecordingForegroundService.instance != null) { - rebindAndCapture() - } else { - mainHandler.post { rebindAndCapture() } - } - } - - private fun stopRecording(result: MethodChannel.Result) { - stopElapsedTicker() - controller.stopRecording { path -> - RecordingSession.stopForeground(activity) - DoNotDisturbHelper.disable(activity) - val previewView = activity.recordingPreviewView - if (previewView == null) { - mainHandler.post { deliverStopResult(result, path) } - return@stopRecording - } - controller.rebindForRecording(activity, previewView) { _ -> - mainHandler.post { deliverStopResult(result, path) } - } - } - } - - private fun setZoomRatio(ratio: Double, result: MethodChannel.Result) { - controller.setZoomRatio(ratio) { success, capabilities, message -> - mainHandler.post { - if (success) { - result.success(capabilities) - } else { - result.error("ZOOM_FAILED", message ?: "Failed to set camera zoom", null) - } - } - } - } - - private fun deliverStopResult(result: MethodChannel.Result, path: String?) { - val fileSaved = path != null && controller.status.state != RecordingState.ERROR - val payload = - mutableMapOf( - "outputPath" to path, - "status" to controller.status.toMap(), - "fileSaved" to fileSaved, - "segmentOutputPaths" to controller.segmentOutputPaths(), - ) - if (!fileSaved) { - payload["fileErrorMessage"] = controller.status.message ?: "保存到文件夹失败" - } - result.success(payload) - } - private fun setImmersiveMode(enabled: Boolean) { val window = activity.window WindowCompat.setDecorFitsSystemWindows(window, !enabled) @@ -216,41 +63,4 @@ class RecordingPlatformHandler( insetsController.show(WindowInsetsCompat.Type.systemBars()) } } - - private fun startElapsedTicker() { - stopElapsedTicker() - elapsedTicker = - object : Runnable { - override fun run() { - if (controller.status.state == RecordingState.RECORDING) { - eventSink?.success( - controller - .status - .copy( - elapsedMillis = - controller.elapsedMillis(), - ) - .toMap(), - ) - mainHandler.postDelayed(this, 1000L) - } - } - } - .also { mainHandler.post(it) } - } - - private fun stopElapsedTicker() { - elapsedTicker?.let { mainHandler.removeCallbacks(it) } - elapsedTicker = null - } - - override fun onListen(arguments: Any?, events: EventChannel.EventSink?) { - eventSink = events - events?.success(controller.status.toMap()) - } - - override fun onCancel(arguments: Any?) { - eventSink = null - stopElapsedTicker() - } } diff --git a/android/app/src/main/kotlin/com/dronex/rec/recording/RecordingPreviewFactory.kt b/android/app/src/main/kotlin/com/dronex/rec/recording/RecordingPreviewFactory.kt deleted file mode 100644 index cf23051..0000000 --- a/android/app/src/main/kotlin/com/dronex/rec/recording/RecordingPreviewFactory.kt +++ /dev/null @@ -1,37 +0,0 @@ -package com.dronex.rec.recording - -import android.content.Context -import android.view.View -import androidx.camera.view.PreviewView -import com.dronex.rec.MainActivity -import io.flutter.plugin.common.StandardMessageCodec -import io.flutter.plugin.platform.PlatformView -import io.flutter.plugin.platform.PlatformViewFactory - -class RecordingPreviewFactory( - private val activity: MainActivity, -) : PlatformViewFactory(StandardMessageCodec.INSTANCE) { - override fun create(context: Context, viewId: Int, args: Any?): PlatformView { - return RecordingPreviewPlatformView(activity) - } -} - -class RecordingPreviewPlatformView( - private val activity: MainActivity, -) : PlatformView { - val previewView: PreviewView = - PreviewView(activity).apply { - implementationMode = PreviewView.ImplementationMode.COMPATIBLE - scaleType = PreviewView.ScaleType.FILL_CENTER - } - - init { - activity.attachRecordingPreview(previewView) - } - - override fun getView(): View = previewView - - override fun dispose() { - activity.detachRecordingPreview(previewView) - } -} diff --git a/android/app/src/main/kotlin/com/dronex/rec/recording/RecordingSegmentMuxer.kt b/android/app/src/main/kotlin/com/dronex/rec/recording/RecordingSegmentMuxer.kt deleted file mode 100644 index 83b9c18..0000000 --- a/android/app/src/main/kotlin/com/dronex/rec/recording/RecordingSegmentMuxer.kt +++ /dev/null @@ -1,174 +0,0 @@ -package com.dronex.rec.recording - -import android.media.MediaCodec -import android.media.MediaExtractor -import android.media.MediaFormat -import android.media.MediaMuxer -import java.io.File -import java.io.FileInputStream -import java.io.FileOutputStream -import java.nio.ByteBuffer - -object RecordingSegmentMuxer { - fun mergeOrCopy( - segments: List, - outputFile: File, - ) { - val validSegments = segments.filter { it.exists() && it.length() > 0L } - require(validSegments.isNotEmpty()) { "No recording segments were generated" } - if (validSegments.size == 1) { - copyFile(validSegments.first(), outputFile) - return - } - - MediaMuxer(outputFile.absolutePath, MediaMuxer.OutputFormat.MUXER_OUTPUT_MPEG_4).use { - muxer -> - val firstTracks = readTrackFormats(validSegments.first()) - val videoTrack = firstTracks.video?.let { muxer.addTrack(it) } - val audioTrack = firstTracks.audio?.let { muxer.addTrack(it) } - require(videoTrack != null) { "No video track in recording segment" } - - muxer.start() - var offsetUs = 0L - validSegments.forEach { segment -> - val durationUs = - copySegmentTracks( - segment = segment, - muxer = muxer, - videoOutputTrack = videoTrack, - audioOutputTrack = audioTrack, - offsetUs = offsetUs, - ) - offsetUs += durationUs + 1L - } - } - } - - private fun copyFile(source: File, target: File) { - FileInputStream(source).use { input -> - FileOutputStream(target).use { output -> input.copyTo(output) } - } - } - - private fun readTrackFormats(file: File): TrackFormats { - val extractor = MediaExtractor() - extractor.setDataSource(file.absolutePath) - try { - var video: MediaFormat? = null - var audio: MediaFormat? = null - for (index in 0 until extractor.trackCount) { - val format = extractor.getTrackFormat(index) - val mime = format.getString(MediaFormat.KEY_MIME).orEmpty() - when { - mime.startsWith("video/") && video == null -> video = format - mime.startsWith("audio/") && audio == null -> audio = format - } - } - return TrackFormats(video = video, audio = audio) - } finally { - extractor.release() - } - } - - private fun copySegmentTracks( - segment: File, - muxer: MediaMuxer, - videoOutputTrack: Int, - audioOutputTrack: Int?, - offsetUs: Long, - ): Long { - var segmentDurationUs = 0L - segmentDurationUs = - maxOf( - segmentDurationUs, - copyTrack(segment, muxer, "video/", videoOutputTrack, offsetUs), - ) - if (audioOutputTrack != null) { - segmentDurationUs = - maxOf( - segmentDurationUs, - copyTrack(segment, muxer, "audio/", audioOutputTrack, offsetUs), - ) - } - return segmentDurationUs - } - - private fun copyTrack( - segment: File, - muxer: MediaMuxer, - mimePrefix: String, - outputTrack: Int, - offsetUs: Long, - ): Long { - val extractor = MediaExtractor() - extractor.setDataSource(segment.absolutePath) - try { - val inputTrack = findTrack(extractor, mimePrefix) ?: return 0L - extractor.selectTrack(inputTrack) - val bufferSize = trackBufferSize(extractor.getTrackFormat(inputTrack)) - val buffer = ByteBuffer.allocate(bufferSize) - val info = MediaCodec.BufferInfo() - var firstSampleTimeUs: Long? = null - var lastSampleTimeUs = 0L - - while (true) { - buffer.clear() - val sampleSize = extractor.readSampleData(buffer, 0) - if (sampleSize < 0) break - - val sampleTimeUs = extractor.sampleTime - val baseTimeUs = firstSampleTimeUs ?: sampleTimeUs.also { firstSampleTimeUs = it } - val normalizedTimeUs = (sampleTimeUs - baseTimeUs).coerceAtLeast(0L) - info.set( - 0, - sampleSize, - offsetUs + normalizedTimeUs, - extractor.sampleFlags, - ) - muxer.writeSampleData(outputTrack, buffer, info) - lastSampleTimeUs = normalizedTimeUs - extractor.advance() - } - return lastSampleTimeUs - } finally { - extractor.release() - } - } - - private fun findTrack(extractor: MediaExtractor, mimePrefix: String): Int? { - for (index in 0 until extractor.trackCount) { - val mime = extractor.getTrackFormat(index).getString(MediaFormat.KEY_MIME).orEmpty() - if (mime.startsWith(mimePrefix)) { - return index - } - } - return null - } - - private fun trackBufferSize(format: MediaFormat): Int { - return if (format.containsKey(MediaFormat.KEY_MAX_INPUT_SIZE)) { - format.getInteger(MediaFormat.KEY_MAX_INPUT_SIZE).coerceAtLeast(DEFAULT_BUFFER_SIZE) - } else { - DEFAULT_BUFFER_SIZE - } - } - - private data class TrackFormats( - val video: MediaFormat?, - val audio: MediaFormat?, - ) - - private const val DEFAULT_BUFFER_SIZE = 2 * 1024 * 1024 -} - -private inline fun MediaMuxer.use(block: (MediaMuxer) -> Unit) { - try { - block(this) - } finally { - try { - stop() - } catch (_: Exception) { - } - release() - } -} diff --git a/android/app/src/main/kotlin/com/dronex/rec/recording/RecordingSession.kt b/android/app/src/main/kotlin/com/dronex/rec/recording/RecordingSession.kt deleted file mode 100644 index f4874b6..0000000 --- a/android/app/src/main/kotlin/com/dronex/rec/recording/RecordingSession.kt +++ /dev/null @@ -1,30 +0,0 @@ -package com.dronex.rec.recording - -import android.content.Context -import androidx.lifecycle.LifecycleService - -object RecordingSession { - private var cameraController: RecordingCameraController? = null - - fun controller(context: Context): RecordingCameraController { - return cameraController - ?: RecordingCameraController(context.applicationContext).also { - cameraController = it - } - } - - fun release() { - cameraController?.unbind() - cameraController = null - } - - fun startForeground(context: Context) { - RecordingForegroundService.start(context) - } - - fun stopForeground(context: Context) { - RecordingForegroundService.stop(context) - } - - fun recordingLifecycleOwner(): LifecycleService? = RecordingForegroundService.instance -} diff --git a/android/app/src/main/kotlin/com/dronex/rec/recording/RecordingState.kt b/android/app/src/main/kotlin/com/dronex/rec/recording/RecordingState.kt deleted file mode 100644 index 2698080..0000000 --- a/android/app/src/main/kotlin/com/dronex/rec/recording/RecordingState.kt +++ /dev/null @@ -1,24 +0,0 @@ -package com.dronex.rec.recording - -enum class RecordingState { - IDLE, - PREVIEWING, - RECORDING, - STOPPING, - ERROR, -} - -data class RecordingStatus( - val state: RecordingState, - val outputPath: String? = null, - val elapsedMillis: Long = 0L, - val message: String? = null, -) { - fun toMap(): Map = - mapOf( - "state" to state.name.lowercase(), - "outputPath" to outputPath, - "elapsedMillis" to elapsedMillis, - "message" to message, - ) -} diff --git a/assets/html/index.html b/assets/html/index.html new file mode 100644 index 0000000..d791f2f --- /dev/null +++ b/assets/html/index.html @@ -0,0 +1,47 @@ + + + + + + + Document + + + + + + + + + + + + + \ No newline at end of file diff --git a/devtools_options.yaml b/devtools_options.yaml index fa0b357..17fa745 100644 --- a/devtools_options.yaml +++ b/devtools_options.yaml @@ -1,3 +1,5 @@ description: This file stores settings for Dart & Flutter DevTools. documentation: https://docs.flutter.dev/tools/devtools/extensions#configure-extension-enablement-states extensions: + - riverpod: true + - shared_preferences: true \ No newline at end of file diff --git a/ios/Runner/PlatformInfoPlugin.swift b/ios/Runner/PlatformInfoPlugin.swift index f219908..5b5de45 100644 --- a/ios/Runner/PlatformInfoPlugin.swift +++ b/ios/Runner/PlatformInfoPlugin.swift @@ -62,6 +62,7 @@ final class PlatformInfoPlugin: NSObject, FlutterPlugin { let device = UIDevice.current return [ "platform": "ios", + "deviceCode": "", "brand": device.systemName, "model": machineIdentifier(), "systemVersion": device.systemVersion, diff --git a/lib/app/app.dart b/lib/app/app.dart index 5d3ffda..3f9659f 100644 --- a/lib/app/app.dart +++ b/lib/app/app.dart @@ -1,46 +1,16 @@ import 'package:flutter/material.dart'; import 'package:flutter_easyloading/flutter_easyloading.dart'; import 'package:flutter_localizations/flutter_localizations.dart'; -import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter_screenutil/flutter_screenutil.dart'; import 'package:pull_to_refresh/pull_to_refresh.dart'; import 'package:recording_tool/app/config/app_config.dart'; import 'package:recording_tool/app/router/app_navigator.dart'; import 'package:recording_tool/app/theme/app_theme.dart'; import 'package:recording_tool/features/auth/pages/page_auth.dart'; -import 'package:recording_tool/features/recording/view-model/view_model_recording.dart'; -class FlutterTemplateApp extends ConsumerStatefulWidget { +class FlutterTemplateApp extends StatelessWidget { const FlutterTemplateApp({super.key}); - @override - ConsumerState createState() => _FlutterTemplateAppState(); -} - -class _FlutterTemplateAppState extends ConsumerState - with WidgetsBindingObserver { - @override - void initState() { - super.initState(); - WidgetsBinding.instance.addObserver(this); - WidgetsBinding.instance.addPostFrameCallback((_) { - ref.read(recordingViewModelProvider.notifier).getClipboardContent(); - }); - } - - @override - void didChangeAppLifecycleState(AppLifecycleState state) { - if (state == AppLifecycleState.resumed) { - ref.read(recordingViewModelProvider.notifier).getClipboardContent(); - } - } - - @override - void dispose() { - WidgetsBinding.instance.removeObserver(this); - super.dispose(); - } - @override Widget build(BuildContext context) { return ScreenUtilInit( diff --git a/lib/app/config/api_common.dart b/lib/app/config/api_common.dart new file mode 100644 index 0000000..0f52718 --- /dev/null +++ b/lib/app/config/api_common.dart @@ -0,0 +1,16 @@ +enum AuthApi { + /// 获取 token + getToken('/api/events/device/token'), + + /// 获取推流地址 + getStreamKey('/api/events/device/stream/key'), + + /// 根据赛事目录获取视频列表 + getRecordList('/api/files'), + + /// 获取选手的赛事信息 + playerRegistrationList('/api/events/device/player/registration/list'); + + final String path; + const AuthApi(this.path); +} diff --git a/lib/app/config/app_config.dart b/lib/app/config/app_config.dart index 202c45c..162758c 100644 --- a/lib/app/config/app_config.dart +++ b/lib/app/config/app_config.dart @@ -32,7 +32,7 @@ class AppConfig { current = switch (environment) { AppEnvironment.dev => const EnvironmentValues( environment: AppEnvironment.dev, - baseUrl: 'https://example.com/api', + baseUrl: 'http://192.168.1.104:8000', enableNetworkLog: true, ), AppEnvironment.staging => const EnvironmentValues( diff --git a/lib/app/router/app_navigator.dart b/lib/app/router/app_navigator.dart index 63d5e98..a517ab4 100644 --- a/lib/app/router/app_navigator.dart +++ b/lib/app/router/app_navigator.dart @@ -103,10 +103,7 @@ class AppNavigator { } static void pop({BuildContext? context, T? result}) { - Navigator.of( - context ?? AppNavigator.context!, - rootNavigator: true, - ).pop(result); + Navigator.maybePop(context ?? AppNavigator.context!); } static void popTimes({BuildContext? context, int count = 1}) { diff --git a/lib/core/network/api_client.dart b/lib/core/network/api_client.dart index 3acfdfd..3c6991e 100644 --- a/lib/core/network/api_client.dart +++ b/lib/core/network/api_client.dart @@ -108,6 +108,7 @@ class ApiClient { final statusCode = error.response?.statusCode; final message = switch (error.type) { DioExceptionType.connectionTimeout => '网络连接超时', + DioExceptionType.transformTimeout => '网络请求处理超时', DioExceptionType.sendTimeout => '请求发送超时', DioExceptionType.receiveTimeout => '响应接收超时', DioExceptionType.badCertificate => '证书校验失败', diff --git a/lib/core/network/api_response.dart b/lib/core/network/api_response.dart index bcd55d9..1f9fb46 100644 --- a/lib/core/network/api_response.dart +++ b/lib/core/network/api_response.dart @@ -5,7 +5,7 @@ class ApiResponse { final String message; final T? data; - bool get isSuccess => code >= 200 && code < 300; + bool get isSuccess => code == 0 || code >= 200 && code < 300; factory ApiResponse.fromJson( Map json, { diff --git a/lib/core/network/header_interceptor.dart b/lib/core/network/header_interceptor.dart index 87f29dc..3723809 100644 --- a/lib/core/network/header_interceptor.dart +++ b/lib/core/network/header_interceptor.dart @@ -28,4 +28,15 @@ class HeaderInterceptor extends Interceptor { handler.next(options); } + + @override + Future onError( + DioException err, + ErrorInterceptorHandler handler, + ) async { + if (err.response?.statusCode == 401) { + await AppStorage.remove(StorageKeys.authToken); + } + handler.next(err); + } } diff --git a/lib/core/platform/app_platform_info.dart b/lib/core/platform/app_platform_info.dart index 3f70f66..830839c 100644 --- a/lib/core/platform/app_platform_info.dart +++ b/lib/core/platform/app_platform_info.dart @@ -31,6 +31,7 @@ class AppDeviceInfo { required this.platform, required this.isPhysicalDevice, required this.values, + required this.deviceCode, }); factory AppDeviceInfo.fromMap(Map map) { @@ -48,12 +49,14 @@ class AppDeviceInfo { platform: map['platform'] as String? ?? Platform.operatingSystem, isPhysicalDevice: isPhysicalDevice is bool ? isPhysicalDevice : true, values: values, + deviceCode: values['deviceCode'] ?? '', ); } final String platform; final bool isPhysicalDevice; final Map values; + final String deviceCode; } class AppPlatformInfo { diff --git a/lib/core/utils/device_utils.dart b/lib/core/utils/device_utils.dart index 73a8f4f..e08b528 100644 --- a/lib/core/utils/device_utils.dart +++ b/lib/core/utils/device_utils.dart @@ -28,4 +28,12 @@ class DeviceUtils { } return (await AppPlatformInfo.deviceInfo()).values; } + + static Future deviceCode() async { + try { + return (await AppPlatformInfo.deviceInfo()).deviceCode.trim(); + } catch (_) { + return ''; + } + } } diff --git a/lib/features/auth/model/model_auth.dart b/lib/features/auth/model/model_auth.dart new file mode 100644 index 0000000..9ff9118 --- /dev/null +++ b/lib/features/auth/model/model_auth.dart @@ -0,0 +1,81 @@ +/// 获取 TOKEN 响应模型 +class GetTokenResModel { + GetTokenResModel({required this.deviceAccessToken}); + + final String deviceAccessToken; + + factory GetTokenResModel.fromJson(Map json) { + return GetTokenResModel( + deviceAccessToken: (json['deviceAccessToken'] ?? '').toString(), + ); + } + + Map toJson() { + return {'deviceAccessToken': deviceAccessToken}; + } +} + +/// 查看录像响应模型 +class GetRecordListResModel { + String? path; + List? items; + + GetRecordListResModel({this.path, this.items}); + + factory GetRecordListResModel.fromJson(Map json) => + GetRecordListResModel( + path: json['path'], + items: json['items'] == null + ? [] + : List.from( + json['items']!.map((x) => RecordListItem.fromJson(x)), + ), + ); + + Map toJson() => { + 'path': path, + 'items': items == null + ? [] + : List.from(items!.map((x) => x.toJson())), + }; +} + +class RecordListItem { + String? name; + String? path; + String? type; + int? size; + DateTime? modTime; + String? url; + String? extension; + + RecordListItem({ + this.name, + this.path, + this.type, + this.size, + this.modTime, + this.url, + this.extension, + }); + + factory RecordListItem.fromJson(Map json) => RecordListItem( + name: json['name'] ?? '', + path: json['path'] ?? '', + type: json['type'] ?? '', + size: json['size'] ?? 0, + modTime: json['modTime'] == null ? null : DateTime.parse(json['modTime']), + url: json['url'] ?? '', + extension: json['extension'] ?? '', + ); + + Map toJson() => { + 'name': name, + 'path': path, + 'type': type, + 'size': size, + 'modTime': modTime?.toIso8601String(), + 'url': url, + 'extension': extension, + }; +} diff --git a/lib/features/auth/model/model_jwt.dart b/lib/features/auth/model/model_jwt.dart new file mode 100644 index 0000000..1388741 --- /dev/null +++ b/lib/features/auth/model/model_jwt.dart @@ -0,0 +1,56 @@ +// To parse this JSON data, do +// +// final jwtDecodedData = jwtDecodedDataFromJson(jsonString); + +import 'dart:convert'; + +JwtDecodedData jwtDecodedDataFromJson(String str) => + JwtDecodedData.fromJson(json.decode(str)); + +String jwtDecodedDataToJson(JwtDecodedData data) => json.encode(data.toJson()); + +class JwtDecodedData { + String? authType; + String? deviceCode; + int? deviceId; + String? deviceRole; + String? eventName; + double? oId; + List? oIds; + double? organizerId; + + JwtDecodedData({ + this.authType, + this.deviceCode, + this.deviceId, + this.deviceRole, + this.eventName, + this.oId, + this.oIds, + this.organizerId, + }); + + factory JwtDecodedData.fromJson(Map json) => JwtDecodedData( + authType: json["authType"], + deviceCode: json["deviceCode"], + deviceId: json["deviceId"], + deviceRole: json["deviceRole"], + eventName: json["eventName"], + oId: json["oId"]?.toDouble(), + oIds: json["oIds"] == null + ? [] + : List.from(json["oIds"]!.map((x) => x?.toDouble())), + organizerId: json["organizerId"]?.toDouble(), + ); + + Map toJson() => { + "authType": authType, + "deviceCode": deviceCode, + "deviceId": deviceId, + "deviceRole": deviceRole, + "eventName": eventName, + "oId": oId, + "oIds": oIds == null ? [] : List.from(oIds!.map((x) => x)), + "organizerId": organizerId, + }; +} diff --git a/lib/features/auth/pages/page_auth.dart b/lib/features/auth/pages/page_auth.dart index 63e3dac..dd04216 100644 --- a/lib/features/auth/pages/page_auth.dart +++ b/lib/features/auth/pages/page_auth.dart @@ -1,46 +1,89 @@ import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter_screenutil/flutter_screenutil.dart'; import 'package:recording_tool/app/router/app_navigator.dart'; +import 'package:recording_tool/core/cache/app_storage.dart'; +import 'package:recording_tool/core/cache/storage_keys.dart'; +import 'package:recording_tool/features/auth/view_model_auth/view_model_auth.dart'; import 'package:recording_tool/features/scan_qrcode/pages/page_scan_qrcode.dart'; import 'package:recording_tool/shared/widgets/widgets.dart'; -class AuthPageWidget extends StatefulWidget { +class AuthPageWidget extends ConsumerStatefulWidget { const AuthPageWidget({super.key}); @override - State createState() => _AuthPageWidgetState(); + ConsumerState createState() => _AuthPageWidgetState(); } -class _AuthPageWidgetState extends State { +class _AuthPageWidgetState extends ConsumerState { + late TextEditingController? _controller; + + @override + void initState() { + super.initState(); + _controller = TextEditingController(); + _controller?.text = '555'; + + WidgetsBinding.instance.addPostFrameCallback((_) async { + final token = AppStorage.getString(StorageKeys.authToken); + if (token?.isNotEmpty ?? false) { + AppNavigator.pushReplacement(const ScanQrCodePage()); + } + }); + } + + @override + void dispose() { + _controller?.dispose(); + super.dispose(); + } + @override Widget build(BuildContext context) { + final authState = ref.watch(authProvider); + return Center( child: Column( children: [ SizedBox(height: 180.h), - Text('裁判工作台', style: TextStyle(fontSize: 50, color: Colors.black)), + AppText('裁判工作台', fontSize: 30.sp), SizedBox(height: 20.h), Text( - 'Auth Page', - style: TextStyle(fontSize: 30, color: Colors.black), + '输入执裁口令', + style: TextStyle(fontSize: 18.sp, color: Colors.black), ), SizedBox(height: 20.h), - SizedBox( - width: 280.w, - height: 80.h, - child: AppTextField(initialValue: 'hhh'), - ), - SizedBox(height: 20.h), - SizedBox( - width: 280.w, - height: 80.h, - child: AppButton( - label: '确定', - onPressed: () { - AppNavigator.push(const ScanQrCodePage()); - }, - variant: AppButtonVariant.secondary, + Container( + padding: EdgeInsets.symmetric(horizontal: 20.w), + child: Column( + children: [ + AppTextField(controller: _controller), + SizedBox(height: 20.h), + SizedBox( + width: double.maxFinite, + child: AppButton( + label: '确定', + onPressed: () async { + final code = _controller?.text; + final success = await ref + .read(authProvider.notifier) + .auth(code ?? ''); + if (!mounted) return; + if (success) { + AppNavigator.push(const ScanQrCodePage()); + return; + } + final message = ref.read(authProvider).errorMessage; + if (message != null && message.isNotEmpty) { + AppToast.show(message); + } + }, + variant: AppButtonVariant.secondary, + isLoading: authState.isLoading, + ), + ), + ], ), ), ], diff --git a/lib/features/auth/server/server_auth.dart b/lib/features/auth/server/server_auth.dart new file mode 100644 index 0000000..2c3ad90 --- /dev/null +++ b/lib/features/auth/server/server_auth.dart @@ -0,0 +1,44 @@ +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:recording_tool/app/config/api_common.dart'; +import 'package:recording_tool/core/network/providers/dio_providers.dart'; +import 'package:recording_tool/core/utils/device_utils.dart'; +import 'package:recording_tool/features/auth/model/model_auth.dart'; + +class AuthServer { + /// [passCode] 口令码 + static Future login(String passCode, Ref ref) async { + final deviceCode = await DeviceUtils.deviceCode(); + if (deviceCode.isEmpty) { + throw const FormatException('无法获取设备标识'); + } + + final apiClient = ref.read(apiClientProvider); + final data = await apiClient.post( + AuthApi.getToken.path, + data: {'deviceCode': deviceCode, 'passCode': passCode}, + parser: (json) => GetTokenResModel.fromJson(json as Map), + ); + + if (data.deviceAccessToken.isEmpty) { + throw const FormatException('登录响应缺少 TOKEN'); + } + + return data; + } + + /// 获取赛事列表 + /// [path] 赛事目录 + static Future getRecordList( + Ref ref, + String path, + ) async { + final apiClient = ref.read(apiClientProvider); + final data = await apiClient.get( + 'http://sheling.local:9001/${AuthApi.getRecordList.path}', + queryParameters: {'path': path}, + parser: (json) => + GetRecordListResModel.fromJson(json as Map), + ); + return data; + } +} diff --git a/lib/features/auth/state/state_auth.dart b/lib/features/auth/state/state_auth.dart new file mode 100644 index 0000000..31b1251 --- /dev/null +++ b/lib/features/auth/state/state_auth.dart @@ -0,0 +1,33 @@ +import 'package:recording_tool/features/auth/model/model_auth.dart'; +import 'package:recording_tool/features/auth/model/model_jwt.dart'; + +class AuthState { + const AuthState({ + this.isLoading = false, + this.errorMessage, + this.jwtDecodedData, + this.recordList, + }); + + final bool isLoading; + final String? errorMessage; + + /// 解析后的 TOKEN 数据 + final JwtDecodedData? jwtDecodedData; + + /// 赛事列表 + final List? recordList; + + AuthState copyWith({ + bool? isLoading, + String? errorMessage, + JwtDecodedData? jwtDecodedData, + List? recordList, + }) { + return AuthState( + isLoading: isLoading ?? this.isLoading, + errorMessage: errorMessage ?? this.errorMessage, + jwtDecodedData: jwtDecodedData ?? this.jwtDecodedData, + ); + } +} diff --git a/lib/features/auth/view_model_auth/view_model_auth.dart b/lib/features/auth/view_model_auth/view_model_auth.dart new file mode 100644 index 0000000..906a7e2 --- /dev/null +++ b/lib/features/auth/view_model_auth/view_model_auth.dart @@ -0,0 +1,68 @@ +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_riverpod/legacy.dart'; +import 'package:jwt_decoder/jwt_decoder.dart'; +import 'package:recording_tool/core/cache/app_storage.dart'; +import 'package:recording_tool/core/cache/storage_keys.dart'; +import 'package:recording_tool/core/network/api_exception.dart'; +import 'package:recording_tool/features/auth/model/model_jwt.dart'; +import 'package:recording_tool/features/auth/server/server_auth.dart'; +import 'package:recording_tool/features/auth/state/state_auth.dart'; + +final authProvider = + StateNotifierProvider.autoDispose((ref) { + return AuthViewModel(ref); + }); + +class AuthViewModel extends StateNotifier { + AuthViewModel(this._ref) : super(const AuthState()); + final Ref _ref; + + /// 鉴权获取 token + Future auth(String code) async { + final passCode = code.trim(); + if (passCode.isEmpty) { + state = const AuthState(errorMessage: '请输入执裁口令'); + return false; + } + + state = const AuthState(isLoading: true); + try { + final data = await AuthServer.login(passCode, _ref); + await AppStorage.setString(StorageKeys.authToken, data.deviceAccessToken); + state = const AuthState(); + if (data.deviceAccessToken.isNotEmpty) { + parseTokenSetState(data.deviceAccessToken); + } + return true; + } on FormatException catch (error) { + state = AuthState(errorMessage: error.message); + return false; + } on ApiException catch (error) { + state = AuthState(errorMessage: error.message); + return false; + } catch (_) { + state = const AuthState(errorMessage: '认证失败,请重试'); + return false; + } + } + + /// 解析 TOKEN,并更新状态 + Future parseTokenSetState(String token) async { + final decoded = JwtDecoder.decode(token); + if (decoded['data'] != null && decoded['data'] is Map) { + final data = JwtDecodedData.fromJson(decoded['data']); + state = state.copyWith(jwtDecodedData: data); + return true; + } + return false; + } + + /// 获取赛事列表 + Future getRecordList(String eventName) async { + if (eventName.isEmpty) return false; + final data = await AuthServer.getRecordList(_ref, eventName); + if (data.items == null || data.items!.isEmpty) return false; + state = state.copyWith(recordList: data.items); + return true; + } +} diff --git a/lib/features/events/model/model_event_info.dart b/lib/features/events/model/model_event_info.dart new file mode 100644 index 0000000..d725139 --- /dev/null +++ b/lib/features/events/model/model_event_info.dart @@ -0,0 +1,356 @@ +import 'package:recording_tool/features/recording/model/model_recording_context.dart'; + +class PlayerRegistrationListReq { + const PlayerRegistrationListReq({required this.userId, this.status = ''}); + + final String userId; + final String status; + + Map toFormDataMap() { + return {'userId': userId, 'status': status}; + } +} + +class StreamKeyReq { + const StreamKeyReq({ + required this.eventId, + required this.itemId, + required this.userId, + }); + + final String eventId; + final String itemId; + final String userId; + + Map toFormDataMap() { + return {'eventId': eventId, 'itemId': itemId, 'userId': userId}; + } +} + +class EventProfile { + const EventProfile({ + required this.name, + required this.phone, + required this.eventTitle, + this.avatarUrl = '', + this.avatarLabel = '头像', + }); + + final String name; + final String phone; + final String eventTitle; + final String avatarUrl; + final String avatarLabel; +} + +class EventRegistrationList { + const EventRegistrationList({ + required this.userId, + required this.name, + required this.avatar, + required this.total, + required this.items, + }); + + final String userId; + final String name; + final String avatar; + final int total; + final List items; + + factory EventRegistrationList.fromJson(dynamic json) { + final map = _extractObject(json); + final rawItems = _extractList(json); + final userId = _readString(map, const ['userId']); + final name = _readString(map, const [ + 'name', + 'playerName', + 'userName', + 'realName', + ]); + final avatar = _readString(map, const ['avatar', 'avatarUrl']); + return EventRegistrationList( + userId: userId, + name: name, + avatar: avatar, + total: _readInt(map, const ['total'], fallback: rawItems.length), + items: rawItems + .whereType() + .map( + (item) => EventRegistrationItem.fromJson( + item, + userId: userId, + playerName: name, + ), + ) + .toList(), + ); + } + + EventProfile toProfile() { + return EventProfile( + name: name, + phone: '', + eventTitle: items.isEmpty ? '赛事信息' : items.first.eventTitle, + avatarUrl: avatar, + ); + } +} + +class EventRegistrationItem { + const EventRegistrationItem({ + required this.eventId, + required this.itemId, + required this.userId, + required this.eventTitle, + required this.name, + required this.group, + required this.venue, + required this.time, + required this.playerName, + required this.playerPhone, + this.avatarLabel = '头像', + this.matchStartTime = '', + this.matchEndTime = '', + this.completed = false, + this.laneNo, + this.status, + this.rawData = const {}, + }); + + final String eventId; + final String itemId; + final String userId; + final String eventTitle; + final String name; + final String group; + final String venue; + final String time; + final String playerName; + final String playerPhone; + final String avatarLabel; + final String matchStartTime; + final String matchEndTime; + final bool completed; + final String? laneNo; + final String? status; + final Map rawData; + + factory EventRegistrationItem.fromJson( + Map json, { + String userId = '', + String playerName = '', + }) { + final map = Map.from(json); + final startTime = _readString(map, const ['matchStartTime', 'startTime']); + final endTime = _readString(map, const ['matchEndTime', 'endTime']); + final completed = _readBool(map, const ['completed']); + return EventRegistrationItem( + eventId: _readString(map, const ['eventId', 'eventsId', 'eventID']), + itemId: _readString(map, const ['itemId', 'eventItemId', 'itemID']), + userId: _readString(map, const [ + 'userId', + 'playerId', + 'registrationId', + ], fallback: userId), + eventTitle: _readString(map, const [ + 'eventTitle', + 'eventName', + 'competitionName', + 'matchTitle', + ], fallback: '赛事信息'), + name: _readString(map, const [ + 'name', + 'itemName', + 'eventItemName', + 'matchName', + 'projectName', + ], fallback: '未命名项目'), + group: _readString(map, const [ + 'group', + 'groupName', + 'categoryName', + 'levelName', + ]), + venue: _readString(map, const [ + 'matchPlace', + 'venue', + 'venueName', + 'siteName', + 'fieldName', + 'placeName', + ]), + time: _readScheduleTime(map, startTime, endTime), + playerName: _readString(map, const [ + 'playerName', + 'userName', + 'nameCn', + 'realName', + 'athleteName', + ], fallback: playerName), + playerPhone: _readString(map, const [ + 'playerPhone', + 'phone', + 'mobile', + 'telephone', + 'userPhone', + ]), + laneNo: _readNullableString(map, const [ + 'laneNo', + 'laneNumber', + 'trackNo', + 'number', + 'serialNo', + ]), + matchStartTime: startTime, + matchEndTime: endTime, + completed: completed, + status: completed ? '已完成' : null, + rawData: map, + ); + } + + EventProfile toProfile() { + return EventProfile( + avatarLabel: avatarLabel, + name: playerName, + phone: playerPhone, + eventTitle: eventTitle, + ); + } + + RecordingContext toRecordingContext({EventProfile? profile}) { + return RecordingContext( + eventTitle: eventTitle, + matchName: name, + group: group, + venue: venue, + time: time, + playerName: profile?.name ?? playerName, + playerPhone: profile?.phone ?? playerPhone, + laneNo: laneNo, + status: status, + ); + } +} + +class StreamKeyResponse { + const StreamKeyResponse({required this.rawData}); + + final Map rawData; + + factory StreamKeyResponse.fromJson(dynamic json) { + if (json is Map) { + return StreamKeyResponse(rawData: Map.from(json)); + } + return StreamKeyResponse(rawData: {'value': json}); + } + + @override + String toString() => rawData.toString(); +} + +List _extractList(dynamic json) { + if (json is List) return json; + if (json is Map) { + for (final key in const ['records', 'items', 'rows', 'list', 'data']) { + final value = json[key]; + if (value is List) return value; + if (value is Map) { + final nested = _extractList(value); + if (nested.isNotEmpty) return nested; + } + } + } + return const []; +} + +Map _extractObject(dynamic json) { + if (json is Map) { + final map = Map.from(json); + final data = map['data']; + if (data is Map) return Map.from(data); + return map; + } + return const {}; +} + +String _readString( + Map map, + List keys, { + String fallback = '', +}) { + return _readNullableString(map, keys) ?? fallback; +} + +String _readScheduleTime( + Map map, + String startTime, + String endTime, +) { + if (startTime.isNotEmpty && endTime.isNotEmpty) { + return '$startTime-$endTime'; + } + if (startTime.isNotEmpty) return startTime; + if (endTime.isNotEmpty) return endTime; + return _readString(map, const [ + 'time', + 'competitionTime', + 'matchTime', + 'scheduleTime', + ]); +} + +int _readInt(Map map, List keys, {int fallback = 0}) { + for (final key in keys) { + final value = _findValue(map, key); + if (value is int) return value; + if (value is num) return value.toInt(); + if (value is String) { + final parsed = int.tryParse(value.trim()); + if (parsed != null) return parsed; + } + } + return fallback; +} + +bool _readBool(Map map, List keys) { + for (final key in keys) { + final value = _findValue(map, key); + if (value is bool) return value; + if (value is num) return value != 0; + if (value is String) { + final text = value.trim().toLowerCase(); + if (text == 'true' || text == '1') return true; + if (text == 'false' || text == '0') return false; + } + } + return false; +} + +String? _readNullableString(Map map, List keys) { + for (final key in keys) { + final value = _findValue(map, key); + if (value == null) continue; + final text = value.toString().trim(); + if (text.isNotEmpty) return text; + } + return null; +} + +dynamic _findValue(dynamic value, String key) { + if (value is Map) { + if (value.containsKey(key)) return value[key]; + for (final child in value.values) { + final found = _findValue(child, key); + if (found != null) return found; + } + } + if (value is List) { + for (final child in value) { + final found = _findValue(child, key); + if (found != null) return found; + } + } + return null; +} diff --git a/lib/features/events/pages/page_event_info.dart b/lib/features/events/pages/page_event_info.dart new file mode 100644 index 0000000..4d7220f --- /dev/null +++ b/lib/features/events/pages/page_event_info.dart @@ -0,0 +1,361 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_screenutil/flutter_screenutil.dart'; +import 'package:recording_tool/app/router/app_navigator.dart'; +import 'package:recording_tool/features/events/model/model_event_info.dart'; +import 'package:recording_tool/features/events/state/state_event_info.dart'; +import 'package:recording_tool/features/events/view_model/view_model_event_info.dart'; +import 'package:recording_tool/features/recording/pages/page_record.dart'; +import 'package:recording_tool/shared/widgets/widgets.dart'; + +class EventInfoPage extends ConsumerStatefulWidget { + const EventInfoPage({super.key, required this.playerId}); + final String playerId; + static const mockRtmpUrl = + 'rtmp://192.168.1.245:19090/蔡依婷vs夏志豪_空中格斗赛_高中组/蔡依婷vs夏志豪_空中格斗赛_高中组'; + + @override + ConsumerState createState() => _EventInfoPageState(); +} + +class _EventInfoPageState extends ConsumerState { + @override + void initState() { + super.initState(); + WidgetsBinding.instance.addPostFrameCallback((_) { + if (!mounted) return; + ref.read(eventInfoProvider.notifier).loadRegistrationList(); + }); + } + + Future onItemTap(EventRegistrationItem item) async { + debugPrint('item tapped: ${item.name}'); + await ref.read(eventInfoProvider.notifier).requestStreamKey(item); + if (!mounted) return; + final profile = ref.read(eventInfoProvider).profile; + AppNavigator.push( + RecordingPage( + recordingContext: item.toRecordingContext(profile: profile), + streamUrl: EventInfoPage.mockRtmpUrl, + ), + ); + } + + @override + Widget build(BuildContext context) { + final state = ref.watch(eventInfoProvider); + final profile = state.profile; + + return Scaffold( + backgroundColor: Colors.white, + body: SafeArea( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + _Header(onBack: () => AppNavigator.pop(context: context)), + Expanded( + child: SingleChildScrollView( + padding: EdgeInsets.fromLTRB(62.w, 8.h, 62.w, 40.h), + child: Column( + children: [ + _ProfileSection(profile: profile), + SizedBox(height: 20.h), + Text( + state.eventTitle, + style: TextStyle( + fontSize: 20.sp, + height: 1.2, + color: const Color(0xFF2F2F2F), + fontWeight: FontWeight.w500, + ), + ), + SizedBox(height: 24.h), + SizedBox( + height: 400.h, + child: _ScheduleList( + state: state, + onRetry: () => ref + .read(eventInfoProvider.notifier) + .loadRegistrationList(), + onItemTap: onItemTap, + ), + ), + ], + ), + ), + ), + ], + ), + ), + ); + } +} + +class _Header extends StatelessWidget { + const _Header({required this.onBack}); + + final VoidCallback onBack; + + @override + Widget build(BuildContext context) { + return SizedBox( + height: 52.h, + child: Align( + alignment: Alignment.centerLeft, + child: IconButton( + onPressed: onBack, + icon: Icon(Icons.arrow_back_ios_new, size: 32.r), + color: Colors.black, + tooltip: '返回', + padding: EdgeInsets.only(left: 16.w), + constraints: BoxConstraints(minWidth: 56.w, minHeight: 52.h), + ), + ), + ); + } +} + +class _ProfileSection extends StatelessWidget { + const _ProfileSection({required this.profile}); + + final EventProfile profile; + + @override + Widget build(BuildContext context) { + return Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + profile.avatarUrl.isEmpty + ? AppAvatar(size: 50.r) + : AppAvatar(size: 50.r, imageUrl: profile.avatarUrl), + + SizedBox(width: 28.w), + Expanded( + child: Padding( + padding: EdgeInsets.only(top: 30.h), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + profile.name, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle( + fontSize: 22.sp, + height: 1.2, + color: const Color(0xFF2F2F2F), + ), + ), + SizedBox(height: 36.h), + Text( + profile.phone, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle( + fontSize: 22.sp, + height: 1.2, + color: const Color(0xFF2F2F2F), + ), + ), + ], + ), + ), + ), + ], + ); + } +} + +class _ScheduleList extends StatelessWidget { + const _ScheduleList({ + required this.state, + required this.onRetry, + required this.onItemTap, + }); + + final EventInfoState state; + final VoidCallback onRetry; + final ValueChanged onItemTap; + + @override + Widget build(BuildContext context) { + if (state.isLoading) { + return const Center(child: CircularProgressIndicator()); + } + + if (state.items.isEmpty) { + return Center( + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + Text( + state.errorMessage ?? '暂无赛事报名信息', + textAlign: TextAlign.center, + style: TextStyle(fontSize: 18.sp, color: const Color(0xFF2F2F2F)), + ), + SizedBox(height: 18.h), + TextButton(onPressed: onRetry, child: const Text('重新加载')), + ], + ), + ); + } + + return ListView.builder( + itemCount: state.items.length, + itemBuilder: (context, index) { + final item = state.items[index]; + return _ScheduleCard(item: item, onTap: () => onItemTap(item)); + }, + ); + } +} + +class _ScheduleCard extends StatelessWidget { + const _ScheduleCard({required this.item, required this.onTap}); + + final EventRegistrationItem item; + final VoidCallback onTap; + + @override + Widget build(BuildContext context) { + return Material( + color: Colors.white, + child: InkWell( + onTap: onTap, + child: Container( + constraints: BoxConstraints(minHeight: 138.h), + padding: EdgeInsets.fromLTRB(10.w, 14.h, 14.w, 0), + decoration: BoxDecoration( + border: Border.all(color: const Color(0xFF7A7A7A)), + ), + child: Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + item.group.isEmpty + ? item.name + : '${item.name} (${item.group})', + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle( + fontSize: 20.sp, + height: 1.2, + color: const Color(0xFF2F2F2F), + fontWeight: FontWeight.w500, + ), + ), + SizedBox(height: 26.h), + Text( + item.venue, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle( + fontSize: 20.sp, + height: 1.2, + color: const Color(0xFF2F2F2F), + ), + ), + SizedBox(height: 26.h), + Text( + item.time, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle( + fontSize: 20.sp, + height: 1.2, + color: const Color(0xFF2F2F2F), + ), + ), + ], + ), + ), + SizedBox(width: 12.w), + SizedBox( + width: 148.w, + height: 120.h, + child: Align( + alignment: Alignment.center, + child: _ScheduleBadge(item: item), + ), + ), + ], + ), + ), + ), + ); + } +} + +class _ScheduleBadge extends StatelessWidget { + const _ScheduleBadge({required this.item}); + + final EventRegistrationItem item; + + @override + Widget build(BuildContext context) { + if (item.status != null) { + return CustomPaint( + painter: _CutCornerBorderPainter(color: const Color(0xFF7A7A7A)), + child: SizedBox( + width: 148.w, + height: 90.h, + child: Center( + child: Text( + item.status!, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle(fontSize: 20.sp, color: const Color(0xFF2F2F2F)), + ), + ), + ), + ); + } + + return Text( + item.laneNo ?? '', + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle( + fontSize: 34.sp, + height: 1, + color: const Color(0xFF2F2F2F), + fontWeight: FontWeight.w700, + ), + ); + } +} + +class _CutCornerBorderPainter extends CustomPainter { + const _CutCornerBorderPainter({required this.color}); + + final Color color; + + @override + void paint(Canvas canvas, Size size) { + final side = 12.r; + final path = Path() + ..moveTo(side, 0) + ..lineTo(size.width - side, 0) + ..lineTo(size.width, side) + ..lineTo(size.width, size.height - side) + ..lineTo(size.width - side, size.height) + ..lineTo(side, size.height) + ..lineTo(0, size.height - side) + ..lineTo(0, side) + ..close(); + final paint = Paint() + ..style = PaintingStyle.stroke + ..strokeWidth = 1 + ..color = color; + canvas.drawPath(path, paint); + } + + @override + bool shouldRepaint(covariant _CutCornerBorderPainter oldDelegate) { + return oldDelegate.color != color; + } +} diff --git a/lib/features/events/server/server_events.dart b/lib/features/events/server/server_events.dart new file mode 100644 index 0000000..f7772b1 --- /dev/null +++ b/lib/features/events/server/server_events.dart @@ -0,0 +1,37 @@ +import 'package:dio/dio.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:recording_tool/app/config/api_common.dart'; +import 'package:recording_tool/core/network/api_client.dart'; +import 'package:recording_tool/core/network/http_method.dart'; +import 'package:recording_tool/core/network/providers/dio_providers.dart'; +import 'package:recording_tool/features/events/model/model_event_info.dart'; + +final eventsServerProvider = Provider((ref) { + return EventsServer(ref.watch(apiClientProvider)); +}); + +class EventsServer { + const EventsServer(this._apiClient); + + final ApiClient _apiClient; + + Future fetchPlayerRegistrationList( + PlayerRegistrationListReq req, + ) { + return _apiClient.request( + AuthApi.playerRegistrationList.path, + method: HttpMethod.get, + data: FormData.fromMap(req.toFormDataMap()), + parser: EventRegistrationList.fromJson, + ); + } + + Future fetchStreamKey(StreamKeyReq req) { + return _apiClient.request( + AuthApi.getStreamKey.path, + method: HttpMethod.get, + data: FormData.fromMap(req.toFormDataMap()), + parser: StreamKeyResponse.fromJson, + ); + } +} diff --git a/lib/features/events/state/state_event_info.dart b/lib/features/events/state/state_event_info.dart new file mode 100644 index 0000000..ac5c827 --- /dev/null +++ b/lib/features/events/state/state_event_info.dart @@ -0,0 +1,44 @@ +import 'package:recording_tool/features/events/model/model_event_info.dart'; + +class EventInfoState { + const EventInfoState({ + this.isLoading = false, + this.isRequestingStreamKey = false, + this.errorMessage, + this.profile = const EventProfile(name: '', phone: '', eventTitle: '赛事信息'), + this.total = 0, + this.items = const [], + }); + + final bool isLoading; + final bool isRequestingStreamKey; + final String? errorMessage; + final EventProfile profile; + final int total; + final List items; + + String get eventTitle => + items.isEmpty ? profile.eventTitle : items.first.eventTitle; + + EventInfoState copyWith({ + bool? isLoading, + bool? isRequestingStreamKey, + String? errorMessage, + bool clearErrorMessage = false, + EventProfile? profile, + int? total, + List? items, + }) { + return EventInfoState( + isLoading: isLoading ?? this.isLoading, + isRequestingStreamKey: + isRequestingStreamKey ?? this.isRequestingStreamKey, + errorMessage: clearErrorMessage + ? null + : (errorMessage ?? this.errorMessage), + profile: profile ?? this.profile, + total: total ?? this.total, + items: items ?? this.items, + ); + } +} diff --git a/lib/features/events/view_model/view_model_event_info.dart b/lib/features/events/view_model/view_model_event_info.dart new file mode 100644 index 0000000..d8e6051 --- /dev/null +++ b/lib/features/events/view_model/view_model_event_info.dart @@ -0,0 +1,85 @@ +import 'package:flutter/foundation.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_riverpod/legacy.dart'; +import 'package:recording_tool/core/network/api_exception.dart'; +import 'package:recording_tool/features/events/model/model_event_info.dart'; +import 'package:recording_tool/features/events/server/server_events.dart'; +import 'package:recording_tool/features/events/state/state_event_info.dart'; + +final eventInfoProvider = + StateNotifierProvider((ref) { + return EventInfoViewModel(ref); + }); + +class EventInfoViewModel extends StateNotifier { + EventInfoViewModel(this._ref) : super(const EventInfoState()); + + static const defaultRegistrationRequest = PlayerRegistrationListReq( + userId: '74300708945530955', + status: '', + ); + + static const _fallbackEventId = '10224'; + static const _fallbackItemId = '2318'; + static const _fallbackStreamUserId = '74300708949725207'; + + final Ref _ref; + + Future loadRegistrationList({ + PlayerRegistrationListReq request = defaultRegistrationRequest, + }) async { + state = state.copyWith(isLoading: true, clearErrorMessage: true); + try { + final result = await _ref + .read(eventsServerProvider) + .fetchPlayerRegistrationList(request); + state = state.copyWith( + isLoading: false, + profile: result.toProfile(), + total: result.total, + items: result.items, + clearErrorMessage: true, + ); + } on ApiException catch (error) { + state = state.copyWith(isLoading: false, errorMessage: error.message); + } catch (error) { + debugPrint('报名列表请求失败: $error'); + state = state.copyWith(isLoading: false, errorMessage: '报名列表加载失败'); + } + } + + Future requestStreamKey(EventRegistrationItem item) async { + state = state.copyWith( + isRequestingStreamKey: true, + clearErrorMessage: true, + ); + final req = StreamKeyReq( + eventId: item.eventId.isNotEmpty ? item.eventId : _fallbackEventId, + itemId: item.itemId.isNotEmpty ? item.itemId : _fallbackItemId, + userId: item.userId.isNotEmpty ? item.userId : _fallbackStreamUserId, + ); + + try { + final response = await _ref + .read(eventsServerProvider) + .fetchStreamKey(req); + debugPrint('推流 Key 接口响应: $response'); + state = state.copyWith( + isRequestingStreamKey: false, + clearErrorMessage: true, + ); + } on ApiException catch (error) { + debugPrint('推流 Key 接口请求失败: ${error.message}'); + state = state.copyWith( + isRequestingStreamKey: false, + errorMessage: error.message, + ); + } catch (error) { + debugPrint('推流 Key 接口请求失败: $error'); + state = state.copyWith( + isRequestingStreamKey: false, + errorMessage: '推流 Key 获取失败', + ); + } + } +} diff --git a/lib/features/dialog/dialog-record.dart b/lib/features/recording/dialog/dialog-record.dart similarity index 100% rename from lib/features/dialog/dialog-record.dart rename to lib/features/recording/dialog/dialog-record.dart diff --git a/lib/features/recording/model/model_clipboard.dart b/lib/features/recording/model/model_clipboard.dart deleted file mode 100644 index c0a92f4..0000000 --- a/lib/features/recording/model/model_clipboard.dart +++ /dev/null @@ -1,61 +0,0 @@ -/// 小程序复制到剪切板的录制信息。 -class ClipboardRecordingModel { - final String title; - int? startTimestamp; - int? endTimestamp; - final String address; - - /// 录制文件名模板,如「选手名称_选手ID_赛事名称_赛项」。 - final String? filename; - - ClipboardRecordingModel({ - required this.title, - this.startTimestamp, - this.endTimestamp, - required this.address, - this.filename, - }); - - factory ClipboardRecordingModel.fromJson(Map json) { - return ClipboardRecordingModel( - title: _readString(json, 'title'), - startTimestamp: _readOptionalInt(json, 'startTimestamp'), - endTimestamp: _readOptionalInt(json, 'endTimestamp'), - address: _readString(json, 'address'), - filename: _readOptionalString(json, 'filename'), - ); - } - - Map toJson() { - return { - 'title': title, - 'startTimestamp': startTimestamp, - 'endTimestamp': endTimestamp, - 'address': address, - if (filename != null) 'filename': filename, - }; - } - - static String? _readOptionalString(Map json, String key) { - final value = json[key]; - if (value == null) return null; - if (value is String && value.isNotEmpty) return value; - if (value is! String) { - throw FormatException('Clipboard field "$key" must be a String.'); - } - return null; - } - - static String _readString(Map json, String key) { - final value = json[key]; - if (value is String) return value; - throw FormatException('Clipboard field "$key" must be a String.'); - } - - static int? _readOptionalInt(Map json, String key) { - final value = json[key]; - if (value == null) return null; - if (value is int) return value; - throw FormatException('Clipboard field "$key" must be an int.'); - } -} diff --git a/lib/features/recording/model/model_recording.dart b/lib/features/recording/model/model_recording.dart index 8d29388..26affff 100644 --- a/lib/features/recording/model/model_recording.dart +++ b/lib/features/recording/model/model_recording.dart @@ -1,51 +1,26 @@ -import 'package:recording_tool/features/recording/model/model_clipboard.dart'; +import 'package:recording_tool/features/recording/model/model_recording_context.dart'; import 'package:recording_tool/features/recording/model/model_recording_session.dart'; class RecordingModel { - /// 剪切板内容 - final ClipboardRecordingModel clipboardRecordingModel; - - /// 剪切板是否包含有效的小程序录制信息 - final bool hasValidClipboardInfo; + /// 从赛事项进入录制页时传入的录制上下文。 + final RecordingContext recordingContext; /// 录制会话状态 final RecordingSessionState session; RecordingModel({ - required this.clipboardRecordingModel, - this.hasValidClipboardInfo = false, + required this.recordingContext, this.session = const RecordingSessionState(), }); bool get isRecording => session.isRecording; - factory RecordingModel.fromJson(Map json) { - return RecordingModel( - clipboardRecordingModel: ClipboardRecordingModel.fromJson( - json['clipboardRecordingModel'], - ), - ); - } - Map toJson() { - return {'clipboardRecordingModel': clipboardRecordingModel.toJson()}; - } - - /// 剪切板是否包含可用于命名的 [ClipboardRecordingModel.filename]。 - bool get hasClipboardFilename { - final name = clipboardRecordingModel.filename?.trim(); - return hasValidClipboardInfo && name != null && name.isNotEmpty; - } - RecordingModel copyWith({ - ClipboardRecordingModel? clipboardRecordingModel, - bool? hasValidClipboardInfo, + RecordingContext? recordingContext, RecordingSessionState? session, }) { return RecordingModel( - clipboardRecordingModel: - clipboardRecordingModel ?? this.clipboardRecordingModel, - hasValidClipboardInfo: - hasValidClipboardInfo ?? this.hasValidClipboardInfo, + recordingContext: recordingContext ?? this.recordingContext, session: session ?? this.session, ); } diff --git a/lib/features/recording/model/model_recording_context.dart b/lib/features/recording/model/model_recording_context.dart new file mode 100644 index 0000000..f36f78c --- /dev/null +++ b/lib/features/recording/model/model_recording_context.dart @@ -0,0 +1,55 @@ +class RecordingContext { + const RecordingContext({ + required this.eventTitle, + required this.matchName, + required this.group, + required this.venue, + required this.time, + required this.playerName, + required this.playerPhone, + this.laneNo, + this.status, + }); + + const RecordingContext.empty() + : eventTitle = '', + matchName = '', + group = '', + venue = '', + time = '', + playerName = '', + playerPhone = '', + laneNo = null, + status = null; + + final String eventTitle; + final String matchName; + final String group; + final String venue; + final String time; + final String playerName; + final String playerPhone; + final String? laneNo; + final String? status; + + String get title => '$matchName $group'; + + String get address => venue; + + String get displayName { + final parts = [ + playerName, + matchName, + group, + if (laneNo != null && laneNo!.trim().isNotEmpty) laneNo!, + ]; + return parts.map(_sanitize).where((part) => part.isNotEmpty).join('_'); + } + + static String _sanitize(String value) { + return value + .trim() + .replaceAll(RegExp(r'[\\/:*?"<>|]'), '_') + .replaceAll(RegExp(r'\s+'), '_'); + } +} diff --git a/lib/features/recording/model/model_recording_session.dart b/lib/features/recording/model/model_recording_session.dart index 5e25176..f09b21c 100644 --- a/lib/features/recording/model/model_recording_session.dart +++ b/lib/features/recording/model/model_recording_session.dart @@ -15,12 +15,11 @@ class RecordingSessionState { this.zoomRatio = 1.0, this.minZoomRatio = 1.0, this.maxZoomRatio = 3.0, - this.lastOutputPath, - this.lastSavedDisplayName, + this.lastStreamUrl, this.errorMessage, this.permissionWarning, - this.fileSaveFailed = false, - this.segmentOutputPaths = const [], + this.streamFinished = false, + this.streamFailed = false, }); final RecordingStatus status; @@ -35,12 +34,11 @@ class RecordingSessionState { final double zoomRatio; final double minZoomRatio; final double maxZoomRatio; - final String? lastOutputPath; - final String? lastSavedDisplayName; + final String? lastStreamUrl; final String? errorMessage; final String? permissionWarning; - final bool fileSaveFailed; - final List segmentOutputPaths; + final bool streamFinished; + final bool streamFailed; bool get isRecording => status.isRecording; @@ -65,14 +63,13 @@ class RecordingSessionState { double? zoomRatio, double? minZoomRatio, double? maxZoomRatio, - String? lastOutputPath, - String? lastSavedDisplayName, + String? lastStreamUrl, String? errorMessage, String? permissionWarning, - bool? fileSaveFailed, - List? segmentOutputPaths, + bool? streamFinished, + bool? streamFailed, bool clearPermissionWarning = false, - bool clearLastSaved = false, + bool clearStreamResult = false, }) { return RecordingSessionState( status: status ?? this.status, @@ -88,16 +85,17 @@ class RecordingSessionState { zoomRatio: zoomRatio ?? this.zoomRatio, minZoomRatio: minZoomRatio ?? this.minZoomRatio, maxZoomRatio: maxZoomRatio ?? this.maxZoomRatio, - lastOutputPath: lastOutputPath ?? this.lastOutputPath, - lastSavedDisplayName: clearLastSaved - ? null - : (lastSavedDisplayName ?? this.lastSavedDisplayName), + lastStreamUrl: lastStreamUrl ?? this.lastStreamUrl, errorMessage: errorMessage, permissionWarning: clearPermissionWarning ? null : (permissionWarning ?? this.permissionWarning), - fileSaveFailed: fileSaveFailed ?? this.fileSaveFailed, - segmentOutputPaths: segmentOutputPaths ?? this.segmentOutputPaths, + streamFinished: clearStreamResult + ? false + : (streamFinished ?? this.streamFinished), + streamFailed: clearStreamResult + ? false + : (streamFailed ?? this.streamFailed), ); } } diff --git a/lib/features/recording/pages/page_record.dart b/lib/features/recording/pages/page_record.dart index 803e28a..8573553 100644 --- a/lib/features/recording/pages/page_record.dart +++ b/lib/features/recording/pages/page_record.dart @@ -1,15 +1,16 @@ import 'dart:io'; +import 'package:apivideo_live_stream/apivideo_live_stream.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:permission_handler/permission_handler.dart'; +import 'package:recording_tool/app/router/app_navigator.dart'; import 'package:recording_tool/core/platform/app_platform_info.dart'; import 'package:recording_tool/core/platform/device_health_checker.dart'; -import 'package:recording_tool/features/dialog/dialog-record.dart'; -import 'package:recording_tool/features/recording/model/model_recording.dart'; +import 'package:recording_tool/features/recording/dialog/dialog-record.dart'; +import 'package:recording_tool/features/recording/model/model_recording_context.dart'; import 'package:recording_tool/features/recording/platform/recording_platform.dart'; -import 'package:recording_tool/features/recording/utils/recording_display_name.dart'; import 'package:recording_tool/features/recording/view-model/view_model_recording.dart'; import 'package:recording_tool/features/recording/widgets/widget_camera_preview.dart'; import 'package:recording_tool/features/recording/widgets/widget_record_footer.dart'; @@ -19,11 +20,20 @@ import 'package:recording_tool/features/recording/widgets/widget_recording_hud.d import 'package:recording_tool/features/recording/widgets/widget_recording_loading_overlay.dart'; import 'package:recording_tool/features/recording/widgets/widget_recording_saved_dialog.dart'; import 'package:recording_tool/features/recording/widgets/widget_recording_touch_lock_overlay.dart'; +import 'package:recording_tool/features/scan_qrcode/pages/page_scan_qrcode.dart'; +import 'package:recording_tool/features/scan_qrcode/utils/rtmp_stream_target.dart'; import 'package:recording_tool/shared/widgets/widgets.dart'; /// 录制页入口 class RecordingPage extends ConsumerStatefulWidget { - const RecordingPage({super.key}); + const RecordingPage({ + super.key, + required this.recordingContext, + required this.streamUrl, + }); + + final RecordingContext recordingContext; + final String streamUrl; @override /// 创建页面状态 @@ -31,13 +41,60 @@ class RecordingPage extends ConsumerStatefulWidget { } class _RecordingPageState extends ConsumerState { + late final ApiVideoLiveStreamController _streamController; var _immersiveApplied = false; + var _previewReady = false; + var _stoppingByUser = false; + var _controllerDisposed = false; + String? _mainCameraId; + String? _ultraWideCameraId; + double _ultraWideZoomRatio = 1.0; @override /// 首帧后初始化录制流程 void initState() { super.initState(); - WidgetsBinding.instance.addPostFrameCallback((_) => _bootstrap()); + _streamController = ApiVideoLiveStreamController( + initialAudioConfig: AudioConfig(bitrate: 128000), + initialVideoConfig: VideoConfig.withDefaultBitrate( + resolution: Resolution.RESOLUTION_1080, + fps: 30, + ), + onConnectionSuccess: () => {debugPrint('推流成功')}, + onConnectionFailed: (reason) { + debugPrint('推流失败'); + + if (!mounted) return; + ref + .read(recordingViewModelProvider.notifier) + .markRecordingStartFailed('推流失败: $reason'); + }, + onDisconnection: () { + debugPrint('推流连接已断开'); + + if (!mounted || _stoppingByUser) return; + final isRecording = ref.read(recordingViewModelProvider).isRecording; + if (isRecording) { + ref + .read(recordingViewModelProvider.notifier) + .markRecordingStopped(errorMessage: '推流连接已断开'); + } + }, + onError: (error) { + debugPrint('推流失败:${error.toString()}'); + if (!mounted) return; + ref + .read(recordingViewModelProvider.notifier) + .setError(error.toString()); + }, + ); + + WidgetsBinding.instance.addPostFrameCallback((_) { + ref + .read(recordingViewModelProvider.notifier) + .setRecordingContext(widget.recordingContext); + _bootstrap(); + }); } /// 检查设备健康状态并弹窗提示 @@ -55,23 +112,81 @@ class _RecordingPageState extends ConsumerState { ); } - /// 页面启动:健康检查、读剪贴板、进入录制模式、准备相机会话 + /// 页面启动:健康检查、进入录制模式、准备相机会话 Future _bootstrap() async { await _checkAndShowDeviceHealthAlerts(); if (!mounted) return; - final clipboardResult = await ref - .read(recordingViewModelProvider.notifier) - .getClipboardContent(); - if (!mounted) return; - if (clipboardResult == ClipboardReadResult.invalid) { - AppToast.show('无选手信息'); - } await _enterRecordingMode(); - // Allow PlatformView to attach before binding CameraX preview. - await Future.delayed(const Duration(milliseconds: 400)); if (!mounted) return; await ref.read(recordingViewModelProvider.notifier).prepareSession(); + if (!mounted) return; + await _initializeLiveStreamPreview(); + } + + Future _initializeLiveStreamPreview() async { + try { + await _streamController.initialize(); + if (!mounted) return; + setState(() => _previewReady = true); + ref + .read(recordingViewModelProvider.notifier) + .setPreviewReady(ready: true); + await _loadBackCameraCapabilities(); + } on PlatformException catch (error) { + if (!mounted) return; + ref + .read(recordingViewModelProvider.notifier) + .setPreviewReady( + ready: false, + errorMessage: error.message ?? '相机预览初始化失败', + ); + if (mounted) setState(() => _previewReady = false); + } catch (error) { + if (!mounted) return; + ref + .read(recordingViewModelProvider.notifier) + .setPreviewReady(ready: false, errorMessage: '相机预览初始化失败: $error'); + setState(() => _previewReady = false); + } + } + + Future _loadBackCameraCapabilities() async { + try { + final cameras = await _streamController.getBackCameras(); + if (cameras.isEmpty) return; + final main = cameras.first; + final widest = cameras.reduce( + (current, next) => + next.horizontalFov > current.horizontalFov ? next : current, + ); + _mainCameraId = main.cameraId; + if (widest.cameraId != main.cameraId && + widest.horizontalFov > main.horizontalFov * 1.08 && + main.minFocalLength > 0) { + _ultraWideCameraId = widest.cameraId; + _ultraWideZoomRatio = (widest.minFocalLength / main.minFocalLength) + .clamp(0.4, 0.9) + .toDouble(); + } + ref + .read(recordingViewModelProvider.notifier) + .updateZoomCapabilities( + zoomRatio: 1.0, + minZoomRatio: _ultraWideCameraId == null + ? 1.0 + : _ultraWideZoomRatio, + maxZoomRatio: 1.0, + ); + } catch (_) { + ref + .read(recordingViewModelProvider.notifier) + .updateZoomCapabilities( + zoomRatio: 1.0, + minZoomRatio: 1.0, + maxZoomRatio: 1.0, + ); + } } /// Android 进入沉浸式全屏 @@ -82,43 +197,6 @@ class _RecordingPageState extends ConsumerState { _immersiveApplied = true; } - /// 解析保存成功弹窗的标题文案 - String _savedDialogSessionTitle( - RecordingModel recordingInfo, - String? savedName, - ) { - final clipboard = recordingInfo.clipboardRecordingModel; - if (recordingInfo.hasValidClipboardInfo && - clipboard.title.trim().isNotEmpty) { - return clipboard.title.trim(); - } - if (savedName != null && savedName.isNotEmpty) { - return resolveRecordingDisplayName(savedName); - } - return '录制完成'; - } - - /// 从剪贴板粘贴赛事信息(与 header「粘贴选手信息」一致)。 - Future _pasteEventInfo() async { - final result = await ref - .read(recordingViewModelProvider.notifier) - .getClipboardContent(); - if (!mounted) return; - if (result != ClipboardReadResult.success) { - AppToast.show('无选手信息'); - } - } - - /// 无选手信息时弹窗提示 - Future _showNoPlayerInfoDialog() { - return RecordDialog.showSingle( - context, - title: '无选手信息!', - buttonText: '粘贴', - onPressed: _pasteEventInfo, - ); - } - /// 根据缺失权限生成弹窗文案。 String _recordingPermissionDialogTitle(RecordingRequiredPermissions result) { if (!result.cameraGranted && !result.microphoneGranted) { @@ -153,65 +231,109 @@ class _RecordingPageState extends ConsumerState { return false; } - /// 点击开始录制:校验剪贴板、权限与健康状态 + /// 点击开始录制:校验推流地址、权限与健康状态 Future _onStartRecording() async { - final recordingInfo = ref.read(recordingViewModelProvider); - if (!recordingInfo.hasClipboardFilename) { - await _showNoPlayerInfoDialog(); + if (widget.streamUrl.trim().isEmpty) { + AppToast.show('推流地址为空,请重新进入录制页'); return; } if (!await _ensureRecordingPermissions()) return; if (!mounted) return; await _checkAndShowDeviceHealthAlerts(); if (!mounted) return; - await ref.read(recordingViewModelProvider.notifier).startRecording(); + final viewModel = ref.read(recordingViewModelProvider.notifier); + viewModel.markStartingRecording(); + try { + final target = RtmpStreamTarget.parse(widget.streamUrl); + await _streamController.startStreaming( + streamKey: target.streamKey, + url: target.url, + ); + if (!mounted) return; + await viewModel.markRecordingStarted(target.fullUrl); + } on FormatException catch (error) { + viewModel.markRecordingStartFailed(error.message); + AppToast.show(error.message); + } on PlatformException catch (error) { + final message = error.message ?? error.code; + viewModel.markRecordingStartFailed('推流失败: $message'); + AppToast.show('推流失败: $message'); + } catch (error) { + viewModel.markRecordingStartFailed('推流失败: $error'); + AppToast.showError(error); + } } - /// 停止录制并按结果显示保存提示。 + /// 停止录制并按结果显示推流提示。 Future _stopRecordingAndShowResult() async { - await ref.read(recordingViewModelProvider.notifier).stopRecording(); - if (!mounted) return; - final latest = ref.read(recordingViewModelProvider).session; - if (latest.fileSaveFailed) { - if (latest.segmentOutputPaths.isNotEmpty) { - AppToast.show('视频合并失败,已为你保存分段文件,可在相册中查看'); - } else { - AppToast.show(latest.errorMessage ?? '保存到文件夹失败,请检查文件保存权限'); - } + final viewModel = ref.read(recordingViewModelProvider.notifier); + _stoppingByUser = true; + try { + await _streamController.stopStreaming(); + if (!mounted) return; + await viewModel.markRecordingStopped(); + } on PlatformException catch (error) { + final message = error.message ?? error.code; + await viewModel.markRecordingStopped(errorMessage: '停止推流失败: $message'); + AppToast.show('停止推流失败: $message'); + return; + } catch (error) { + await viewModel.markRecordingStopped(errorMessage: '停止推流失败: $error'); + AppToast.showError(error); + return; + } finally { + _stoppingByUser = false; + } + await _showRecordingFinishedDialogIfNeeded(); + } + + Future _setCameraZoomRatio(double ratio) async { + final viewModel = ref.read(recordingViewModelProvider.notifier); + final targetCameraId = ratio < 1.0 ? _ultraWideCameraId : _mainCameraId; + if (targetCameraId == null) { + viewModel.setError('当前设备不支持该镜头'); return; } - await _showRecordingSavedDialogIfNeeded(); + viewModel.markLensSwitching(true); + try { + await _streamController.setCameraId(targetCameraId); + viewModel.setZoomRatioValue(ratio < 1.0 ? _ultraWideZoomRatio : 1.0); + } on PlatformException catch (error) { + final isRecording = ref.read(recordingViewModelProvider).isRecording; + final message = isRecording + ? '推流中切换镜头失败,请停止后重试' + : (error.message ?? '切换镜头失败,请重试'); + viewModel.setError(message); + } catch (_) { + final isRecording = ref.read(recordingViewModelProvider).isRecording; + viewModel.setError(isRecording ? '推流中切换镜头失败,请停止后重试' : '切换镜头失败,请重试'); + } finally { + viewModel.markLensSwitching(false); + } } - /// 清空剪贴板信息,准备新一轮录制 - void _clearClipboardForNewRound() { - final notifier = ref.read(recordingViewModelProvider.notifier); - notifier.resetClipboardInfo(); - notifier.clearSavedRecordingResult(); + /// 返回扫码页,准备新一轮录制。 + void _recordNewRound() { + AppNavigator.pushAndRemoveUntil(const ScanQrCodePage()); } - /// 保存成功后按需弹出完成对话框 - Future _showRecordingSavedDialogIfNeeded() async { + /// 推流结束后按需弹出完成对话框 + Future _showRecordingFinishedDialogIfNeeded() async { final recordingInfo = ref.read(recordingViewModelProvider); final session = recordingInfo.session; - if (session.lastSavedDisplayName == null || session.fileSaveFailed) { + if (!session.streamFinished || session.streamFailed) { return; } - final sessionTitle = _savedDialogSessionTitle( - recordingInfo, - session.lastSavedDisplayName, - ); - await showRecordingSavedDialog( context, - sessionTitle: sessionTitle, + sessionTitle: recordingInfo.recordingContext.title, onContinueRound: () { ref .read(recordingViewModelProvider.notifier) .clearSavedRecordingResult(); }, - onRecordNewRound: _clearClipboardForNewRound, + onRecordNewRound: _recordNewRound, ); } @@ -219,6 +341,7 @@ class _RecordingPageState extends ConsumerState { Future _exitRecordingMode() async { if (!_immersiveApplied) return; await ref.read(recordingViewModelProvider.notifier).teardown(); + await _disposeStreamController(); await SystemChrome.setEnabledSystemUIMode( SystemUiMode.manual, overlays: SystemUiOverlay.values, @@ -237,9 +360,17 @@ class _RecordingPageState extends ConsumerState { ); RecordingPlatform.setImmersiveMode(enabled: false); } + _disposeStreamController(); super.dispose(); } + Future _disposeStreamController() async { + if (_controllerDisposed) return; + _controllerDisposed = true; + await _streamController.stop(); + await _streamController.dispose(); + } + @override /// 构建录制页 UI Widget build(BuildContext context) { @@ -249,19 +380,20 @@ class _RecordingPageState extends ConsumerState { backgroundColor: Colors.black, body: Column( children: [ - _RecordHeaderSection( - onPasteEventInfo: _pasteEventInfo, - onClearEventInfo: _clearClipboardForNewRound, - ), + const _RecordHeaderSection(), Expanded( child: Stack( children: [ - const CameraPreviewWidget(), + CameraPreviewWidget( + controller: _streamController, + isReady: _previewReady, + ), const _PreviewLoadingLayer(), const RecordTimerWidget(), _RecordingHudLayer( onStart: _onStartRecording, onStop: _stopRecordingAndShowResult, + onZoomSelected: _setCameraZoomRatio, ), _TouchLockOverlayLayer( onStopRecording: _stopRecordingAndShowResult, @@ -310,34 +442,18 @@ class _RecordingPopScope extends ConsumerWidget { } class _RecordHeaderSection extends ConsumerWidget { - const _RecordHeaderSection({ - required this.onPasteEventInfo, - required this.onClearEventInfo, - }); - - final Future Function() onPasteEventInfo; - final VoidCallback onClearEventInfo; + const _RecordHeaderSection(); @override Widget build(BuildContext context, WidgetRef ref) { final headerState = ref.watch( recordingViewModelProvider.select( - (m) => ( - m.hasValidClipboardInfo, - m.hasValidClipboardInfo ? m.clipboardRecordingModel.title : null, - m.session.isRecording, - ), + (m) => (m.recordingContext.title, m.session.isRecording), ), ); - final (hasValidClipboardInfo, eventTitle, isRecording) = headerState; + final (eventTitle, isRecording) = headerState; - return RecordHeaderWidget( - hasValidClipboardInfo: hasValidClipboardInfo, - eventTitle: eventTitle, - isRecording: isRecording, - onPasteEventInfo: onPasteEventInfo, - onClearEventInfo: onClearEventInfo, - ); + return RecordHeaderWidget(eventTitle: eventTitle, isRecording: isRecording); } } @@ -361,10 +477,15 @@ class _PreviewLoadingLayer extends ConsumerWidget { } class _RecordingHudLayer extends ConsumerWidget { - const _RecordingHudLayer({required this.onStart, required this.onStop}); + const _RecordingHudLayer({ + required this.onStart, + required this.onStop, + required this.onZoomSelected, + }); final Future Function() onStart; final Future Function() onStop; + final ValueChanged onZoomSelected; @override Widget build(BuildContext context, WidgetRef ref) { @@ -383,8 +504,7 @@ class _RecordingHudLayer extends ConsumerWidget { m.session.zoomRatio, m.session.minZoomRatio, m.session.maxZoomRatio, - m.hasValidClipboardInfo, - m.clipboardRecordingModel.address.trim(), + m.recordingContext.address.trim(), ), ), ); @@ -401,8 +521,7 @@ class _RecordingHudLayer extends ConsumerWidget { zoomRatio, minZoomRatio, maxZoomRatio, - showClipboardHint, - clipboardAddress, + venue, ) = hudState; final viewModel = ref.read(recordingViewModelProvider.notifier); @@ -419,8 +538,8 @@ class _RecordingHudLayer extends ConsumerWidget { zoomRatio: zoomRatio, minZoomRatio: minZoomRatio, maxZoomRatio: maxZoomRatio, - showClipboardHint: showClipboardHint, - clipboardAddress: clipboardAddress, + showContextHint: venue.isNotEmpty, + contextAddress: venue, onStart: onStart, onStop: onStop, onOpenDnd: () async { @@ -438,9 +557,7 @@ class _RecordingHudLayer extends ConsumerWidget { .isTouchLocked; viewModel.setTouchLocked(!locked); }, - onZoomSelected: (ratio) async { - await viewModel.setZoomRatio(ratio); - }, + onZoomSelected: onZoomSelected, ); } } @@ -491,7 +608,7 @@ class _StartingRecordingOverlay extends ConsumerWidget { } return RecordingLoadingOverlayWidget( - message: '正在开始录制…', + message: '正在连接推流…', backgroundColor: Colors.black.withValues(alpha: 0.24), ); } diff --git a/lib/features/recording/platform/recording_platform.dart b/lib/features/recording/platform/recording_platform.dart index ecf6d88..b3fa70f 100644 --- a/lib/features/recording/platform/recording_platform.dart +++ b/lib/features/recording/platform/recording_platform.dart @@ -1,4 +1,3 @@ -import 'dart:async'; import 'dart:io'; import 'package:flutter/services.dart'; @@ -22,20 +21,20 @@ enum RecordingState { class RecordingStatus { const RecordingStatus({ required this.state, - this.outputPath, + this.streamUrl, this.elapsedMillis = 0, this.message, }); final RecordingState state; - final String? outputPath; + final String? streamUrl; final int elapsedMillis; final String? message; factory RecordingStatus.fromMap(Map map) { return RecordingStatus( state: RecordingState.fromRaw(map['state'] as String?), - outputPath: map['outputPath'] as String?, + streamUrl: map['streamUrl'] as String?, elapsedMillis: (map['elapsedMillis'] as num?)?.toInt() ?? 0, message: map['message'] as String?, ); @@ -50,9 +49,6 @@ class RecordingPlatform { static const MethodChannel _channel = MethodChannel( RecordingChannelNames.method, ); - static const EventChannel _events = EventChannel( - RecordingChannelNames.events, - ); static bool get isSupported => supportsHost(isAndroid: Platform.isAndroid, isIOS: Platform.isIOS); @@ -61,76 +57,6 @@ class RecordingPlatform { return isAndroid || isIOS; } - static Stream? _statusStream; - - static Stream statusStream() { - if (!isSupported) { - return const Stream.empty(); - } - _statusStream ??= _events.receiveBroadcastStream().map( - (event) => - RecordingStatus.fromMap(Map.from(event as Map)), - ); - return _statusStream!; - } - - static Future initializePreview() async { - final result = await _channel.invokeMapMethod( - 'initializePreview', - ); - return RecordingStatus.fromMap(result ?? const {}); - } - - static Future getZoomCapabilities() async { - final result = await _channel.invokeMapMethod( - 'getZoomCapabilities', - ); - return RecordingZoomCapabilities.fromMap(result); - } - - static Future setZoomRatio(double ratio) async { - final result = await _channel.invokeMapMethod( - 'setZoomRatio', - {'zoomRatio': ratio}, - ); - return RecordingZoomCapabilities.fromMap(result); - } - - static Future startRecording({ - bool withAudio = true, - bool enableDoNotDisturb = true, - String? displayName, - }) async { - final args = { - 'withAudio': withAudio, - 'enableDoNotDisturb': enableDoNotDisturb, - }; - if (displayName != null) { - args['displayName'] = displayName; - } - - final result = await _channel.invokeMapMethod( - 'startRecording', - args, - ); - return RecordingStartResult( - outputPath: result?['outputPath'] as String?, - status: RecordingStatus.fromMap( - Map.from(result?['status'] as Map? ?? const {}), - ), - ); - } - - static Future stopRecording() async { - final result = await _channel.invokeMapMethod( - 'stopRecording', - ); - return RecordingStopResult.fromMap(result); - } - - static Future disposePreview() => - _channel.invokeMethod('disposePreview'); - static Future hasNotificationPolicyAccess() async { return await _channel.invokeMethod('hasNotificationPolicyAccess') ?? false; @@ -164,71 +90,4 @@ class RecordingPlatform { 'enabled': enabled, }); } - - static Future getStatus() async { - final result = await _channel.invokeMapMethod('getStatus'); - return RecordingStatus.fromMap(result ?? const {}); - } -} - -class RecordingZoomCapabilities { - const RecordingZoomCapabilities({ - required this.zoomRatio, - required this.minZoomRatio, - required this.maxZoomRatio, - }); - - final double zoomRatio; - final double minZoomRatio; - final double maxZoomRatio; - - factory RecordingZoomCapabilities.fromMap(Map? map) { - final minZoomRatio = (map?['minZoomRatio'] as num?)?.toDouble() ?? 1.0; - final maxZoomRatio = (map?['maxZoomRatio'] as num?)?.toDouble() ?? 3.0; - final zoomRatio = (map?['zoomRatio'] as num?)?.toDouble() ?? minZoomRatio; - return RecordingZoomCapabilities( - zoomRatio: zoomRatio.clamp(minZoomRatio, maxZoomRatio).toDouble(), - minZoomRatio: minZoomRatio, - maxZoomRatio: maxZoomRatio, - ); - } -} - -class RecordingStartResult { - const RecordingStartResult({this.outputPath, required this.status}); - - final String? outputPath; - final RecordingStatus status; -} - -class RecordingStopResult { - const RecordingStopResult({ - this.outputPath, - required this.status, - this.fileSaved = true, - this.fileErrorMessage, - this.segmentOutputPaths = const [], - }); - - final String? outputPath; - final RecordingStatus status; - final bool fileSaved; - final String? fileErrorMessage; - final List segmentOutputPaths; - - factory RecordingStopResult.fromMap(Map? result) { - return RecordingStopResult( - outputPath: result?['outputPath'] as String?, - status: RecordingStatus.fromMap( - Map.from(result?['status'] as Map? ?? const {}), - ), - fileSaved: result?['fileSaved'] as bool? ?? true, - fileErrorMessage: result?['fileErrorMessage'] as String?, - segmentOutputPaths: - (result?['segmentOutputPaths'] as List?)?.whereType().toList( - growable: false, - ) ?? - const [], - ); - } } diff --git a/lib/features/recording/utils/recording_display_name.dart b/lib/features/recording/utils/recording_display_name.dart deleted file mode 100644 index 1d6ab2c..0000000 --- a/lib/features/recording/utils/recording_display_name.dart +++ /dev/null @@ -1,53 +0,0 @@ -import 'dart:io'; - -/// 非法文件名字符(路径分隔符等)。 -final _invalidNameChars = RegExp(r'[/\\:*?"<>|]'); - -const _maxBaseNameLength = 120; - -/// 清洗小程序复制的文件名基底(不含扩展名)。 -String? sanitizeRecordingBaseName(String raw) { - var name = raw.replaceAll(_invalidNameChars, '_').trim(); - if (name.isEmpty) return null; - if (name.length > _maxBaseNameLength) { - name = name.substring(0, _maxBaseNameLength); - } - return name; -} - -/// 解析录制展示名:优先剪切板 filename,否则 REC_时间戳。 -String resolveRecordingDisplayName(String? clipboardFilename) { - final sanitized = clipboardFilename == null - ? null - : sanitizeRecordingBaseName(clipboardFilename); - if (sanitized != null) return sanitized; - final now = DateTime.now(); - final stamp = - '${now.year}' - '${now.month.toString().padLeft(2, '0')}' - '${now.day.toString().padLeft(2, '0')}_' - '${now.hour.toString().padLeft(2, '0')}' - '${now.minute.toString().padLeft(2, '0')}' - '${now.second.toString().padLeft(2, '0')}'; - return 'REC_$stamp'; -} - -/// 为展示名补全视频扩展名(已有 .mp4/.mov 则保留)。 -String withVideoExtension(String baseName, {bool? isIOS}) { - final ios = isIOS ?? Platform.isIOS; - final ext = ios ? '.mov' : '.mp4'; - final lower = baseName.toLowerCase(); - if (lower.endsWith('.mp4') || lower.endsWith('.mov')) { - return baseName; - } - return '$baseName$ext'; -} - -/// 传给原生的完整文件名(含扩展名)。 -String recordingFileNameForPlatform( - String? clipboardFilename, { - bool? isIOS, -}) { - final base = resolveRecordingDisplayName(clipboardFilename); - return withVideoExtension(base, isIOS: isIOS); -} diff --git a/lib/features/recording/view-model/view_model_recording.dart b/lib/features/recording/view-model/view_model_recording.dart index 2cdca50..6ddfde5 100644 --- a/lib/features/recording/view-model/view_model_recording.dart +++ b/lib/features/recording/view-model/view_model_recording.dart @@ -1,18 +1,13 @@ import 'dart:async'; -import 'dart:convert'; import 'dart:io'; -import 'package:flutter/services.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:permission_handler/permission_handler.dart'; -import 'package:recording_tool/core/logging/app_logger.dart'; import 'package:recording_tool/core/permission/permission_service.dart'; -import 'package:recording_tool/core/platform/app_platform_info.dart'; -import 'package:recording_tool/features/recording/model/model_clipboard.dart'; import 'package:recording_tool/features/recording/model/model_recording.dart'; +import 'package:recording_tool/features/recording/model/model_recording_context.dart'; import 'package:recording_tool/features/recording/model/model_recording_session.dart'; import 'package:recording_tool/features/recording/platform/recording_platform.dart'; -import 'package:recording_tool/features/recording/utils/recording_display_name.dart'; /// 录制页状态 Provider。 final recordingViewModelProvider = @@ -20,35 +15,6 @@ final recordingViewModelProvider = RecordingViewModel.new, ); -/// 剪切板读取结果,供 UI 决定是否提示用户。 -enum ClipboardReadResult { - /// 剪切板为空,不提示 - empty, - - /// 解析成功 - success, - - /// 有内容但格式不符合小程序录制信息 - invalid, -} - -List recordingFileSavePermissionsForHost({ - required bool isIOS, - required bool isAndroid, - int? androidSdkInt, -}) { - if (isIOS) { - return const []; - } - if (isAndroid) { - if (androidSdkInt != null && androidSdkInt <= 28) { - return [Permission.storage]; - } - return const []; - } - return const []; -} - /// 开始录制所需的相机/麦克风权限检测结果。 class RecordingRequiredPermissions { const RecordingRequiredPermissions({ @@ -62,20 +28,16 @@ class RecordingRequiredPermissions { bool get allGranted => cameraGranted && microphoneGranted; } -/// 录制页 ViewModel:剪贴板、权限、相机预览与录制流程。 +/// 录制页 ViewModel:赛事上下文、权限、推流与页面状态。 class RecordingViewModel extends Notifier { - static final _defaultClipboard = ClipboardRecordingModel( - title: '', - address: '', - ); - - StreamSubscription? _statusSubscription; + Timer? _elapsedTimer; + DateTime? _recordingStartedAt; /// 初始化状态并注册销毁回调。 @override RecordingModel build() { ref.onDispose(_dispose); - return RecordingModel(clipboardRecordingModel: _defaultClipboard); + return RecordingModel(recordingContext: const RecordingContext.empty()); } /// 局部更新 session 子状态。 @@ -85,76 +47,22 @@ class RecordingViewModel extends Notifier { state = state.copyWith(session: update(state.session)); } - /// 读取并解析剪贴板中的小程序录制信息。 - Future getClipboardContent() async { - try { - final clipboardData = await Clipboard.getData(Clipboard.kTextPlain); - final text = clipboardData?.text; - AppLogger.debug('读取剪切板内容:$text'); - - if (text == null || text.trim().isEmpty) { - AppLogger.info('剪切板内容为空,跳过录制信息解析'); - _resetClipboardInfo(); - return ClipboardReadResult.empty; - } - - final decoded = jsonDecode(text.trim()); - if (decoded is! Map) { - AppLogger.warning('剪切板内容不是 JSON 对象,跳过录制信息解析'); - _resetClipboardInfo(); - return ClipboardReadResult.invalid; - } - - final clipboardRecordingModel = ClipboardRecordingModel.fromJson(decoded); - if (clipboardRecordingModel.title.trim().isEmpty) { - AppLogger.warning('剪切板录制信息缺少有效 title'); - _resetClipboardInfo(); - return ClipboardReadResult.invalid; - } - - state = state.copyWith( - clipboardRecordingModel: clipboardRecordingModel, - hasValidClipboardInfo: true, - ); - AppLogger.info('剪切板录制信息解析成功:${clipboardRecordingModel.toJson()}'); - return ClipboardReadResult.success; - } on FormatException catch (error) { - AppLogger.warning('剪切板录制信息格式错误:$error'); - _resetClipboardInfo(); - return ClipboardReadResult.invalid; - } catch (error, stackTrace) { - AppLogger.debug('读取剪切板录制信息失败', error: error, stackTrace: stackTrace); - _resetClipboardInfo(); - return ClipboardReadResult.invalid; - } + /// 设置当前录制页上下文。 + void setRecordingContext(RecordingContext recordingContext) { + state = state.copyWith(recordingContext: recordingContext); } - /// 清空剪贴板赛事信息(供 UI 调用)。 - void resetClipboardInfo() { - _resetClipboardInfo(); - } - - /// 重置剪贴板赛事信息为默认空值。 - void _resetClipboardInfo() { - state = state.copyWith( - clipboardRecordingModel: _defaultClipboard, - hasValidClipboardInfo: false, - ); - } - - /// 申请权限、检查系统设置并初始化相机预览。 + /// 申请权限并检查系统设置。 Future prepareSession() async { if (!RecordingPlatform.isSupported) { _updateSession((s) => s.copyWith(errorMessage: '当前设备不支持录制')); return; } - final fileSavePermissions = await _fileSavePermissions(); final permissions = await PermissionService.requestMissing([ Permission.camera, Permission.microphone, if (Platform.isAndroid) Permission.notification, - ...fileSavePermissions, ]); final cameraGranted = permissions[Permission.camera]?.isGranted ?? false; @@ -176,10 +84,6 @@ class RecordingViewModel extends Notifier { if (!microphoneGranted) { warnings.add('未授予麦克风权限,当前将以静音模式录制'); } - if (!_isFileSavePermissionGranted(permissions, fileSavePermissions)) { - warnings.add('未授予文件保存权限,录制结束后可能无法保存到文件夹'); - } - final hasDnd = await RecordingPlatform.hasNotificationPolicyAccess(); final batteryIgnored = await RecordingPlatform.isIgnoringBatteryOptimizations(); @@ -196,106 +100,13 @@ class RecordingViewModel extends Notifier { ), ); - await _listenStatus(); - try { - final status = await _initializePreviewWithRetry(); - await _refreshZoomCapabilities(); - _updateSession( - (s) => s.copyWith( - status: status, - isPreviewReady: status.state == RecordingState.previewing, - errorMessage: status.state == RecordingState.previewing - ? null - : (status.message ?? '相机预览初始化失败'), - ), - ); - } on PlatformException catch (error) { - _updateSession( - (s) => s.copyWith( - isPreviewReady: false, - errorMessage: error.message ?? '相机预览初始化失败', - ), - ); - } + _updateSession((s) => s.copyWith(errorMessage: null)); } - /// 初始化相机预览,PlatformView 未就绪时自动重试。 - Future _initializePreviewWithRetry() async { - const maxAttempts = 8; - for (var attempt = 0; attempt < maxAttempts; attempt++) { - try { - return await RecordingPlatform.initializePreview(); - } on PlatformException catch (error) { - final shouldRetry = - error.code == 'NO_PREVIEW' && attempt < maxAttempts - 1; - if (!shouldRetry) { - rethrow; - } - await Future.delayed(Duration(milliseconds: 150 * (attempt + 1))); - } - } - throw StateError('initializePreview retry exhausted'); - } - - /// 停止录制后重新绑定相机预览,并显示加载遮罩。 - Future restorePreview() async { - if (!RecordingPlatform.isSupported) return; - + void setPreviewReady({required bool ready, String? errorMessage}) { _updateSession( - (s) => s.copyWith(isPreviewReady: false, errorMessage: null), + (s) => s.copyWith(isPreviewReady: ready, errorMessage: errorMessage), ); - try { - final status = await _initializePreviewWithRetry(); - await _refreshZoomCapabilities(); - _updateSession( - (s) => s.copyWith( - status: status, - isPreviewReady: status.state == RecordingState.previewing, - errorMessage: status.state == RecordingState.previewing - ? null - : (status.message ?? '相机预览初始化失败'), - ), - ); - } on PlatformException catch (error) { - _updateSession( - (s) => s.copyWith( - isPreviewReady: false, - errorMessage: error.message ?? '相机预览初始化失败', - ), - ); - } - } - - /// 当前平台所需的视频文件保存权限列表。 - Future> _fileSavePermissions() async { - int? androidSdkInt; - if (Platform.isAndroid) { - try { - androidSdkInt = int.tryParse( - (await AppPlatformInfo.deviceInfo()).values['sdkInt'] ?? '', - ); - } on PlatformException { - androidSdkInt = null; - } - } - return recordingFileSavePermissionsForHost( - isIOS: Platform.isIOS, - isAndroid: Platform.isAndroid, - androidSdkInt: androidSdkInt, - ); - } - - /// 判断文件保存相关权限是否至少有一项已授予。 - bool _isFileSavePermissionGranted( - Map permissions, - List fileSavePermissions, - ) { - for (final permission in fileSavePermissions) { - if (permissions[permission]?.isGranted ?? false) { - return true; - } - } - return fileSavePermissions.isEmpty; } /// 检测并尝试申请相机、麦克风权限,同步更新 session 中的 isMicrophoneGranted。 @@ -315,8 +126,7 @@ class RecordingViewModel extends Notifier { if (cameraGranted && !state.session.isPreviewReady) { _updateSession((s) => s.copyWith(errorMessage: null)); - await _listenStatus(); - await restorePreview(); + _updateSession((s) => s.copyWith(isPreviewReady: true)); } return RecordingRequiredPermissions( @@ -329,130 +139,115 @@ class RecordingViewModel extends Notifier { return status?.isGranted == true || status?.isLimited == true; } - /// 读取相机支持的倍距范围并同步当前倍距。 - Future _refreshZoomCapabilities() async { - try { - final zoom = await RecordingPlatform.getZoomCapabilities(); - _updateSession( - (s) => s.copyWith( - zoomRatio: zoom.zoomRatio, - minZoomRatio: zoom.minZoomRatio, - maxZoomRatio: zoom.maxZoomRatio, - errorMessage: null, - ), - ); - } on PlatformException catch (error) { - AppLogger.debug('读取相机倍距能力失败', error: error); - } - } - - /// 设置相机倍距,原生层会返回设备实际应用后的倍距范围与当前值。 - Future setZoomRatio(double ratio) async { - final session = state.session; - if (session.isSwitchingLens) { - return; - } - final clamped = ratio - .clamp(session.minZoomRatio, session.maxZoomRatio) - .toDouble(); - - _updateSession((s) => s.copyWith(isSwitchingLens: true)); - try { - final zoom = await RecordingPlatform.setZoomRatio(clamped); - _updateSession( - (s) => s.copyWith( - zoomRatio: zoom.zoomRatio, - minZoomRatio: zoom.minZoomRatio, - maxZoomRatio: zoom.maxZoomRatio, - errorMessage: null, - ), - ); - } on PlatformException catch (error) { - final message = error.code == 'ZOOM_FAILED' - ? '切换镜头失败,请重试' - : (error.message ?? '相机倍距设置失败'); - _updateSession((s) => s.copyWith(errorMessage: message)); - } finally { - _updateSession( - (s) => s.copyWith(isSwitchingLens: false, errorMessage: s.errorMessage), - ); - } - } - - /// 开始录制,可选开启勿扰模式。 - Future startRecording({bool enableDoNotDisturb = true}) async { - final session = state.session; - if (session.isRecording || - session.isStartingRecording || - session.isSwitchingLens) { - return; - } - if (!session.isPreviewReady) { - _updateSession((s) => s.copyWith(errorMessage: '相机预览未就绪,请稍后重试')); - return; - } - - final displayName = recordingFileNameForPlatform( - state.clipboardRecordingModel.filename, - ); - + void updateZoomCapabilities({ + required double zoomRatio, + required double minZoomRatio, + required double maxZoomRatio, + }) { _updateSession( - (s) => s.copyWith(isStartingRecording: true, errorMessage: null), + (s) => s.copyWith( + zoomRatio: zoomRatio, + minZoomRatio: minZoomRatio, + maxZoomRatio: maxZoomRatio, + errorMessage: null, + ), ); - try { - final result = await RecordingPlatform.startRecording( - enableDoNotDisturb: enableDoNotDisturb && state.session.hasDndAccess, - displayName: displayName, - ); - _updateSession( - (s) => s.copyWith( - status: result.status, - lastOutputPath: result.outputPath, - isTouchLocked: true, - errorMessage: null, - fileSaveFailed: false, - segmentOutputPaths: const [], - clearLastSaved: true, - ), - ); - } on PlatformException catch (error) { - _updateSession( - (s) => s.copyWith(errorMessage: error.message ?? '开始录制失败'), - ); - } finally { - _updateSession((s) => s.copyWith(isStartingRecording: false)); - } } - /// 停止录制、保存到文件夹,并恢复相机预览。 - Future stopRecording() async { - if (!state.session.isRecording || state.session.isSwitchingLens) return; + void markLensSwitching(bool switching) { + _updateSession((s) => s.copyWith(isSwitchingLens: switching)); + } - try { - final result = await RecordingPlatform.stopRecording(); - final fileFailed = !result.fileSaved; - final savedName = recordingFileNameForPlatform( - state.clipboardRecordingModel.filename, - ); + void setZoomRatioValue(double ratio) { + _updateSession((s) => s.copyWith(zoomRatio: ratio, errorMessage: null)); + } + + void setError(String message) { + _updateSession((s) => s.copyWith(errorMessage: message)); + } + + void markStartingRecording() { + _updateSession( + (s) => s.copyWith( + isStartingRecording: true, + errorMessage: null, + clearStreamResult: true, + ), + ); + } + + Future markRecordingStarted(String streamUrl) async { + if (state.session.hasDndAccess) { + await RecordingPlatform.enableDoNotDisturb(); + } + _recordingStartedAt = DateTime.now(); + _elapsedTimer?.cancel(); + _elapsedTimer = Timer.periodic(const Duration(seconds: 1), (_) { + final startedAt = _recordingStartedAt; + if (startedAt == null) return; + final elapsed = DateTime.now().difference(startedAt).inMilliseconds; _updateSession( (s) => s.copyWith( - status: result.status, - lastOutputPath: result.outputPath ?? s.lastOutputPath, - lastSavedDisplayName: fileFailed ? null : savedName, - errorMessage: fileFailed - ? (result.fileErrorMessage ?? '保存到文件夹失败,请检查文件保存权限') - : null, - fileSaveFailed: fileFailed, - segmentOutputPaths: result.segmentOutputPaths, + status: RecordingStatus( + state: RecordingState.recording, + streamUrl: streamUrl, + elapsedMillis: elapsed, + ), ), ); - } on PlatformException catch (error) { - _updateSession( - (s) => s.copyWith(errorMessage: error.message ?? '停止录制失败'), - ); - } finally { - await restorePreview(); - } + }); + _updateSession( + (s) => s.copyWith( + status: RecordingStatus( + state: RecordingState.recording, + streamUrl: streamUrl, + ), + lastStreamUrl: streamUrl, + isStartingRecording: false, + isTouchLocked: true, + errorMessage: null, + streamFailed: false, + clearStreamResult: true, + ), + ); + } + + void markRecordingStartFailed(String message) { + _recordingStartedAt = null; + _elapsedTimer?.cancel(); + _elapsedTimer = null; + _updateSession( + (s) => s.copyWith( + status: const RecordingStatus(state: RecordingState.previewing), + isStartingRecording: false, + errorMessage: message, + streamFailed: true, + ), + ); + } + + Future markRecordingStopped({String? errorMessage}) async { + final lastStreamUrl = state.session.lastStreamUrl; + final elapsed = _recordingStartedAt == null + ? state.session.status.elapsedMillis + : DateTime.now().difference(_recordingStartedAt!).inMilliseconds; + _recordingStartedAt = null; + _elapsedTimer?.cancel(); + _elapsedTimer = null; + await RecordingPlatform.disableDoNotDisturb(); + _updateSession( + (s) => s.copyWith( + status: RecordingStatus( + state: RecordingState.previewing, + streamUrl: lastStreamUrl, + elapsedMillis: elapsed, + ), + isStartingRecording: false, + errorMessage: errorMessage, + streamFinished: errorMessage == null, + streamFailed: errorMessage != null, + ), + ); } /// 切换录制中触屏锁定状态。 @@ -460,9 +255,9 @@ class RecordingViewModel extends Notifier { _updateSession((s) => s.copyWith(isTouchLocked: locked)); } - /// 清除上次保存成功的录制结果标记。 + /// 清除上次推流完成结果标记。 void clearSavedRecordingResult() { - _updateSession((s) => s.copyWith(clearLastSaved: true)); + _updateSession((s) => s.copyWith(clearStreamResult: true)); } /// 跳转系统勿扰/通知策略设置页。 @@ -489,22 +284,14 @@ class RecordingViewModel extends Notifier { Future teardown() async { await RecordingPlatform.setImmersiveMode(enabled: false); await RecordingPlatform.disableDoNotDisturb(); - await RecordingPlatform.disposePreview(); - await _statusSubscription?.cancel(); - _statusSubscription = null; + _recordingStartedAt = null; + _elapsedTimer?.cancel(); + _elapsedTimer = null; state = state.copyWith(session: const RecordingSessionState()); } - /// 订阅原生层录制状态流并同步到 session。 - Future _listenStatus() async { - await _statusSubscription?.cancel(); - _statusSubscription = RecordingPlatform.statusStream().listen((status) { - _updateSession((s) => s.copyWith(status: status)); - }); - } - /// Provider 销毁时取消状态流订阅。 Future _dispose() async { - await _statusSubscription?.cancel(); + _elapsedTimer?.cancel(); } } diff --git a/lib/features/recording/widgets/widget_camera_preview.dart b/lib/features/recording/widgets/widget_camera_preview.dart index 7c8def4..1335e99 100644 --- a/lib/features/recording/widgets/widget_camera_preview.dart +++ b/lib/features/recording/widgets/widget_camera_preview.dart @@ -1,34 +1,22 @@ -import 'dart:io'; - +import 'package:apivideo_live_stream/apivideo_live_stream.dart'; import 'package:flutter/material.dart'; -import 'package:flutter/services.dart'; class CameraPreviewWidget extends StatelessWidget { - const CameraPreviewWidget({super.key}); + const CameraPreviewWidget({ + super.key, + required this.controller, + required this.isReady, + }); + + final ApiVideoLiveStreamController controller; + final bool isReady; @override Widget build(BuildContext context) { - if (Platform.isAndroid) { - return AndroidView( - viewType: 'recording-camera-preview', - layoutDirection: TextDirection.ltr, - creationParams: const {}, - creationParamsCodec: const StandardMessageCodec(), - ); + if (!isReady) { + return const ColoredBox(color: Colors.black); } - if (Platform.isIOS) { - return UiKitView( - viewType: 'recording-camera-preview', - layoutDirection: TextDirection.ltr, - creationParams: const {}, - creationParamsCodec: const StandardMessageCodec(), - ); - } - - return const ColoredBox( - color: Colors.black, - child: Center(child: Text('当前平台不支持相机预览')), - ); + return ApiVideoCameraPreview(controller: controller, fit: BoxFit.cover); } } diff --git a/lib/features/recording/widgets/widget_record_header.dart b/lib/features/recording/widgets/widget_record_header.dart index 0b99cec..b39a4b0 100644 --- a/lib/features/recording/widgets/widget_record_header.dart +++ b/lib/features/recording/widgets/widget_record_header.dart @@ -1,51 +1,32 @@ import 'package:flutter/material.dart'; -import 'package:flutter/services.dart'; import 'package:flutter_screenutil/flutter_screenutil.dart'; import 'package:recording_tool/features/recording/widgets/record_content_transition.dart'; import 'package:recording_tool/gen/assets.gen.dart'; -import 'package:recording_tool/shared/widgets/app_toast.dart'; -/// 录制页顶部:Logo、粘贴赛事、赛事标题 +/// 录制页顶部:Logo、赛事标题 class RecordHeaderWidget extends StatelessWidget { const RecordHeaderWidget({ super.key, - required this.hasValidClipboardInfo, this.eventTitle, required this.isRecording, - required this.onPasteEventInfo, - required this.onClearEventInfo, }); - final bool hasValidClipboardInfo; final String? eventTitle; final bool isRecording; - final Future Function() onPasteEventInfo; - final VoidCallback onClearEventInfo; - bool get _showPasteButtons => !hasValidClipboardInfo && !isRecording; - - bool get _showEventTitle => hasValidClipboardInfo; + bool get _showEventTitle => eventTitle?.trim().isNotEmpty == true; Widget _buildAnimatedHeaderContent() { if (_showEventTitle) { return _HeaderEventTitleRow( key: ValueKey('title-${eventTitle ?? ''}'), title: eventTitle ?? '', - isRecording: isRecording, - onClearEventInfo: onClearEventInfo, ); } return const SizedBox.shrink(key: ValueKey('header-empty')); } - void _mockCopyEventInfo() { - const strTemp = - '{"title":"蔡依婷vs夏志豪 空中格斗赛 初中组","address":"黑龙江省鹤岗市11111","filename":"蔡依婷_夏志豪_测试循环赛-7_空中格斗赛"}'; - Clipboard.setData(const ClipboardData(text: strTemp)); - AppToast.show('模拟复制赛事信息成功'); - } - @override Widget build(BuildContext context) { return SafeArea( @@ -75,14 +56,6 @@ class RecordHeaderWidget extends StatelessWidget { transitionBuilder: RecordContentTransition.builder, child: _buildAnimatedHeaderContent(), ), - if (_showPasteButtons) - Align( - alignment: Alignment.centerRight, - child: _HeaderPasteActions( - onMockCopy: _mockCopyEventInfo, - onPasteEventInfo: onPasteEventInfo, - ), - ), ], ), ), @@ -95,16 +68,9 @@ class RecordHeaderWidget extends StatelessWidget { } class _HeaderEventTitleRow extends StatelessWidget { - const _HeaderEventTitleRow({ - super.key, - required this.title, - required this.isRecording, - required this.onClearEventInfo, - }); + const _HeaderEventTitleRow({super.key, required this.title}); final String title; - final bool isRecording; - final VoidCallback onClearEventInfo; static TextStyle get _overlayTextStyle => TextStyle( color: Colors.white, @@ -135,87 +101,7 @@ class _HeaderEventTitleRow extends StatelessWidget { ), ), ), - !isRecording - ? IconButton( - key: const ValueKey('clear-event-info'), - onPressed: onClearEventInfo, - icon: Assets.images.imageDelete.image( - width: 15.r, - height: 15.r, - fit: BoxFit.contain, - excludeFromSemantics: true, - ), - padding: EdgeInsets.zero, - constraints: BoxConstraints(minWidth: 40.r, minHeight: 40.r), - alignment: Alignment.centerRight, - tooltip: '删除', - ) - : const SizedBox.shrink(key: ValueKey('clear-event-info-hidden')), ], ); } } - -class _HeaderPasteActions extends StatelessWidget { - const _HeaderPasteActions({ - required this.onMockCopy, - required this.onPasteEventInfo, - }); - - final VoidCallback onMockCopy; - final Future Function() onPasteEventInfo; - - @override - Widget build(BuildContext context) { - return Row( - mainAxisAlignment: MainAxisAlignment.end, - children: [ - // _HeaderActionButton(label: 'mock', onPressed: onMockCopy), - _HeaderActionButton( - label: '粘贴选手信息', - onPressed: () => onPasteEventInfo(), - icon: Assets.images.imageCopy.image( - width: 10.r, - height: 10.r, - fit: BoxFit.contain, - excludeFromSemantics: true, - ), - ), - ], - ); - } -} - -class _HeaderActionButton extends StatelessWidget { - const _HeaderActionButton({ - required this.label, - required this.onPressed, - this.icon, - }); - - final String label; - final VoidCallback onPressed; - final Widget? icon; - - @override - Widget build(BuildContext context) { - return TextButton.icon( - onPressed: onPressed, - icon: icon ?? Icon(Icons.content_paste, size: 10.r), - label: Text(label), - - style: TextButton.styleFrom( - minimumSize: Size.zero, // 取消 40dp 最小高度 - tapTargetSize: MaterialTapTargetSize.shrinkWrap, // 取消额外点击热区 - foregroundColor: Colors.white, - backgroundColor: Colors.black.withValues(alpha: 0.5), - textStyle: TextStyle(fontSize: 10.sp), - padding: EdgeInsets.symmetric(horizontal: 7.r, vertical: 4.r), - shape: RoundedRectangleBorder( - borderRadius: BorderRadius.circular(25.r), - side: const BorderSide(color: Colors.white30), - ), - ), - ); - } -} diff --git a/lib/features/recording/widgets/widget_clipboard_address_clock_chip.dart b/lib/features/recording/widgets/widget_recording_context_clock_chip.dart similarity index 74% rename from lib/features/recording/widgets/widget_clipboard_address_clock_chip.dart rename to lib/features/recording/widgets/widget_recording_context_clock_chip.dart index cf82c6b..e94c50c 100644 --- a/lib/features/recording/widgets/widget_clipboard_address_clock_chip.dart +++ b/lib/features/recording/widgets/widget_recording_context_clock_chip.dart @@ -5,19 +5,19 @@ import 'package:flutter_screenutil/flutter_screenutil.dart'; import 'package:recording_tool/core/utils/date_time_formatter.dart'; import 'package:recording_tool/features/recording/widgets/record_content_transition.dart'; -/// 左下角实时时钟与剪贴板地址 -class ClipboardAddressClockChipWidget extends StatefulWidget { - const ClipboardAddressClockChipWidget({super.key, required this.address}); +/// 左下角实时时钟与赛事场地信息。 +class RecordingContextClockChipWidget extends StatefulWidget { + const RecordingContextClockChipWidget({super.key, required this.address}); final String address; @override - State createState() => - _ClipboardAddressClockChipWidgetState(); + State createState() => + _RecordingContextClockChipWidgetState(); } -class _ClipboardAddressClockChipWidgetState - extends State { +class _RecordingContextClockChipWidgetState + extends State { Timer? _clockTimer; static TextStyle get _textStyle => TextStyle( @@ -42,10 +42,8 @@ class _ClipboardAddressClockChipWidgetState super.dispose(); } - String get _nowText => DateTimeFormatter.format( - DateTime.now(), - pattern: 'yyyy-M-d-H:mm:ss', - ); + String get _nowText => + DateTimeFormatter.format(DateTime.now(), pattern: 'yyyy-M-d-H:mm:ss'); @override Widget build(BuildContext context) { @@ -71,7 +69,9 @@ class _ClipboardAddressClockChipWidgetState key: ValueKey(widget.address), style: _textStyle, ) - : const SizedBox.shrink(key: ValueKey('clipboard-address-empty')), + : const SizedBox.shrink( + key: ValueKey('recording-address-empty'), + ), ), ], ), diff --git a/lib/features/recording/widgets/widget_recording_hud.dart b/lib/features/recording/widgets/widget_recording_hud.dart index ab76bc3..309e646 100644 --- a/lib/features/recording/widgets/widget_recording_hud.dart +++ b/lib/features/recording/widgets/widget_recording_hud.dart @@ -3,8 +3,8 @@ import 'package:flutter_screenutil/flutter_screenutil.dart'; import 'package:permission_handler/permission_handler.dart'; import 'package:recording_tool/core/utils/rate_limiter.dart'; import 'package:recording_tool/features/recording/widgets/record_content_transition.dart'; -import 'package:recording_tool/features/recording/widgets/widget_clipboard_address_clock_chip.dart'; import 'package:recording_tool/features/recording/widgets/widget_recording_button.dart'; +import 'package:recording_tool/features/recording/widgets/widget_recording_context_clock_chip.dart'; import 'package:recording_tool/features/recording/widgets/widget_recording_setup_hints.dart'; /// 录制页 HUD 层(状态提示、录制控制) @@ -20,8 +20,8 @@ class RecordingHudWidget extends StatelessWidget { required this.isStartingRecording, required this.isSwitchingLens, required this.isTouchLocked, - this.showClipboardHint = false, - this.clipboardAddress = '', + this.showContextHint = false, + this.contextAddress = '', required this.zoomRatio, required this.minZoomRatio, required this.maxZoomRatio, @@ -42,8 +42,8 @@ class RecordingHudWidget extends StatelessWidget { final bool isStartingRecording; final bool isSwitchingLens; final bool isTouchLocked; - final bool showClipboardHint; - final String clipboardAddress; + final bool showContextHint; + final String contextAddress; final double zoomRatio; final double minZoomRatio; final double maxZoomRatio; @@ -117,12 +117,14 @@ class RecordingHudWidget extends StatelessWidget { switchOutCurve: Curves.easeInCubic, layoutBuilder: RecordContentTransition.bottomStackLayoutBuilder, transitionBuilder: RecordContentTransition.builder, - child: showClipboardHint - ? ClipboardAddressClockChipWidget( - key: const ValueKey('clipboard-info'), - address: clipboardAddress, + child: showContextHint + ? RecordingContextClockChipWidget( + key: const ValueKey('recording-context-info'), + address: contextAddress, ) - : const SizedBox.shrink(key: ValueKey('clipboard-info-hidden')), + : const SizedBox.shrink( + key: ValueKey('recording-context-info-hidden'), + ), ), ), if (isRecording) diff --git a/lib/features/recording/widgets/widget_recording_saved_dialog.dart b/lib/features/recording/widgets/widget_recording_saved_dialog.dart index 584ed17..8c7e0ae 100644 --- a/lib/features/recording/widgets/widget_recording_saved_dialog.dart +++ b/lib/features/recording/widgets/widget_recording_saved_dialog.dart @@ -1,7 +1,7 @@ import 'package:flutter/material.dart'; -import 'package:recording_tool/features/dialog/dialog-record.dart'; +import 'package:recording_tool/features/recording/dialog/dialog-record.dart'; -/// 录制结束并保存到文件夹后的后续操作弹窗。 +/// 推流录制结束后的后续操作弹窗。 Future showRecordingSavedDialog( BuildContext context, { required String sessionTitle, @@ -10,7 +10,7 @@ Future showRecordingSavedDialog( }) { return RecordDialog.showDouble( context, - title: '本轮比赛视频已保存到文件夹\n请选择后续录制信息', + title: '本轮比赛视频已提交 NAS 录制\n请选择后续录制信息', leftText: '继续本轮', rightText: '录制新轮', onLeftPressed: onContinueRound, diff --git a/lib/features/scan_qrcode/pages/page_push_test.dart b/lib/features/scan_qrcode/pages/page_push_test.dart new file mode 100644 index 0000000..5551031 --- /dev/null +++ b/lib/features/scan_qrcode/pages/page_push_test.dart @@ -0,0 +1,131 @@ +import 'package:apivideo_live_stream/apivideo_live_stream.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:recording_tool/features/scan_qrcode/utils/rtmp_stream_target.dart'; +import 'package:recording_tool/shared/widgets/app_bar.dart'; +import 'package:recording_tool/shared/widgets/app_toast.dart'; + +class PushSteamTestWidget extends StatefulWidget { + const PushSteamTestWidget({ + super.key, + this.rtmpUrl = + 'rtmp://192.168.1.245:19090/蔡依婷vs夏志豪_空中格斗赛_高中组/蔡依婷vs夏志豪_空中格斗赛_高中组', + }); + + final String rtmpUrl; + + @override + State createState() => _PushSteamTestWidgetState(); +} + +class _PushSteamTestWidgetState extends State + with WidgetsBindingObserver { + late final ApiVideoLiveStreamController _controller; + bool _ready = false; + bool _isStreaming = false; + + @override + void initState() { + super.initState(); + WidgetsBinding.instance.addObserver(this); + + _controller = ApiVideoLiveStreamController( + initialAudioConfig: AudioConfig(bitrate: 128000), + initialVideoConfig: VideoConfig.withDefaultBitrate( + resolution: Resolution.RESOLUTION_1080, + fps: 30, + ), + onConnectionSuccess: () => { + debugPrint('推流成功'), + + setState(() => _isStreaming = true), + }, + onConnectionFailed: (reason) { + setState(() => _isStreaming = false); + debugPrint('推流失败: $reason'); + }, + onDisconnection: () => { + debugPrint('推流断开'), + + setState(() => _isStreaming = false), + }, + ); + WidgetsBinding.instance.addPostFrameCallback((_) => _initialize()); + } + + Future _initialize() async { + try { + await _controller.initialize(); + await _controller.startPreview(); + + setState(() => _ready = true); + } catch (e) { + debugPrint('初始化失败: $e'); + } + } + + Future _startPush() async { + try { + final target = RtmpStreamTarget.parse(widget.rtmpUrl); + await _controller.startStreaming( + streamKey: target.streamKey, + url: target.url, + ); + } on FormatException catch (e) { + debugPrint('推流地址错误: ${e.message}'); + AppToast.show(e.message); + } on PlatformException catch (e) { + final message = e.message ?? e.code; + debugPrint('推流失败: ${e.code} $message'); + AppToast.show('推流失败: $message'); + } catch (e) { + debugPrint('推流失败: $e'); + AppToast.showError(e); + } + } + + Future _stopPush() => _controller.stopStreaming(); + + @override + void didChangeAppLifecycleState(AppLifecycleState state) { + if (state == AppLifecycleState.inactive) { + _controller.stop(); + } else if (state == AppLifecycleState.resumed) { + _controller.startPreview(); + } + } + + @override + void dispose() { + WidgetsBinding.instance.removeObserver(this); + _controller.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + return Scaffold( + appBar: myAppBar(context: context), + body: Stack( + children: [ + if (_ready) + ApiVideoCameraPreview(controller: _controller, fit: BoxFit.cover), + Positioned( + bottom: 32, + left: 0, + right: 0, + child: Center( + child: FloatingActionButton( + backgroundColor: _isStreaming ? Colors.red : Colors.green, + onPressed: _ready + ? (_isStreaming ? _stopPush : _startPush) + : null, + child: Icon(_isStreaming ? Icons.stop : Icons.circle), + ), + ), + ), + ], + ), + ); + } +} diff --git a/lib/features/scan_qrcode/pages/page_scan_qrcode.dart b/lib/features/scan_qrcode/pages/page_scan_qrcode.dart index 192bca9..4a930e2 100644 --- a/lib/features/scan_qrcode/pages/page_scan_qrcode.dart +++ b/lib/features/scan_qrcode/pages/page_scan_qrcode.dart @@ -1,33 +1,61 @@ import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter_screenutil/flutter_screenutil.dart'; import 'package:recording_tool/app/router/app_navigator.dart'; +import 'package:recording_tool/core/cache/app_storage.dart'; +import 'package:recording_tool/core/cache/storage_keys.dart'; +import 'package:recording_tool/features/auth/pages/page_auth.dart'; +import 'package:recording_tool/features/auth/view_model_auth/view_model_auth.dart'; +import 'package:recording_tool/features/events/pages/page_event_info.dart'; +import 'package:recording_tool/features/recording/model/model_recording_context.dart'; +import 'package:recording_tool/shared/widgets/app_bar.dart'; import 'package:recording_tool/shared/widgets/app_button.dart'; import 'package:recording_tool/shared/widgets/app_qr_scanner_dialog.dart'; -import 'package:recording_tool/shared/widgets/app_webview.dart'; +import 'package:recording_tool/shared/widgets/app_toast.dart'; -class ScanQrCodePage extends StatefulWidget { +class ScanQrCodePage extends ConsumerStatefulWidget { const ScanQrCodePage({super.key}); + static const mockRtmpUrl = + 'rtmp://192.168.1.245:19090/蔡依婷vs夏志豪_空中格斗赛_高中组/蔡依婷vs夏志豪_空中格斗赛_高中组'; + + static const mockRecordingContext = RecordingContext( + eventTitle: '全国青少年无人机大赛', + matchName: '空中格斗赛', + group: '高中组', + venue: '场地 1', + time: '7月1日 12:00-15:00', + playerName: '蔡依婷vs夏志豪', + playerPhone: '', + ); + @override - State createState() => _AuthPageWidgetState(); + ConsumerState createState() => _AuthPageWidgetState(); } -class _AuthPageWidgetState extends State { +class _AuthPageWidgetState extends ConsumerState { + @override + void initState() { + super.initState(); + WidgetsBinding.instance.addPostFrameCallback((_) async { + final token = AppStorage.getString(StorageKeys.authToken); + if (token?.isNotEmpty ?? false) { + final success = await ref + .read(authProvider.notifier) + .parseTokenSetState(token!); + if (!success) { + AppToast.show('请重新鉴权'); + AppNavigator.pushAndRemoveUntil(const AuthPageWidget()); + return; + } + } + }); + } + @override Widget build(BuildContext context) { return Scaffold( - appBar: AppBar( - leading: IconButton( - icon: const Icon(Icons.arrow_back), - onPressed: () { - Navigator.of(context).maybePop(); - }, - ), - centerTitle: true, - elevation: 0, - backgroundColor: Colors.transparent, - foregroundColor: Colors.black, - ), + appBar: myAppBar(context: context, title: '扫码'), body: Center( child: Column( children: [ @@ -40,17 +68,44 @@ class _AuthPageWidgetState extends State { ), SizedBox(height: 20.h), + Consumer( + builder: (context, ref, child) { + return SizedBox( + width: 280.w, + height: 80.h, + child: AppButton( + label: '查看录像', + onPressed: () async { + final data = ref.watch( + authProvider.select((state) => state.jwtDecodedData), + ); + if (data == null) return; + debugPrint('赛事名字: ${data.eventName}'); + final eventName = data.eventName ?? ''; + await ref + .read(authProvider.notifier) + .getRecordList(eventName); + }, + variant: AppButtonVariant.secondary, + ), + ); + }, + ), + SizedBox(height: 16.h), SizedBox( width: 280.w, height: 80.h, child: AppButton( label: '扫码', onPressed: () async { - final result = await AppQrScannerDialog.show(context); - if (result == null || result.isEmpty) return; - debugPrint('扫码结果: $result'); + final String? playerId = await AppQrScannerDialog.show( + context, + ); + if (playerId == null || playerId.isEmpty) return; + + /// TODO AppNavigator.push( - const WebviewPage(url: 'https://www.dronex.cc/'), + EventInfoPage(playerId: '74300708945530955'), ); }, variant: AppButtonVariant.secondary, diff --git a/lib/features/scan_qrcode/utils/rtmp_stream_target.dart b/lib/features/scan_qrcode/utils/rtmp_stream_target.dart new file mode 100644 index 0000000..5e0d523 --- /dev/null +++ b/lib/features/scan_qrcode/utils/rtmp_stream_target.dart @@ -0,0 +1,33 @@ +class RtmpStreamTarget { + const RtmpStreamTarget({required this.url, required this.streamKey}); + + final String url; + final String streamKey; + + factory RtmpStreamTarget.parse(String value) { + final source = value.trim(); + final uri = Uri.tryParse(source); + if (uri == null || + (uri.scheme != 'rtmp' && uri.scheme != 'rtmps') || + uri.host.isEmpty) { + throw const FormatException('推流地址必须是 rtmp:// 或 rtmps:// 开头的完整地址'); + } + + final pathSegments = uri.pathSegments + .where((segment) => segment.trim().isNotEmpty) + .toList(growable: false); + if (pathSegments.length < 2) { + throw const FormatException('推流地址路径必须包含 app 和 streamKey,例如 /app/xxxx'); + } + + final appPath = pathSegments.take(pathSegments.length - 1).join('/'); + final streamKey = pathSegments.last; + final baseUrl = uri + .replace(path: '/$appPath', query: null, fragment: null) + .toString(); + + return RtmpStreamTarget(url: baseUrl, streamKey: streamKey); + } + + String get fullUrl => '$url/$streamKey'; +} diff --git a/lib/gen/assets.gen.dart b/lib/gen/assets.gen.dart index d2870ba..80a04cf 100644 --- a/lib/gen/assets.gen.dart +++ b/lib/gen/assets.gen.dart @@ -11,6 +11,16 @@ import 'package:flutter/widgets.dart'; +class $AssetsHtmlGen { + const $AssetsHtmlGen(); + + /// File path: assets/html/index.html + String get index => 'assets/html/index.html'; + + /// List of all assets + List get values => [index]; +} + class $AssetsImagesGen { const $AssetsImagesGen(); @@ -30,18 +40,24 @@ class $AssetsImagesGen { AssetGenImage get imageLogo => const AssetGenImage('assets/images/image_logo.png'); + /// File path: assets/images/image_vs.png + AssetGenImage get imageVs => + const AssetGenImage('assets/images/image_vs.png'); + /// List of all assets List get values => [ imageCopy, imageDelete, imageDialogBg, imageLogo, + imageVs, ]; } class Assets { const Assets._(); + static const $AssetsHtmlGen html = $AssetsHtmlGen(); static const $AssetsImagesGen images = $AssetsImagesGen(); } diff --git a/lib/shared/widgets/app_bar.dart b/lib/shared/widgets/app_bar.dart new file mode 100644 index 0000000..3e7904a --- /dev/null +++ b/lib/shared/widgets/app_bar.dart @@ -0,0 +1,31 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_screenutil/flutter_screenutil.dart'; + +AppBar myAppBar({ + required BuildContext context, + String title = '', + Widget? titleWidget, +}) => AppBar( + leadingWidth: 56.w, + leading: IconButton( + icon: const Icon(Icons.arrow_back), + onPressed: () { + Navigator.of(context).maybePop(); + }, + ), + title: + titleWidget ?? + Text( + title, + textAlign: TextAlign.center, + style: TextStyle( + color: Colors.white, + fontSize: 20.sp, + fontFamily: 'PingFang SC', + fontWeight: FontWeight.w400, + ), + ), + centerTitle: true, + backgroundColor: Colors.transparent, + elevation: 0, +); diff --git a/lib/shared/widgets/app_qr_scanner_dialog.dart b/lib/shared/widgets/app_qr_scanner_dialog.dart index dde2fbe..b1142d8 100644 --- a/lib/shared/widgets/app_qr_scanner_dialog.dart +++ b/lib/shared/widgets/app_qr_scanner_dialog.dart @@ -41,6 +41,7 @@ class _AppQrScannerDialogState extends State detectionSpeed: DetectionSpeed.noDuplicates, facing: CameraFacing.back, formats: const [BarcodeFormat.qrCode], + autoZoom: true, ); _scanLineController = AnimationController( vsync: this, @@ -63,18 +64,32 @@ class _AppQrScannerDialogState extends State _hasScanned = true; final navigator = Navigator.of(context, rootNavigator: true); + debugPrint('扫码结果: $value'); + if (!mounted) return; + if (navigator.canPop()) { + navigator.pop(value); + } + unawaited(_stopScanner()); + } + + void _handleDetectError(Object error, StackTrace stackTrace) { + debugPrint('扫码识别失败: $error'); + } + + Future _stopScanner() async { try { await _controller.stop(); } catch (error) { debugPrint('停止扫码相机失败: $error'); } - - if (!mounted) return; - navigator.pop(value); } void _close() { - Navigator.of(context, rootNavigator: true).pop(); + if (!mounted) return; + final navigator = Navigator.of(context, rootNavigator: true); + if (navigator.canPop()) { + navigator.pop(); + } } Rect _scanWindowFor(Size size) { @@ -98,8 +113,8 @@ class _AppQrScannerDialogState extends State child: MobileScanner( controller: _controller, fit: BoxFit.cover, - scanWindow: scanWindow, onDetect: _handleDetect, + onDetectError: _handleDetectError, errorBuilder: _buildCameraError, placeholderBuilder: (_) => const ColoredBox( color: Colors.black, diff --git a/lib/shared/widgets/app_text.dart b/lib/shared/widgets/app_text.dart new file mode 100644 index 0000000..c30c71c --- /dev/null +++ b/lib/shared/widgets/app_text.dart @@ -0,0 +1,234 @@ +import 'package:flutter/material.dart'; + +/// 全局文本尺寸语义。 +/// +/// 业务代码应优先选择语义化的 variant,而不是直接散落 `fontSize`。 +/// 这样后续调整整套字号体系时,只需要维护这一处映射。 +enum AppTextVariant { + display, + headline, + title, + subtitle, + body, + bodySmall, + label, + caption, +} + +/// 全局文本颜色语义。 +/// +/// tone 只表达“文本在界面中的语义角色”,具体颜色从当前 Theme 解析, +/// 避免页面直接依赖硬编码色值。 +enum AppTextTone { + primary, + secondary, + tertiary, + inverse, + brand, + success, + warning, + danger, + disabled, +} + +/// 应用级文本组件。 +/// +/// `AppText` 是对 Flutter `Text` 的轻量封装,目标是统一页面里的字号、 +/// 字重、颜色和溢出策略,同时保留 `Text` 的常用能力。 +/// +/// 使用建议: +/// - 普通文案使用默认 `AppText('内容')`。 +/// - 标题使用 `variant: AppTextVariant.title`。 +/// - 错误、警告、成功等状态文案使用 `tone`,不要在业务里直接写颜色。 +/// - 只有遇到一次性视觉细节时才传入 `style`、`fontSize` 或 `fontWeight`。 +class AppText extends StatelessWidget { + const AppText( + this.data, { + super.key, + this.variant = AppTextVariant.body, + this.tone = AppTextTone.primary, + this.style, + this.color, + this.fontSize, + this.fontWeight, + this.height, + this.letterSpacing, + this.textAlign, + this.textDirection, + this.locale, + this.softWrap, + this.overflow, + this.maxLines, + this.semanticsLabel, + this.textWidthBasis, + this.textHeightBehavior, + this.textScaler, + this.selectionColor, + }) : textSpan = null; + + /// 富文本构造器。 + /// + /// 用于同一段文案中存在局部强调、不同颜色或不同字重的场景。 + /// 外层的 `variant`、`tone` 和通用排版参数仍会作为默认样式作用到 span。 + const AppText.rich( + this.textSpan, { + super.key, + this.variant = AppTextVariant.body, + this.tone = AppTextTone.primary, + this.style, + this.color, + this.fontSize, + this.fontWeight, + this.height, + this.letterSpacing, + this.textAlign, + this.textDirection, + this.locale, + this.softWrap, + this.overflow, + this.maxLines, + this.semanticsLabel, + this.textWidthBasis, + this.textHeightBehavior, + this.textScaler, + this.selectionColor, + }) : data = null; + + /// 普通文本内容。与 [textSpan] 二选一。 + final String? data; + + /// 富文本内容。与 [data] 二选一。 + final InlineSpan? textSpan; + + /// 文本尺寸和基础字重语义。 + final AppTextVariant variant; + + /// 文本颜色语义。 + final AppTextTone tone; + + /// 额外样式覆盖。优先级高于 variant 和 tone。 + final TextStyle? style; + + /// 显式颜色覆盖。优先级高于 tone 和 `style.color`。 + final Color? color; + + /// 一次性字号覆盖。常规场景优先使用 [variant]。 + final double? fontSize; + + /// 一次性字重覆盖。常规场景优先使用 [variant]。 + final FontWeight? fontWeight; + + /// 行高覆盖。 + final double? height; + + /// 字间距覆盖。 + final double? letterSpacing; + + final TextAlign? textAlign; + final TextDirection? textDirection; + final Locale? locale; + final bool? softWrap; + final TextOverflow? overflow; + final int? maxLines; + final String? semanticsLabel; + final TextWidthBasis? textWidthBasis; + final TextHeightBehavior? textHeightBehavior; + final TextScaler? textScaler; + final Color? selectionColor; + + @override + Widget build(BuildContext context) { + final effectiveStyle = _resolveStyle(context); + + if (textSpan != null) { + return Text.rich( + textSpan!, + style: effectiveStyle, + textAlign: textAlign, + textDirection: textDirection, + locale: locale, + softWrap: softWrap, + overflow: overflow, + maxLines: maxLines, + semanticsLabel: semanticsLabel, + textWidthBasis: textWidthBasis, + textHeightBehavior: textHeightBehavior, + textScaler: textScaler, + selectionColor: selectionColor, + ); + } + + return Text( + data ?? '', + style: effectiveStyle, + textAlign: textAlign, + textDirection: textDirection, + locale: locale, + softWrap: softWrap, + overflow: overflow, + maxLines: maxLines, + semanticsLabel: semanticsLabel, + textWidthBasis: textWidthBasis, + textHeightBehavior: textHeightBehavior, + textScaler: textScaler, + selectionColor: selectionColor, + ); + } + + /// 合成最终样式。 + /// + /// 优先级从低到高: + /// 1. Theme 中的 TextTheme。 + /// 2. `variant` 与 `tone` 对应的默认样式。 + /// 3. 外部传入的 `style`。 + /// 4. `color`、`fontSize`、`fontWeight` 等显式字段。 + TextStyle _resolveStyle(BuildContext context) { + final baseStyle = _variantStyle(Theme.of(context).textTheme); + final toneStyle = baseStyle.copyWith(color: _toneColor(context)); + final mergedStyle = style == null ? toneStyle : toneStyle.merge(style); + + return mergedStyle.copyWith( + color: color ?? mergedStyle.color, + fontSize: fontSize ?? mergedStyle.fontSize, + fontWeight: fontWeight ?? mergedStyle.fontWeight, + height: height ?? mergedStyle.height, + letterSpacing: letterSpacing ?? mergedStyle.letterSpacing, + ); + } + + TextStyle _variantStyle(TextTheme textTheme) { + return switch (variant) { + AppTextVariant.display => + textTheme.displaySmall ?? const TextStyle(fontSize: 36), + AppTextVariant.headline => + textTheme.headlineSmall ?? const TextStyle(fontSize: 24), + AppTextVariant.title => + textTheme.titleMedium ?? const TextStyle(fontSize: 16), + AppTextVariant.subtitle => + textTheme.titleSmall ?? const TextStyle(fontSize: 14), + AppTextVariant.body => + textTheme.bodyMedium ?? const TextStyle(fontSize: 14), + AppTextVariant.bodySmall => + textTheme.bodySmall ?? const TextStyle(fontSize: 12), + AppTextVariant.label => + textTheme.labelLarge ?? const TextStyle(fontSize: 14), + AppTextVariant.caption => + textTheme.labelSmall ?? const TextStyle(fontSize: 11), + }; + } + + Color _toneColor(BuildContext context) { + final colors = Theme.of(context).colorScheme; + return switch (tone) { + AppTextTone.primary => colors.onSurface, + AppTextTone.secondary => colors.onSurfaceVariant, + AppTextTone.tertiary => colors.outline, + AppTextTone.inverse => colors.onInverseSurface, + AppTextTone.brand => colors.primary, + AppTextTone.success => colors.tertiary, + AppTextTone.warning => colors.secondary, + AppTextTone.danger => colors.error, + AppTextTone.disabled => colors.onSurface.withValues(alpha: 0.38), + }; + } +} diff --git a/lib/shared/widgets/app_webview.dart b/lib/shared/widgets/app_webview.dart index 0c724fb..be2677b 100644 --- a/lib/shared/widgets/app_webview.dart +++ b/lib/shared/widgets/app_webview.dart @@ -1,20 +1,34 @@ +import 'dart:async'; +import 'dart:convert'; + import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; +import 'package:recording_tool/app/router/app_navigator.dart'; import 'package:webview_flutter/webview_flutter.dart'; import 'package:webview_flutter_android/webview_flutter_android.dart'; import 'package:webview_flutter_wkwebview/webview_flutter_wkwebview.dart'; class WebviewPage extends StatefulWidget { - final String url; + final String? url; final String? title; + final String? assetPath; + final bool? canPop; - const WebviewPage({super.key, required this.url, this.title}); + const WebviewPage({ + super.key, + this.url, + this.title, + this.assetPath, + this.canPop, + }); @override State createState() => WebviewPageState(); } class WebviewPageState extends State { + static const String _javaScriptChannelName = 'AppBridge'; + WebViewController? _controller; bool _isLoading = true; String? _errorMessage; @@ -25,12 +39,23 @@ class WebviewPageState extends State { _initController(); } + @override + void dispose() { + final controller = _controller; + _controller = null; + if (controller != null) { + unawaited(_disposeWebViewController(controller)); + } + super.dispose(); + } + Future _initController() async { - if (widget.url?.isEmpty ?? true) { + if ((widget.url?.isEmpty ?? true) && widget.assetPath == null) { return; } final params = _createPlatformParams(); - final controller = WebViewController.fromPlatformCreationParams(params) + late final WebViewController controller; + controller = WebViewController.fromPlatformCreationParams(params) ..setJavaScriptMode(JavaScriptMode.unrestricted) ..setBackgroundColor(Colors.transparent) ..setNavigationDelegate( @@ -46,8 +71,10 @@ class WebviewPageState extends State { _errorMessage = null; }); }, - onPageFinished: (String url) { + onPageFinished: (String url) async { debugPrint('webview - page finished: $url'); + // await _injectPostMessageBridge(controller); + await _injectH5NeedData(controller); if (!mounted) return; setState(() => _isLoading = false); }, @@ -72,17 +99,28 @@ class WebviewPageState extends State { ), ); + controller.addJavaScriptChannel( + _javaScriptChannelName, + onMessageReceived: (JavaScriptMessage message) { + _onMessageReceived(message); + }, + ); + if (controller.platform is AndroidWebViewController) { AndroidWebViewController.enableDebugging(kDebugMode); await (controller.platform as AndroidWebViewController) .setMediaPlaybackRequiresUserGesture(false); } - final targetUrl = widget.url ?? ''; try { - await controller.loadRequest(Uri.parse(targetUrl)); + if (widget.assetPath != null) { + await controller.loadFlutterAsset(widget.assetPath!); + } else { + final targetUrl = widget.url ?? ''; + await controller.loadRequest(Uri.parse(targetUrl)); + } } catch (e) { - debugPrint('webview - loadRequest failed: $e'); + debugPrint('webview - load failed: $e'); if (!mounted) return; setState(() { _isLoading = false; @@ -91,10 +129,79 @@ class WebviewPageState extends State { return; } - if (!mounted) return; + if (!mounted) { + unawaited(_disposeWebViewController(controller)); + return; + } setState(() => _controller = controller); } + Future _disposeWebViewController(WebViewController controller) async { + await _runWebViewCleanupStep( + 'reset navigation delegate', + () => controller.setNavigationDelegate(NavigationDelegate()), + ); + await _runWebViewCleanupStep( + 'remove javascript channel', + () => controller.removeJavaScriptChannel(_javaScriptChannelName), + ); + await _runWebViewCleanupStep( + 'load blank page', + () => controller.loadRequest(Uri.parse('about:blank')), + ); + await _runWebViewCleanupStep('clear cache', controller.clearCache); + await _runWebViewCleanupStep( + 'clear local storage', + controller.clearLocalStorage, + ); + await _runWebViewCleanupStep( + 'clear cookies', + () => WebViewCookieManager().clearCookies(), + ); + } + + Future _runWebViewCleanupStep( + String step, + Future Function() cleanup, + ) async { + try { + debugPrint('webview - dispose cleanup at $step '); + + await cleanup(); + } catch (e) { + debugPrint('webview - dispose cleanup failed at $step: $e'); + } + } + + void _onMessageReceived(JavaScriptMessage message) { + debugPrint('收到来自 WebView 的消息: ${message.message}'); + final jsonMap = json.decode(message.message); + if (jsonMap['type'] != null && jsonMap['type'] == 'navigator_pop') { + Navigator.of(context).maybePop(); + } + } + + /// 脚本注入传输给h5 数据 + Future _injectH5NeedData(WebViewController controller) async { + final token = + 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOjgxNDI4NTczNTY2NjY4ODAwLCJkYXRhIjp7fSwic3ViIjoiODE0Mjg1NzM1NjY2Njg4MDAiLCJleHAiOjE3ODM5MzM1ODQsIm5iZiI6MTc4MzMyODc4NCwiaWF0IjoxNzgzMzI4Nzg0fQ.r1wYfvpV-5HIgwUuvq1Or3jPgjc3AhfJmoV1PNP23-Y'; + try { + await controller.runJavaScript(''' + (function () { + if (window.__appInstallData) { + return; + } + window.__appInstallData = ${true}; + + window.AppBridge.token = '$token'; + + })(); + '''); + } catch (e) { + debugPrint('webview - inject postMessage bridge failed: $e'); + } + } + PlatformWebViewControllerCreationParams _createPlatformParams() { if (WebViewPlatform.instance is WebKitWebViewPlatform) { return WebKitWebViewControllerCreationParams( @@ -110,27 +217,8 @@ class WebviewPageState extends State { return Scaffold( backgroundColor: Colors.transparent, extendBodyBehindAppBar: true, - appBar: AppBar( - backgroundColor: Colors.transparent, - elevation: 0, - title: Text( - widget.title ?? '', - style: const TextStyle(color: Colors.white), - ), - leading: IconButton( - icon: const Icon(Icons.arrow_back, color: Colors.white), - onPressed: () async { - final controller = _controller; - if (controller != null && await controller.canGoBack()) { - await controller.goBack(); - } else { - if (context.mounted) Navigator.of(context).maybePop(); - } - }, - ), - iconTheme: const IconThemeData(color: Colors.white), - ), + // appBar: myAppBar(context: context), body: _buildBody(), ); } @@ -154,11 +242,48 @@ class WebviewPageState extends State { return const Center(child: CircularProgressIndicator()); } - return Stack( - children: [ - Positioned.fill(child: WebViewWidget(controller: controller)), - if (_isLoading) const Center(child: CircularProgressIndicator()), - ], + return PopScope( + canPop: widget.canPop ?? true, + onPopInvokedWithResult: (didPop, result) async { + if (didPop) return; + + final ok = await showDialog( + context: context, + builder: (context) => AlertDialog( + title: const Text('提示'), + content: const Text('是否返回上一页?'), + actions: [ + TextButton( + onPressed: () => Navigator.of(context).pop(false), + child: const Text('取消'), + ), + TextButton( + onPressed: () => Navigator.of(context).pop(true), + child: const Text('确定'), + ), + ], + ), + ); + if (ok == true) { + AppNavigator.pop(); + } + }, + child: Scaffold( + body: Column( + children: [ + SizedBox(height: 48), + Expanded( + child: Stack( + children: [ + Positioned.fill(child: WebViewWidget(controller: controller)), + if (_isLoading) + const Center(child: CircularProgressIndicator()), + ], + ), + ), + ], + ), + ), ); } } diff --git a/lib/shared/widgets/widgets.dart b/lib/shared/widgets/widgets.dart index f457f49..c5baed8 100644 --- a/lib/shared/widgets/widgets.dart +++ b/lib/shared/widgets/widgets.dart @@ -11,6 +11,7 @@ export 'app_refresh_list.dart'; export 'app_search_bar.dart'; export 'app_status_view.dart'; export 'app_tag.dart'; +export 'app_text.dart'; export 'app_text_field.dart'; export 'app_toast.dart'; export 'safe_area_wrapper.dart'; diff --git a/plugins/apivideo_live_stream/.gitignore b/plugins/apivideo_live_stream/.gitignore new file mode 100644 index 0000000..be3943c --- /dev/null +++ b/plugins/apivideo_live_stream/.gitignore @@ -0,0 +1,14 @@ +gradle-wrapper.jar +/.gradle +/captures/ +/gradlew +/gradlew.bat +/local.properties +GeneratedPluginRegistrant.java +.cxx/ + +# Remember to never publicly share your keystore. +# See https://flutter.dev/to/reference-keystore +key.properties +**/*.keystore +**/*.jks diff --git a/plugins/apivideo_live_stream/CHANGELOG.md b/plugins/apivideo_live_stream/CHANGELOG.md new file mode 100644 index 0000000..7ca0c38 --- /dev/null +++ b/plugins/apivideo_live_stream/CHANGELOG.md @@ -0,0 +1,82 @@ +# Changelog + +All changes to this project will be documented in this file. + +## [1.2.0] - 2024-02-12 + +- Add a `fit` parameter to `ApiVideoCameraPreview` to control the fit of the preview inside its + parent widget +- Improve and fix few video resolution issues +- Android: The package automatically requests the camera and microphone permissions +- Android: upgrade gradle, kotlin, AGP and other dependencies +- iOS: add missing `getVideoSize` method +- iOS: send events from the main thread +- Example: lower default bitrate to run the example effortlessly +- Example: enable wake lock to keep the device awake during the live stream +- Example: put the application in the safe area + +## [1.1.3] - 2023-10-16 + +- Android: call `disconnect` event when `stopStream` is explicitly called +- Add api.video application icon for Android and iOS + +## [1.1.2] - 2023-08-16 + +- Android: fix the `videoSize` cast + +## [1.1.1] - 2023-01-23 + +- iOS: fix the orientation when device is turned + +## [1.1.0] - 2023-01-11 + +- Major refactor: + - use `initialize` instead of `create` and pass default parameters + to `ApiVideoLiveStreamController` constructor + - simplified usage of `CameraPreview` (and renamed to `ApiVideoCameraPreview`) +- Getter for properties such as `isMuted`, `cameraPosition`, ... ( + see [#13](https://github.com/apivideo/api.video-flutter-live-stream/issues/13)) +- Few fixes on Android and iOS + +## [1.0.7] - 2022-10-12 + +- Fix crash on `stopStreaming`. + See [#14](https://github.com/apivideo/api.video-flutter-live-stream/issues/14) + +## [1.0.6] - 2022-09-30 + +- Fix 1080p configuration. + See [#16](https://github.com/apivideo/api.video-flutter-live-stream/issues/16) +- Upgrade HaishinKit to 1.3.0. + See [#15](https://github.com/apivideo/api.video-flutter-live-stream/issues/15) +- Upgrade dependencies + +## [1.0.5] - 2022-08-03 + +- Few fixes on FLV/RTMP to increase compatibility +- iOS: fix landscape orientation. + See [#12](https://github.com/apivideo/api.video-flutter-live-stream/issues/12) + +## [1.0.4] - 2022-06-01 + +- iOS: Fix the random aspect ratio of the preview and random crashes. + See [#7](https://github.com/apivideo/api.video-flutter-live-stream/issues/7) + +## [1.0.3] - 2022-05-30 + +- Android: do not obfuscate rtmpdroid classes to + fix [#6](https://github.com/apivideo/api.video-flutter-live-stream/issues/6) + +## [1.0.2] - 2022-05-25 + +- iOS: implements `stopPreview` and `startPreview` to + fix [#4](https://github.com/apivideo/api.video-flutter-live-stream/issues/4) + +## [1.0.1] - 2022-04-13 + +- Fix audio and video configuration for iOS +- Fix setAudioConfig when preview is running for Android + +## [1.0.0] - 2022-04-08 + +- Initial release. diff --git a/plugins/apivideo_live_stream/CONTRIBUTING.md b/plugins/apivideo_live_stream/CONTRIBUTING.md new file mode 100644 index 0000000..754d17e --- /dev/null +++ b/plugins/apivideo_live_stream/CONTRIBUTING.md @@ -0,0 +1,228 @@ +# Contributing to api.video + +:movie_camera::+1::tada: Thank you for taking the time to contribute and participate in the implementation of a Video First World! :tada::+1::movie_camera: + +The following is a set of guidelines for contributing to api.video and its packages, which are hosted in the [api.video Organization](https://github.com/apivideo) on GitHub. + +#### Table of contents + +- [Contributing to api.video](#contributing-to-apivideo) + - [Table of contents](#table-of-contents) + - [Code of conduct](#code-of-conduct) + - [I just have a question!](#i-just-have-a-question) + - [How can I contribute?](#how-can-i-contribute) + - [Reporting bugs](#reporting-bugs) + - [Before submitting a bug report](#before-submitting-a-bug-report) + - [How do I submit a (good) bug report?](#how-do-i-submit-a-good-bug-report) + - [Suggesting enhancements](#suggesting-enhancements) + - [How do I submit a (good) enhancement suggestion?](#how-do-i-submit-a-good-enhancement-suggestion) + - [Pull requests](#pull-requests) + - [Style guides](#style-guides) + - [Git commit messages](#git-commit-messages) + - [Documentation style guide](#documentation-style-guide) + - [Additional notes](#additional-notes) + - [Issue and pull request labels](#issue-and-pull-request-labels) + - [Type of issue and issue state](#type-of-issue-and-issue-state) + - [Topic categories](#topic-categories) + - [Pull request labels](#pull-request-labels) + +## Code of conduct + +This project and everyone participating in it is governed by the [api.video Code of Conduct](https://github.com/apivideo/.github/blob/main/CODE_OF_CONDUCT.md). By participating, you are expected to uphold this code. Please report unacceptable behavior to [help@api.video](mailto:help@api.video). + +## I just have a question! + +> **Note:** [Please don't file an issue to ask a question.] You'll get faster results by using the resources below. + +We have an official message board with a detailed FAQ and where the community chimes in with helpful advice if you have questions. + +* [The official api.video's Community](https://community.api.video/) +* [api.video FAQ](https://community.api.video/c/faq/) + + +## How can I contribute? + +### Reporting bugs + +This section guides you through submitting a bug report for api.video. Following these guidelines helps maintainers and the community understand your report :pencil:, reproduce the behavior :computer:, and find related reports :mag_right:. + +Before creating bug reports, please check [this list](#before-submitting-a-bug-report) as you might find out that you don't need to create one. When you are creating a bug report, please [include as many details as possible](#how-do-i-submit-a-good-bug-report). Fill out [the required template](https://github.com/apivideo/.github/blob/main/.github/ISSUE_TEMPLATE/bug_report.yml), the information it asks for helps us resolve issues faster. + +> **Note:** If you find a **Closed** issue that seems like it is the same thing that you're experiencing, open a new issue and include a link to the original issue in the body of your new one. + +#### Before submitting a bug report + +* **Check the [The official api.video's Community](https://community.api.video/)** for a list of common questions and problems. +* **Determine which repository the problem should be reported in**. +* **Perform a [cursory search](https://github.com/search?q=is%3Aissue+user%3Aapivideo)** to see if the problem has already been reported. If it has **and the issue is still open**, add a comment to the existing issue instead of opening a new one. + +#### How do I submit a (good) bug report? + +Bugs are tracked as [GitHub issues](https://guides.github.com/features/issues/). After you've determined which repository your bug is related to, create an issue on that repository and provide the following information by filling in [the template](https://github.com/apivideo/.github/blob/main/.github/ISSUE_TEMPLATE/bug_report.yml). + +Explain the problem and include additional details to help maintainers reproduce the problem: + +* **Use a clear and descriptive title** for the issue to identify the problem. +* **Describe the exact steps which reproduce the problem** in as many details as possible. When listing steps, **don't just say what you did, but explain how you did it**. +* **Provide specific examples to demonstrate the steps**. Include links to files or GitHub projects, or copy/pasteable snippets, which you use in those examples. If you're providing snippets in the issue, use [Markdown code blocks](https://help.github.com/articles/markdown-basics/#multiple-lines). +* **Describe the behavior you observed after following the steps** and point out what exactly is the problem with that behavior. +* **Explain which behavior you expected to see instead and why.** +* **Include screenshots or videos** which show you following the described steps and clearly demonstrate the problem. +* **If the problem wasn't triggered by a specific action**, describe what you were doing before the problem happened and share more information using the guidelines below. + +Provide more context by answering these questions: + +* **Did the problem start happening recently** (e.g. after updating to a new version of api.video) or was this always a problem? +* If the problem started happening recently.** +* **Can you reliably reproduce the issue?** If not, provide details about how often the problem happens and under which conditions it normally happens. + +Include details about your configuration and environment: + +* **Which version of the api.video package are you using?** +* **What's the name and version of the OS you're using?** + +### Suggesting enhancements + +This section guides you through submitting an enhancement suggestion for api.video project, including completely new features and minor improvements to existing functionality. Following these guidelines helps maintainers and the community understand your suggestion :pencil: and find related suggestions :mag_right:. + +When you are creating an enhancement suggestion, please [include as many details as possible](#how-do-i-submit-a-good-enhancement-suggestion). Fill in [the template](https://github.com/apivideo/.github/blob/main/.github/ISSUE_TEMPLATE/feature_request.yml), including the steps that you imagine you would take if the feature you're requesting existed. + + +#### How do I submit a (good) enhancement suggestion? + +Enhancement suggestions are tracked as [GitHub issues](https://guides.github.com/features/issues/). After you've determined which repository your enhancement suggestion is related to, create an issue on that repository and provide the following information: + +* **Use a clear and descriptive title** for the issue to identify the suggestion. +* **Provide a step-by-step description of the suggested enhancement** in as many details as possible. +* **Provide specific examples to demonstrate the steps**. Include copy/pasteable snippets which you use in those examples, as [Markdown code blocks](https://help.github.com/articles/markdown-basics/#multiple-lines). +* **Describe the current behavior** and **explain which behavior you expected to see instead** and why. +* **Include screenshots** which help you demonstrate the steps or point out the part of api.video which the suggestion is related to. +* **Explain why this enhancement would be useful** to most api.video users and isn't something that can or should be implemented as a community package. +* **Specify which version of the api.video package you're using.** +* **Specify the name and version of the OS you're using.** + + +### Pull requests + +The process described here has several goals: + +- Maintain api.video's quality +- Fix problems that are important to users +- Engage the community in working toward the best possible api.video +- Enable a sustainable system for api.video's maintainers to review contributions + +Please follow these steps to have your contribution considered by the maintainers: + +1. Explain what, why and how you resolved the issue. If you have a related issue, please mention it. +2. Follow the [style guides](#style-guides) +3. After you submit your pull request, verify that all [status checks](https://help.github.com/articles/about-status-checks/) are passing
What if the status checks are failing?If a status check is failing, and you believe that the failure is unrelated to your change, please leave a comment on the pull request explaining why you believe the failure is unrelated. A maintainer will re-run the status check for you. If we conclude that the failure was a false positive, then we will open an issue to track that problem with our status check suite.
+ +While the prerequisites above must be satisfied prior to having your pull request reviewed, the reviewer(s) may ask you to complete additional design work, tests, or other changes before your pull request can be ultimately accepted. + +## Style guides + +### Git commit messages + +* Use the present tense ("Add feature" not "Added feature") +* Limit the first line to 72 characters or less +* Reference issues and pull requests after the first line +* Consider starting the commit message with an applicable emoji: + * :art: `:art:` when improving the format/structure of the code + * :racehorse: `:racehorse:` when improving performance + * :non-potable_water: `:non-potable_water:` when plugging memory leaks + * :memo: `:memo:` when writing docs + * :penguin: `:penguin:` when fixing something on Linux + * :apple: `:apple:` when fixing something on macOS + * :checkered_flag: `:checkered_flag:` when fixing something on Windows + * :bug: `:bug:` when fixing a bug + * :fire: `:fire:` when removing code or files + * :green_heart: `:green_heart:` when fixing the CI build + * :white_check_mark: `:white_check_mark:` when adding tests + * :lock: `:lock:` when dealing with security + * :arrow_up: `:arrow_up:` when upgrading dependencies + * :arrow_down: `:arrow_down:` when downgrading dependencies + * :shirt: `:shirt:` when removing linter warnings + +### Documentation style guide + +* Use [Markdown](https://daringfireball.net/projects/markdown). + + +## Additional notes + +### Issue and pull request labels + +This section lists the labels we use to help us track and manage issues and pull requests on all api.video repositories. + +[GitHub search](https://help.github.com/articles/searching-issues/) makes it easy to use labels for finding groups of issues or pull requests you're interested in. We encourage you to read about [other search filters](https://help.github.com/articles/searching-issues/) which will help you write more focused queries. + + +#### Type of issue and issue state + +| Label name | `apivideo` :mag_right: | Description | +| --- | --- | --- | +| `enhancement` | [search][search-apivideo-org-label-enhancement] | Feature requests. | +| `bug` | [search][search-apivideo-org-label-bug] | Confirmed bugs or reports that are very likely to be bugs. | +| `question` | [search][search-apivideo-org-label-question] | Questions more than bug reports or feature requests (e.g. how do I do X). | +| `feedback` | [search][search-apivideo-org-label-feedback] | General feedback more than bug reports or feature requests. | +| `help-wanted` | [search][search-apivideo-org-label-help-wanted] | The api.video team would appreciate help from the community in resolving these issues. | +| `more-information-needed` | [search][search-apivideo-org-label-more-information-needed] | More information needs to be collected about these problems or feature requests (e.g. steps to reproduce). | +| `needs-reproduction` | [search][search-apivideo-org-label-needs-reproduction] | Likely bugs, but haven't been reliably reproduced. | +| `blocked` | [search][search-apivideo-org-label-blocked] | Issues blocked on other issues. | +| `duplicate` | [search][search-apivideo-org-label-duplicate] | Issues which are duplicates of other issues, i.e. they have been reported before. | +| `wontfix` | [search][search-apivideo-org-label-wontfix] | The api.video team has decided not to fix these issues for now, either because they're working as intended or for some other reason. | +| `invalid` | [search][search-apivideo-org-label-invalid] | Issues which aren't valid (e.g. user errors). | +| `package-idea` | [search][search-apivideo-org-label-package-idea] | Feature request which might be good candidates for new packages, instead of extending api.video packages. | +| `wrong-repo` | [search][search-apivideo-org-label-wrong-repo] | Issues reported on the wrong repository. | + +#### Topic categories + +| Label name | `apivideo` :mag_right: | Description | +| --- | --- | --- | +| `windows` | [search][search-apivideo-org-label-windows] | Related to api.video running on Windows. | +| `linux` | [search][search-apivideo-org-label-linux] | Related to api.video running on Linux. | +| `mac` | [search][search-apivideo-org-label-mac] | Related to api.video running on macOS. | +| `documentation` | [search][search-apivideo-org-label-documentation] | Related to any type of documentation. | +| `performance` | [search][search-apivideo-org-label-performance] | Related to performance. | +| `security` | [search][search-apivideo-org-label-security] | Related to security. | +| `ui` | [search][search-apivideo-org-label-ui] | Related to visual design. | +| `api` | [search][search-apivideo-org-label-api] | Related to api.video's public APIs. | + +#### Pull request labels + +| Label name | `apivideo` :mag_right: | Description +| --- | --- | --- | +| `work-in-progress` | [search][search-apivideo-org-label-work-in-progress] | Pull requests which are still being worked on, more changes will follow. | +| `needs-review` | [search][search-apivideo-org-label-needs-review] | Pull requests which need code review, and approval from maintainers or api.video team. | +| `under-review` | [search][search-apivideo-org-label-under-review] | Pull requests being reviewed by maintainers or api.video team. | +| `requires-changes` | [search][search-apivideo-org-label-requires-changes] | Pull requests which need to be updated based on review comments and then reviewed again. | +| `needs-testing` | [search][search-apivideo-org-label-needs-testing] | Pull requests which need manual testing. | + +[search-apivideo-org-label-enhancement]: https://github.com/search?q=is%3Aopen+is%3Aissue+user%3Aapivideo+label%3Aenhancement +[search-apivideo-org-label-bug]: https://github.com/search?q=is%3Aopen+is%3Aissue+user%3Aapivideo+label%3Abug +[search-apivideo-org-label-question]: https://github.com/search?q=is%3Aopen+is%3Aissue+user%3Aapivideo+label%3Aquestion +[search-apivideo-org-label-feedback]: https://github.com/search?q=is%3Aopen+is%3Aissue+user%3Aapivideo+label%3Afeedback +[search-apivideo-org-label-help-wanted]: https://github.com/search?q=is%3Aopen+is%3Aissue+user%3Aapivideo+label%3Ahelp-wanted +[search-apivideo-org-label-more-information-needed]: https://github.com/search?q=is%3Aopen+is%3Aissue+user%3Aapivideo+label%3Amore-information-needed +[search-apivideo-org-label-needs-reproduction]: https://github.com/search?q=is%3Aopen+is%3Aissue+user%3Aapivideo+label%3Aneeds-reproduction +[search-apivideo-org-label-windows]: https://github.com/search?q=is%3Aopen+is%3Aissue+user%3Aapivideo+label%3Awindows +[search-apivideo-org-label-linux]: https://github.com/search?q=is%3Aopen+is%3Aissue+user%3Aapivideo+label%3Alinux +[search-apivideo-org-label-mac]: https://github.com/search?q=is%3Aopen+is%3Aissue+user%3Aapivideo+label%3Amac +[search-apivideo-org-label-documentation]: https://github.com/search?q=is%3Aopen+is%3Aissue+user%3Aapivideo+label%3Adocumentation +[search-apivideo-org-label-performance]: https://github.com/search?q=is%3Aopen+is%3Aissue+user%3Aapivideo+label%3Aperformance +[search-apivideo-org-label-security]: https://github.com/search?q=is%3Aopen+is%3Aissue+user%3Aapivideo+label%3Asecurity +[search-apivideo-org-label-ui]: https://github.com/search?q=is%3Aopen+is%3Aissue+user%3Aapivideo+label%3Aui +[search-apivideo-org-label-api]: https://github.com/search?q=is%3Aopen+is%3Aissue+user%3Aapivideo+label%3Aapi +[search-apivideo-org-label-blocked]: https://github.com/search?q=is%3Aopen+is%3Aissue+user%3Aapivideo+label%3Ablocked +[search-apivideo-org-label-duplicate]: https://github.com/search?q=is%3Aopen+is%3Aissue+user%3Aapivideo+label%3Aduplicate +[search-apivideo-org-label-wontfix]: https://github.com/search?q=is%3Aopen+is%3Aissue+user%3Aapivideo+label%3Awontfix +[search-apivideo-org-label-invalid]: https://github.com/search?q=is%3Aopen+is%3Aissue+user%3Aapivideo+label%3Ainvalid +[search-apivideo-org-label-package-idea]: https://github.com/search?q=is%3Aopen+is%3Aissue+user%3Aapivideo+label%3Apackage-idea +[search-apivideo-org-label-wrong-repo]: https://github.com/search?q=is%3Aopen+is%3Aissue+user%3Aapivideo+label%3Awrong-repo +[search-apivideo-org-label-work-in-progress]: https://github.com/search?q=is%3Aopen+is%3Apr+repo%3Aapivideo%2Fapivideo+label%3Awork-in-progress +[search-apivideo-org-label-needs-review]: https://github.com/search?q=is%3Aopen+is%3Apr+repo%3Aapivideo%2Fapivideo+label%3Aneeds-review +[search-apivideo-org-label-under-review]: https://github.com/search?q=is%3Aopen+is%3Apr+repo%3Aapivideo%2Fapivideo+label%3Aunder-review +[search-apivideo-org-label-requires-changes]: https://github.com/search?q=is%3Aopen+is%3Apr+repo%3Aapivideo%2Fapivideo+label%3Arequires-changes +[search-apivideo-org-label-needs-testing]: https://github.com/search?q=is%3Aopen+is%3Apr+repo%3Aapivideo%2Fapivideo+label%3Aneeds-testing + +[help-wanted]:https://github.com/search?q=is%3Aopen+is%3Aissue+label%3Ahelp-wanted+user%3Aapivideo+sort%3Acomments-desc diff --git a/plugins/apivideo_live_stream/LICENSE b/plugins/apivideo_live_stream/LICENSE new file mode 100644 index 0000000..c0eef12 --- /dev/null +++ b/plugins/apivideo_live_stream/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2022 api.video + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/plugins/apivideo_live_stream/README.md b/plugins/apivideo_live_stream/README.md new file mode 100644 index 0000000..5560aff --- /dev/null +++ b/plugins/apivideo_live_stream/README.md @@ -0,0 +1,214 @@ + +[![badge](https://img.shields.io/twitter/follow/api_video?style=social)](https://twitter.com/intent/follow?screen_name=api_video) +  [![badge](https://img.shields.io/github/stars/apivideo/api.video-flutter-live-stream?style=social)](https://github.com/apivideo/api.video-flutter-live-stream) +  [![badge](https://img.shields.io/discourse/topics?server=https%3A%2F%2Fcommunity.api.video)](https://community.api.video) +![](https://github.com/apivideo/.github/blob/main/assets/apivideo_banner.png) + +

Flutter RTMP live stream client

+ +[api.video](https://api.video) is the video infrastructure for product builders. Lightning fast +video APIs for integrating, scaling, and managing on-demand & low latency live streaming features in +your app. + +## Table of contents + +- [Table of contents](#table-of-contents) +- [Project description](#project-description) +- [Getting started](#getting-started) + - [Installation](#installation) + - [Permissions](#permissions) + - [Code sample](#code-sample) + - [Manage application lifecycle](#manage-application-lifecycle) +- [Example App](#example-app) + - [Setup](#setup) + - [Android](#android) + - [iOS](#ios) +- [Plugins](#plugins) +- [FAQ](#faq) + + + + +## Project description + +This module is made for broadcasting RTMP live stream from smartphone camera. + +## Getting started + +### Installation + +Run the following command at the root of your project: + +```shell +flutter pub add apivideo_live_stream +``` + +In your dart file, import the package: + +```dart +import 'package:apivideo_live_stream/apivideo_live_stream.dart'; +``` + +### Permissions + +To be able to broadcast, you must: + +1. On Android: ask for internet, camera and microphone permissions: + +```xml + + + + + + +``` + +The library will require android.permission.CAMERA and android.permission.RECORD_AUDIO at runtime. +You don't need to request them. + +2. On iOS: update the Info.plist with a usage description for camera and microphone + +```xml + +NSCameraUsageDescription +Your own description of the purpose +NSMicrophoneUsageDescription +Your own description of the purpose +``` + +### Code sample + +1. Creates a live stream controller + +```dart + +final ApiVideoLiveStreamController _controller = ApiVideoLiveStreamController( + initialAudioConfig: AudioConfig(), initialVideoConfig: VideoConfig.withDefaultBitrate()); +``` + +2. Initializes the live stream controller + +```dart +await _controller.initialize(); +``` + +3. Adds a CameraPreview widget as a child of your view + +```dart +@override +Widget build(BuildContext context) { + return SizedBox( + width: 300.0, + height: 300.0, + child: ApiVideoCameraPreview(controller: _controller)); +} +``` + +`ApiVideoCameraPreview` parameters: + +- `controller`: the live stream controller +- `fit`: the fit of the preview (default is BoxFit.contain, + see [BoxFit](https://api.flutter.dev/flutter/painting/BoxFit.html) for more information) +- `child`: a child widget to overlay on top of the preview (optional) + +4. Starts a live stream + +```dart +_controller.startStreaming("YOUR_STREAM_KEY"); +``` + +5. Stops streaming and preview + +```dart +_controller.stop(); +``` + +#### Manage application lifecycle + +On the application side, you must manage application lifecycle: + +```dart +@override +void didChangeAppLifecycleState(AppLifecycleState state) { + if (state == AppLifecycleState.inactive) { + _controller.stop(); + } else if (state == AppLifecycleState.resumed) { + _controller.startPreview(); + } +} +``` + +## Example App + +You can try +our [example app](https://github.com/apivideo/api.video-flutter-live-stream/tree/master/example), +feel free to test it. + +### Setup + +Be sure to follow the [Flutter installation steps](https://docs.flutter.dev/get-started/) before +anything. + +1) Open Android Studio +2) File > New > Project from Version Control + +In URL field, type: + +```shell +git@github.com:apivideo/api.video-flutter-live-stream.git +``` + +Wait for the indexation to finish. + +#### Android + +Connect an Android device to your computer and click on the `Run main.dart` button. + +#### iOS + +1) Connect an iOS device to your computer and click on the `Run main.dart` button. + +2) The build will fail because you haven't set your development profile, sign your application: + +Open Xcode, click on "Open a project or file" and open +the `YOUR_PROJECT_NAME/example/ios/Runner.xcworkspace` file. +
Click on Example, go in `Signin & Capabilities` tab, add your team and create a unique bundle +identifier. + +## Plugins + +api.video Flutter live stream library is using external native libraries: + +| Plugin | README | +|------------|--------------| +| StreamPack | [StreamPack] | +| HaishinKit | [HaishinKit] | + +## FAQ + +If you have any questions, ask us in the [community](https://community.api.video) or +use [issues](https://github.com/apivideo/api.video-flutter-live-stream/issues). + +[//]: # (These are reference links used in the body of this note and get stripped out when the markdown processor does its job. There is no need to format nicely because it shouldn't be seen. Thanks SO - http://stackoverflow.com/questions/4823468/store-comments-in-markdown-syntax) + +[StreamPack]: + +[HaishinKit]: + diff --git a/plugins/apivideo_live_stream/analysis_options.yaml b/plugins/apivideo_live_stream/analysis_options.yaml new file mode 100644 index 0000000..477a6db --- /dev/null +++ b/plugins/apivideo_live_stream/analysis_options.yaml @@ -0,0 +1,7 @@ +include: package:flutter_lints/flutter.yaml + +linter: + rules: + constant_identifier_names: false + prefer_final_fields: false + prefer_single_quotes: false diff --git a/plugins/apivideo_live_stream/android/.gradle/8.2/checksums/checksums.lock b/plugins/apivideo_live_stream/android/.gradle/8.2/checksums/checksums.lock new file mode 100644 index 0000000..f9cc278 Binary files /dev/null and b/plugins/apivideo_live_stream/android/.gradle/8.2/checksums/checksums.lock differ diff --git a/plugins/apivideo_live_stream/android/.gradle/8.2/dependencies-accessors/dependencies-accessors.lock b/plugins/apivideo_live_stream/android/.gradle/8.2/dependencies-accessors/dependencies-accessors.lock new file mode 100644 index 0000000..8eabff0 Binary files /dev/null and b/plugins/apivideo_live_stream/android/.gradle/8.2/dependencies-accessors/dependencies-accessors.lock differ diff --git a/plugins/apivideo_live_stream/android/.gradle/8.2/dependencies-accessors/gc.properties b/plugins/apivideo_live_stream/android/.gradle/8.2/dependencies-accessors/gc.properties new file mode 100644 index 0000000..e69de29 diff --git a/plugins/apivideo_live_stream/android/.gradle/8.2/executionHistory/executionHistory.lock b/plugins/apivideo_live_stream/android/.gradle/8.2/executionHistory/executionHistory.lock new file mode 100644 index 0000000..64f1468 Binary files /dev/null and b/plugins/apivideo_live_stream/android/.gradle/8.2/executionHistory/executionHistory.lock differ diff --git a/plugins/apivideo_live_stream/android/.gradle/8.2/fileChanges/last-build.bin b/plugins/apivideo_live_stream/android/.gradle/8.2/fileChanges/last-build.bin new file mode 100644 index 0000000..f76dd23 Binary files /dev/null and b/plugins/apivideo_live_stream/android/.gradle/8.2/fileChanges/last-build.bin differ diff --git a/plugins/apivideo_live_stream/android/.gradle/8.2/fileHashes/fileHashes.lock b/plugins/apivideo_live_stream/android/.gradle/8.2/fileHashes/fileHashes.lock new file mode 100644 index 0000000..04ae26e Binary files /dev/null and b/plugins/apivideo_live_stream/android/.gradle/8.2/fileHashes/fileHashes.lock differ diff --git a/plugins/apivideo_live_stream/android/.gradle/8.2/gc.properties b/plugins/apivideo_live_stream/android/.gradle/8.2/gc.properties new file mode 100644 index 0000000..e69de29 diff --git a/plugins/apivideo_live_stream/android/.gradle/buildOutputCleanup/buildOutputCleanup.lock b/plugins/apivideo_live_stream/android/.gradle/buildOutputCleanup/buildOutputCleanup.lock new file mode 100644 index 0000000..1c5cf3e Binary files /dev/null and b/plugins/apivideo_live_stream/android/.gradle/buildOutputCleanup/buildOutputCleanup.lock differ diff --git a/plugins/apivideo_live_stream/android/.gradle/buildOutputCleanup/cache.properties b/plugins/apivideo_live_stream/android/.gradle/buildOutputCleanup/cache.properties new file mode 100644 index 0000000..7a41652 --- /dev/null +++ b/plugins/apivideo_live_stream/android/.gradle/buildOutputCleanup/cache.properties @@ -0,0 +1,2 @@ +#Mon Jul 13 17:53:35 CST 2026 +gradle.version=8.2 diff --git a/plugins/apivideo_live_stream/android/.gradle/vcs-1/gc.properties b/plugins/apivideo_live_stream/android/.gradle/vcs-1/gc.properties new file mode 100644 index 0000000..e69de29 diff --git a/plugins/apivideo_live_stream/android/build.gradle b/plugins/apivideo_live_stream/android/build.gradle new file mode 100644 index 0000000..8c1a2b4 --- /dev/null +++ b/plugins/apivideo_live_stream/android/build.gradle @@ -0,0 +1,62 @@ +group 'video.api.flutter.livestream' +version '1.0-SNAPSHOT' + +buildscript { + ext { + kotlin_version = '1.9.22' + streamPackVersion = '2.6.0' + } + repositories { + google() + mavenCentral() + } + + dependencies { + classpath 'com.android.tools.build:gradle:8.2.2' + classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" + } +} + +rootProject.allprojects { + repositories { + google() + mavenCentral() + } +} + +apply plugin: 'com.android.library' +apply plugin: 'kotlin-android' + +android { + compileSdk 34 + + sourceSets { + main.java.srcDirs += 'src/main/kotlin' + } + + defaultConfig { + minSdkVersion 21 + } + + compileOptions { + sourceCompatibility JavaVersion.VERSION_1_8 + targetCompatibility JavaVersion.VERSION_1_8 + } + + kotlinOptions { + jvmTarget = '1.8' + } + + namespace "video.api.flutter.livestream" +} + +dependencies { + implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version" + implementation 'androidx.constraintlayout:constraintlayout:2.1.4' + + implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.7.3' + implementation 'androidx.appcompat:appcompat:1.6.1' + + implementation "io.github.thibaultbee:streampack:$streamPackVersion" + implementation "io.github.thibaultbee:streampack-extension-rtmp:$streamPackVersion" +} diff --git a/plugins/apivideo_live_stream/android/gradle.properties b/plugins/apivideo_live_stream/android/gradle.properties new file mode 100644 index 0000000..94adc3a --- /dev/null +++ b/plugins/apivideo_live_stream/android/gradle.properties @@ -0,0 +1,3 @@ +org.gradle.jvmargs=-Xmx1536M +android.useAndroidX=true +android.enableJetifier=true diff --git a/plugins/apivideo_live_stream/android/gradle/wrapper/gradle-wrapper.properties b/plugins/apivideo_live_stream/android/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..b5fc5a7 --- /dev/null +++ b/plugins/apivideo_live_stream/android/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,5 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.2-all.zip diff --git a/plugins/apivideo_live_stream/android/settings.gradle b/plugins/apivideo_live_stream/android/settings.gradle new file mode 100644 index 0000000..b71fcb1 --- /dev/null +++ b/plugins/apivideo_live_stream/android/settings.gradle @@ -0,0 +1 @@ +rootProject.name = 'apivideo_live_stream' diff --git a/plugins/apivideo_live_stream/android/src/main/AndroidManifest.xml b/plugins/apivideo_live_stream/android/src/main/AndroidManifest.xml new file mode 100644 index 0000000..0c6fcc9 --- /dev/null +++ b/plugins/apivideo_live_stream/android/src/main/AndroidManifest.xml @@ -0,0 +1,9 @@ + + + + + + + diff --git a/plugins/apivideo_live_stream/android/src/main/kotlin/video/api/flutter/livestream/ApiVideoLiveStreamPlugin.kt b/plugins/apivideo_live_stream/android/src/main/kotlin/video/api/flutter/livestream/ApiVideoLiveStreamPlugin.kt new file mode 100644 index 0000000..df17449 --- /dev/null +++ b/plugins/apivideo_live_stream/android/src/main/kotlin/video/api/flutter/livestream/ApiVideoLiveStreamPlugin.kt @@ -0,0 +1,54 @@ +package video.api.flutter.livestream + +import io.flutter.embedding.engine.plugins.FlutterPlugin +import io.flutter.embedding.engine.plugins.FlutterPlugin.FlutterPluginBinding +import io.flutter.embedding.engine.plugins.activity.ActivityAware +import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding + +/** ApiVideoLiveStreamPlugin */ +class ApiVideoLiveStreamPlugin : FlutterPlugin, ActivityAware { + private var permissionsManager: PermissionsManager? = null + private var methodCallHandlerImpl: MethodCallHandlerImpl? = null + + override fun onAttachedToEngine(binding: FlutterPluginBinding) { + permissionsManager = PermissionsManager(binding.applicationContext).apply { + methodCallHandlerImpl = MethodCallHandlerImpl( + binding.applicationContext, + binding.binaryMessenger, + this, + binding.textureRegistry + ).apply { + startListening() + } + } + } + + override fun onDetachedFromEngine(binding: FlutterPluginBinding) { + methodCallHandlerImpl?.stopListening() + methodCallHandlerImpl = null + permissionsManager = null + } + + override fun onAttachedToActivity(binding: ActivityPluginBinding) { + val activity = binding.activity + permissionsManager?.let { + it.activity = activity + binding.addRequestPermissionsResultListener(it) + } + } + + override fun onDetachedFromActivityForConfigChanges() { + permissionsManager?.activity = null + } + + override fun onReattachedToActivityForConfigChanges(binding: ActivityPluginBinding) { + permissionsManager?.let { + it.activity = null + binding.addRequestPermissionsResultListener(it) + } + } + + override fun onDetachedFromActivity() { + permissionsManager?.activity = null + } +} diff --git a/plugins/apivideo_live_stream/android/src/main/kotlin/video/api/flutter/livestream/FlutterLiveStreamView.kt b/plugins/apivideo_live_stream/android/src/main/kotlin/video/api/flutter/livestream/FlutterLiveStreamView.kt new file mode 100644 index 0000000..e93407c --- /dev/null +++ b/plugins/apivideo_live_stream/android/src/main/kotlin/video/api/flutter/livestream/FlutterLiveStreamView.kt @@ -0,0 +1,274 @@ +package video.api.flutter.livestream + +import android.Manifest +import android.content.Context +import android.util.Size +import android.view.Surface +import io.flutter.view.TextureRegistry +import io.github.thibaultbee.streampack.data.AudioConfig +import io.github.thibaultbee.streampack.data.VideoConfig +import io.github.thibaultbee.streampack.error.StreamPackError +import io.github.thibaultbee.streampack.ext.rtmp.streamers.CameraRtmpLiveStreamer +import io.github.thibaultbee.streampack.listeners.OnConnectionListener +import io.github.thibaultbee.streampack.listeners.OnErrorListener +import io.github.thibaultbee.streampack.utils.backCameraList +import io.github.thibaultbee.streampack.utils.externalCameraList +import io.github.thibaultbee.streampack.utils.frontCameraList +import io.github.thibaultbee.streampack.utils.isBackCamera +import io.github.thibaultbee.streampack.utils.isExternalCamera +import io.github.thibaultbee.streampack.utils.isFrontCamera +import kotlinx.coroutines.runBlocking + +class FlutterLiveStreamView( + private val context: Context, + textureRegistry: TextureRegistry, + private val permissionsManager: PermissionsManager, + private val onConnectionSucceeded: () -> Unit, + private val onDisconnected: () -> Unit, + private val onConnectionFailed: (String) -> Unit, + private val onGenericError: (Exception) -> Unit, + private val onVideoSizeChanged: (Size) -> Unit, +) : + OnConnectionListener, OnErrorListener { + private val flutterTexture = textureRegistry.createSurfaceTexture() + val textureId: Long + get() = flutterTexture.id() + + private val streamer = CameraRtmpLiveStreamer( + context = context, + initialOnConnectionListener = this, + initialOnErrorListener = this + ) + + private var _isPreviewing = false + private var _isStreaming = false + val isStreaming: Boolean + get() = _isStreaming + + + private var _videoConfig: VideoConfig? = null + val videoConfig: VideoConfig + get() = _videoConfig!! + + fun setVideoConfig( + videoConfig: VideoConfig, + onSuccess: () -> Unit, + onError: (Exception) -> Unit + ) { + if (isStreaming) { + throw UnsupportedOperationException("You have to stop streaming first") + } + + onVideoSizeChanged(videoConfig.resolution) + + val wasPreviewing = _isPreviewing + if (wasPreviewing) { + stopPreview() + } + streamer.configure(videoConfig) + _videoConfig = videoConfig + if (wasPreviewing) { + startPreview(onSuccess, onError) + } else { + onSuccess() + } + } + + private var _audioConfig: AudioConfig? = null + val audioConfig: AudioConfig + get() = _audioConfig!! + + fun setAudioConfig( + audioConfig: AudioConfig, + onSuccess: () -> Unit, + onError: (Exception) -> Unit + ) { + if (isStreaming) { + throw UnsupportedOperationException("You have to stop streaming first") + } + + permissionsManager.requestPermission( + Manifest.permission.RECORD_AUDIO, + onGranted = { + try { + streamer.configure(audioConfig) + _audioConfig = audioConfig + onSuccess() + } catch (e: Exception) { + onError(e) + } + }, + onShowPermissionRationale = { _ -> + /** + * Require an AppCompat theme to use MaterialAlertDialogBuilder + * + context.showDialog( + R.string.permission_required, + R.string.record_audio_permission_required_message, + android.R.string.ok, + onPositiveButtonClick = { onRequiredPermissionLastTime() } + ) */ + onError(SecurityException("Missing permission Manifest.permission.RECORD_AUDIO")) + }, + onDenied = { + onError(SecurityException("Missing permission Manifest.permission.RECORD_AUDIO")) + }) + } + + var isMuted: Boolean + get() = streamer.settings.audio.isMuted + set(value) { + streamer.settings.audio.isMuted = value + } + + val camera: String + get() = streamer.camera + + fun setCamera(camera: String, onSuccess: () -> Unit, onError: (Exception) -> Unit) { + permissionsManager.requestPermission( + Manifest.permission.CAMERA, + onGranted = { + try { + streamer.camera = camera + onSuccess() + } catch (e: Exception) { + onError(e) + } + }, + onShowPermissionRationale = { _ -> + /** + * Require an AppCompat theme to use MaterialAlertDialogBuilder + * + * context.showDialog( + R.string.permission_required, + R.string.camera_permission_required_message, + android.R.string.ok, + onPositiveButtonClick = { onRequiredPermissionLastTime() } + )*/ + onError(SecurityException("Missing permission Manifest.permission.CAMERA")) + }, + onDenied = { + onError(SecurityException("Missing permission Manifest.permission.CAMERA")) + }) + } + + fun setCameraId(cameraId: String, onSuccess: () -> Unit, onError: (Exception) -> Unit) { + setCamera(cameraId, onSuccess, onError) + } + + val cameraPosition: String + get() = when { + context.isFrontCamera(streamer.camera) -> "front" + context.isBackCamera(streamer.camera) -> "back" + context.isExternalCamera(streamer.camera) -> "other" + else -> throw IllegalArgumentException("Invalid camera position for camera ${streamer.camera}") + } + + fun setCameraPosition(position: String, onSuccess: () -> Unit, onError: (Exception) -> Unit) { + val cameraList = when (position) { + "front" -> context.frontCameraList + "back" -> context.backCameraList + "other" -> context.externalCameraList + else -> throw IllegalArgumentException("Invalid camera position: $position") + } + setCamera(cameraList.first(), onSuccess, onError) + } + + fun dispose() { + stopStream() + streamer.stopPreview() + flutterTexture.release() + } + + fun startStream(url: String) { + runBlocking { + streamer.connect(url) + try { + streamer.startStream() + _isStreaming = true + } catch (e: Exception) { + streamer.disconnect() + onLost("Failed to start stream: ${e.message}") + throw e + } + } + } + + fun stopStream() { + val isConnected = streamer.isConnected + runBlocking { + streamer.stopStream() + streamer.disconnect() + if (isConnected) { + onDisconnected() + } + _isStreaming = false + } + } + + fun startPreview(onSuccess: () -> Unit, onError: (Exception) -> Unit) { + permissionsManager.requestPermission( + Manifest.permission.CAMERA, + onGranted = { + if (_videoConfig == null) { + onError(IllegalStateException("Video has not been configured!")) + } else { + try { + streamer.startPreview(getSurface(videoConfig.resolution)) + _isPreviewing = true + onSuccess() + } catch (e: Exception) { + onError(e) + } + } + }, + onShowPermissionRationale = { _ -> + /** + * Require an AppCompat theme to use MaterialAlertDialogBuilder + * + * context.showDialog( + R.string.permission_required, + R.string.camera_permission_required_message, + android.R.string.ok, + onPositiveButtonClick = { onRequiredPermissionLastTime() } + )*/ + onError(SecurityException("Missing permission Manifest.permission.CAMERA")) + }, + onDenied = { + onError(SecurityException("Missing permission Manifest.permission.CAMERA")) + }) + } + + fun stopPreview() { + streamer.stopPreview() + _isPreviewing = false + } + + private fun getSurface(resolution: Size): Surface { + val surfaceTexture = flutterTexture.surfaceTexture().apply { + setDefaultBufferSize( + resolution.width, + resolution.height + ) + } + return Surface(surfaceTexture) + } + + + override fun onSuccess() { + onConnectionSucceeded() + } + + override fun onLost(message: String) { + onDisconnected() + } + + override fun onFailed(message: String) { + onConnectionFailed(message) + } + + override fun onError(error: StreamPackError) { + _isStreaming = false + onGenericError(error) + } +} diff --git a/plugins/apivideo_live_stream/android/src/main/kotlin/video/api/flutter/livestream/MethodCallHandlerImpl.kt b/plugins/apivideo_live_stream/android/src/main/kotlin/video/api/flutter/livestream/MethodCallHandlerImpl.kt new file mode 100644 index 0000000..39d96f8 --- /dev/null +++ b/plugins/apivideo_live_stream/android/src/main/kotlin/video/api/flutter/livestream/MethodCallHandlerImpl.kt @@ -0,0 +1,341 @@ +package video.api.flutter.livestream + +import android.content.Context +import android.hardware.camera2.CameraCharacteristics +import android.hardware.camera2.CameraManager +import android.os.Handler +import android.os.Looper +import android.util.Size +import io.flutter.plugin.common.BinaryMessenger +import io.flutter.plugin.common.EventChannel +import io.flutter.plugin.common.MethodCall +import io.flutter.plugin.common.MethodChannel +import io.flutter.view.TextureRegistry +import video.api.flutter.livestream.utils.addTrailingSlashIfNeeded +import video.api.flutter.livestream.utils.toAudioConfig +import video.api.flutter.livestream.utils.toVideoConfig +import kotlin.math.atan + +class MethodCallHandlerImpl( + private val context: Context, + messenger: BinaryMessenger, + private val permissionsManager: PermissionsManager, + private val textureRegistry: TextureRegistry +) : MethodChannel.MethodCallHandler { + private val methodChannel = MethodChannel(messenger, METHOD_CHANNEL_NAME) + private val eventChannel = EventChannel(messenger, EVENT_CHANNEL_NAME) + private var eventSink: EventChannel.EventSink? = null + + private var flutterView: FlutterLiveStreamView? = null + + fun startListening() { + methodChannel.setMethodCallHandler(this) + eventChannel.setStreamHandler(object : EventChannel.StreamHandler { + override fun onListen(arguments: Any?, events: EventChannel.EventSink?) { + eventSink = events + } + + override fun onCancel(arguments: Any?) { + eventSink?.endOfStream() + eventSink = null + } + }) + } + + fun stopListening() { + methodChannel.setMethodCallHandler(null) + eventChannel.setStreamHandler(null) + } + + override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) { + when (call.method) { + "create" -> { + try { + flutterView?.dispose() + flutterView = FlutterLiveStreamView( + context, + textureRegistry, + permissionsManager, + { sendConnected() }, + { sendDisconnected() }, + { sendConnectionFailed(it) }, + { sendError(it) }, + { sendVideoSizeChanged(it) } + ) + result.success(mapOf("textureId" to flutterView!!.textureId)) + } catch (e: Exception) { + result.error("failed_to_create_live_stream", e.message, null) + } + } + + "dispose" -> { + flutterView?.dispose() + flutterView = null + } + + "setVideoConfig" -> { + try { + @Suppress("UNCHECKED_CAST") + val videoConfig = (call.arguments as Map).toVideoConfig() + flutterView!!.setVideoConfig( + videoConfig, + { result.success(null) }, + { + result.error( + "failed_to_set_video_config", + it.message, + null + ) + }) + } catch (e: Exception) { + result.error("failed_to_set_video_config", e.message, null) + } + } + + "setAudioConfig" -> { + try { + @Suppress("UNCHECKED_CAST") + val audioConfig = (call.arguments as Map).toAudioConfig() + flutterView!!.setAudioConfig( + audioConfig, + { result.success(null) }, + { + result.error( + "failed_to_set_audio_config", + it.message, + null + ) + }) + } catch (e: Exception) { + result.error("failed_to_set_audio_config", e.message, null) + } + } + + "startPreview" -> { + try { + flutterView!!.startPreview( + { result.success(null) }, + { + result.error( + "failed_to_start_preview", + it.message, + null + ) + }) + } catch (e: Exception) { + result.error("failed_to_start_preview", e.message, null) + } + } + + "stopPreview" -> { + flutterView?.stopPreview() + result.success(null) + } + + "startStreaming" -> { + val streamKey = call.argument("streamKey") + val url = call.argument("url") + when { + streamKey == null -> result.error( + "missing_stream_key", "Stream key is missing", null + ) + + streamKey.isEmpty() -> result.error( + "empty_stream_key", "Stream key is empty", null + ) + + url == null -> result.error( + "missing_rtmp_url", + "RTMP URL is missing", + null + ) + + url.isEmpty() -> result.error("empty_rtmp_url", "RTMP URL is empty", null) + + else -> + try { + flutterView!!.startStream(url.addTrailingSlashIfNeeded() + streamKey) + result.success(null) + } catch (e: Exception) { + result.error("failed_to_start_stream", e.message, null) + } + } + } + + "stopStreaming" -> { + flutterView?.stopStream() + result.success(null) + } + + "getIsStreaming" -> result.success(mapOf("isStreaming" to flutterView!!.isStreaming)) + "getCameraPosition" -> { + try { + result.success(mapOf("position" to flutterView!!.cameraPosition)) + } catch (e: Exception) { + result.error("failed_to_get_camera_position", e.message, null) + } + } + + "setCameraPosition" -> { + val cameraPosition = try { + ((call.arguments as Map<*, *>)["position"] as String) + } catch (e: Exception) { + result.error("invalid_parameter", "Invalid camera position", e) + return + } + try { + flutterView!!.setCameraPosition(cameraPosition, + { result.success(null) }, + { + result.error( + "failed_to_set_camera_position", + it.message, + null + ) + }) + } catch (e: Exception) { + result.error("failed_to_set_camera_position", e.message, null) + } + } + + "getBackCameras" -> { + try { + result.success(getBackCameras()) + } catch (e: Exception) { + result.error("failed_to_get_back_cameras", e.message, null) + } + } + + "setCameraId" -> { + val cameraId = try { + ((call.arguments as Map<*, *>)["cameraId"] as String) + } catch (e: Exception) { + result.error("invalid_parameter", "Invalid cameraId", e) + return + } + try { + flutterView!!.setCameraId(cameraId, + { result.success(null) }, + { + result.error( + "failed_to_set_camera_id", + it.message, + null + ) + }) + } catch (e: Exception) { + result.error("failed_to_set_camera_id", e.message, null) + } + } + + "getIsMuted" -> { + try { + result.success(mapOf("isMuted" to flutterView!!.isMuted)) + } catch (e: Exception) { + result.error("failed_to_get_is_muted", e.message, null) + } + } + + "setIsMuted" -> { + val isMuted = try { + ((call.arguments as Map<*, *>)["isMuted"] as Boolean) + } catch (e: Exception) { + result.error("invalid_parameter", "Invalid isMuted", e) + return + } + try { + flutterView!!.isMuted = isMuted + result.success(null) + } catch (e: Exception) { + result.error("failed_to_set_is_muted", e.message, null) + } + } + + "getVideoSize" -> { + try { + val videoSize = flutterView!!.videoConfig.resolution + result.success( + mapOf( + "width" to videoSize.width.toDouble(), + "height" to videoSize.height.toDouble() + ) + ) + } catch (e: Exception) { + result.error("failed_to_get_video_size", e.message, null) + } + } + + else -> result.notImplemented() + } + } + + private fun sendEvent(type: String) { + Handler(Looper.getMainLooper()).post { + eventSink?.success(mapOf("type" to type)) + } + } + + private fun sendConnected() { + sendEvent("connected") + } + + private fun sendDisconnected() { + sendEvent("disconnected") + } + + private fun sendConnectionFailed(message: String) { + Handler(Looper.getMainLooper()).post { + eventSink?.success(mapOf("type" to "connectionFailed", "message" to message)) + } + } + + private fun sendError(error: Exception) { + Handler(Looper.getMainLooper()).post { + eventSink?.error(error::class.java.name, error.message, error) + } + } + + private fun sendVideoSizeChanged(resolution: Size) { + Handler(Looper.getMainLooper()).post { + eventSink?.success( + mapOf( + "type" to "videoSizeChanged", + "width" to resolution.width.toDouble(), + "height" to resolution.height.toDouble() // Dart size fields are in double + ) + ) + } + } + + private fun getBackCameras(): List> { + val manager = context.getSystemService(Context.CAMERA_SERVICE) as CameraManager + return manager.cameraIdList.mapNotNull { cameraId -> + val characteristics = manager.getCameraCharacteristics(cameraId) + val facing = characteristics.get(CameraCharacteristics.LENS_FACING) + if (facing != CameraCharacteristics.LENS_FACING_BACK) { + return@mapNotNull null + } + val focalLengths = + characteristics.get(CameraCharacteristics.LENS_INFO_AVAILABLE_FOCAL_LENGTHS) + ?: return@mapNotNull null + val sensorSize = + characteristics.get(CameraCharacteristics.SENSOR_INFO_PHYSICAL_SIZE) + ?: return@mapNotNull null + val minFocalLength = focalLengths.minOrNull() ?: return@mapNotNull null + val horizontalFov = + 2.0 * atan((sensorSize.width / (2.0f * minFocalLength)).toDouble()) + mapOf( + "cameraId" to cameraId, + "minFocalLength" to minFocalLength.toDouble(), + "sensorWidth" to sensorSize.width.toDouble(), + "sensorHeight" to sensorSize.height.toDouble(), + "horizontalFov" to horizontalFov, + ) + } + } + + companion object { + private const val METHOD_CHANNEL_NAME = "video.api.livestream/controller" + private const val EVENT_CHANNEL_NAME = "video.api.livestream/events" + } +} diff --git a/plugins/apivideo_live_stream/android/src/main/kotlin/video/api/flutter/livestream/PermissionsManager.kt b/plugins/apivideo_live_stream/android/src/main/kotlin/video/api/flutter/livestream/PermissionsManager.kt new file mode 100644 index 0000000..ba61123 --- /dev/null +++ b/plugins/apivideo_live_stream/android/src/main/kotlin/video/api/flutter/livestream/PermissionsManager.kt @@ -0,0 +1,164 @@ +package video.api.flutter.livestream + +import android.app.Activity +import android.content.Context +import android.content.pm.PackageManager +import androidx.core.app.ActivityCompat +import androidx.core.content.ContextCompat +import io.flutter.plugin.common.PluginRegistry + +/** + * Check if the app has the given permissions. + * For a single permission or multiple permissions. + */ +class PermissionsManager( + private val context: Context, +) : PluginRegistry.RequestPermissionsResultListener { + private var uniqueRequestCode = 1 + + // To request permission, we need the activity + var activity: Activity? = null + + private val listeners = mutableMapOf() + private fun hasPermission(permission: String) = + ContextCompat.checkSelfPermission(context, permission) == PackageManager.PERMISSION_GRANTED + + private fun hasAllPermissions(permissions: List) = permissions.all { permission -> + ContextCompat.checkSelfPermission( + context, + permission + ) == PackageManager.PERMISSION_GRANTED + } + + private fun shouldShowRequestPermissionRationale( + activity: Activity, + permissions: List + ) = + permissions.filter { permission -> + ActivityCompat.shouldShowRequestPermissionRationale(activity, permission) + } + + fun requestPermissions( + permissions: List, + onAllGranted: () -> Unit, + onShowPermissionRationale: (List, () -> Unit) -> Unit, + onAtLeastOnePermissionDenied: () -> Unit + ) { + activity?.let { + requestPermissions(it, permissions, object : IListener { + override fun onAllGranted() { + onAllGranted() + } + + override fun onShowPermissionRationale( + permissions: List, + onRequiredPermissionLastTime: () -> Unit + ) { + onShowPermissionRationale(permissions, onRequiredPermissionLastTime) + } + + override fun onAtLeastOnePermissionDenied() { + onAtLeastOnePermissionDenied() + } + }) + } ?: throw IllegalStateException("Missing Activity") + } + + private fun requestPermissions( + activity: Activity, + permissions: List, + listener: IListener + ) { + val currentRequestCode = synchronized(this) { + uniqueRequestCode++ + } + listeners[currentRequestCode] = listener + when { + hasAllPermissions(permissions) -> listener.onAllGranted() + shouldShowRequestPermissionRationale(activity, permissions).isNotEmpty() -> { + val missingPermissions = shouldShowRequestPermissionRationale(activity, permissions) + listener.onShowPermissionRationale(missingPermissions) { + ActivityCompat.requestPermissions( + activity, + missingPermissions.toTypedArray(), + currentRequestCode + ) + } + } + + else -> ActivityCompat.requestPermissions( + activity, + permissions.toTypedArray(), + currentRequestCode + ) + } + } + + fun requestPermission( + permission: String, + onGranted: () -> Unit, + onShowPermissionRationale: (() -> Unit) -> Unit, + onDenied: () -> Unit + ) { + activity?.let { + requestPermissions(it, listOf(permission), object : IListener { + override fun onAllGranted() { + onGranted() + } + + override fun onShowPermissionRationale( + permissions: List, + onRequiredPermissionLastTime: () -> Unit + ) { + onShowPermissionRationale(onRequiredPermissionLastTime) + } + + override fun onAtLeastOnePermissionDenied() { + onDenied() + } + }) + } ?: throw IllegalStateException("Missing Activity") + } + + override fun onRequestPermissionsResult( + requestCode: Int, + permissions: Array, + grantResults: IntArray + ): Boolean { + val listener = listeners[requestCode] ?: return false + listeners.remove(requestCode) + + if (grantResults.isEmpty()) { + return false + } + + grantResults.forEach { + if (it == PackageManager.PERMISSION_GRANTED) { + listener.onGranted(permissions[grantResults.indexOf(it)]) + } else { + listener.onDenied(permissions[grantResults.indexOf(it)]) + } + } + + if (grantResults.all { it == PackageManager.PERMISSION_GRANTED }) { + listener.onAllGranted() + } else { + listener.onAtLeastOnePermissionDenied() + } + + return listeners.isEmpty() + } + + interface IListener { + fun onAllGranted() {} + fun onGranted(permission: String) {} + fun onShowPermissionRationale( + permissions: List, + onRequiredPermissionLastTime: () -> Unit + ) { + } + + fun onDenied(permission: String) {} + fun onAtLeastOnePermissionDenied() {} + } +} diff --git a/plugins/apivideo_live_stream/android/src/main/kotlin/video/api/flutter/livestream/utils/ContextExtensions.kt b/plugins/apivideo_live_stream/android/src/main/kotlin/video/api/flutter/livestream/utils/ContextExtensions.kt new file mode 100644 index 0000000..98d7e06 --- /dev/null +++ b/plugins/apivideo_live_stream/android/src/main/kotlin/video/api/flutter/livestream/utils/ContextExtensions.kt @@ -0,0 +1,41 @@ +package video.api.flutter.livestream.utils + +import android.content.Context +import android.content.DialogInterface +import androidx.annotation.StringRes +import androidx.appcompat.app.AlertDialog + + +/** + * Show a dialog with the given title and message. + */ +fun Context.showDialog( + @StringRes title: Int, + @StringRes message: Int = 0, + @StringRes + positiveButtonText: Int = android.R.string.ok, + @StringRes + negativeButtonText: Int = 0, + onPositiveButtonClick: () -> Unit = {}, + onNegativeButtonClick: () -> Unit = {} +) { + AlertDialog.Builder(this) + .setTitle(title) + .setMessage(message) + .apply { + if (positiveButtonText != 0) { + setPositiveButton(positiveButtonText) { dialogInterface: DialogInterface, _: Int -> + dialogInterface.dismiss() + onPositiveButtonClick() + } + } + if (negativeButtonText != 0) { + setNegativeButton(negativeButtonText) { dialogInterface: DialogInterface, _: Int -> + dialogInterface.dismiss() + onNegativeButtonClick() + } + } + } + .show() +} + diff --git a/plugins/apivideo_live_stream/android/src/main/kotlin/video/api/flutter/livestream/utils/Extensions.kt b/plugins/apivideo_live_stream/android/src/main/kotlin/video/api/flutter/livestream/utils/Extensions.kt new file mode 100644 index 0000000..b386bd7 --- /dev/null +++ b/plugins/apivideo_live_stream/android/src/main/kotlin/video/api/flutter/livestream/utils/Extensions.kt @@ -0,0 +1,52 @@ +package video.api.flutter.livestream.utils + +import android.util.Size +import io.github.thibaultbee.streampack.data.AudioConfig +import io.github.thibaultbee.streampack.data.VideoConfig + + +fun Map.toVideoConfig(): VideoConfig { + return VideoConfig( + startBitrate = this["bitrate"] as Int, + resolution = (this["resolution"] as String).toResolution(), + fps = this["fps"] as Int + ) +} + +fun Map.toAudioConfig(): AudioConfig { + return AudioConfig( + startBitrate = this["bitrate"] as Int, + sampleRate = this["sampleRate"] as Int, + channelConfig = AudioConfig.getChannelConfig( + if (this["channel"] == "stereo") { + 2 + } else { + 1 + } + ), + enableNoiseSuppressor = this["enableNoiseSuppressor"] as Boolean, + enableEchoCanceler = this["enableEchoCanceler"] as Boolean + ) +} + +fun String.toResolution(): Size { + return when (this) { + "240p" -> Size(426, 240) + "360p" -> Size(640, 360) + "480p" -> Size(854, 480) + "720p" -> Size(1280, 720) + "1080p" -> Size(1920, 1080) + else -> throw IllegalArgumentException("Unknown resolution: $this") + } +} + +/** + * Add a slash at the end of a [String] only if it is missing. + * + * @return the given string with a trailing slash. + */ +fun String.addTrailingSlashIfNeeded(): String { + return if (this.endsWith("/")) this else "$this/" +} + + diff --git a/plugins/apivideo_live_stream/android/src/main/res/values/strings.xml b/plugins/apivideo_live_stream/android/src/main/res/values/strings.xml new file mode 100644 index 0000000..7e26a09 --- /dev/null +++ b/plugins/apivideo_live_stream/android/src/main/res/values/strings.xml @@ -0,0 +1,6 @@ + + + Permission required + You have to grant the record audio permission to stream. + You have to grant the camera permission to stream. + diff --git a/plugins/apivideo_live_stream/ios/Classes/ApiVideoLiveStreamPlugin.h b/plugins/apivideo_live_stream/ios/Classes/ApiVideoLiveStreamPlugin.h new file mode 100644 index 0000000..3051cde --- /dev/null +++ b/plugins/apivideo_live_stream/ios/Classes/ApiVideoLiveStreamPlugin.h @@ -0,0 +1,4 @@ +#import + +@interface ApiVideoLiveStreamPlugin : NSObject +@end diff --git a/plugins/apivideo_live_stream/ios/Classes/ApiVideoLiveStreamPlugin.m b/plugins/apivideo_live_stream/ios/Classes/ApiVideoLiveStreamPlugin.m new file mode 100644 index 0000000..c0b0b9c --- /dev/null +++ b/plugins/apivideo_live_stream/ios/Classes/ApiVideoLiveStreamPlugin.m @@ -0,0 +1,15 @@ +#import "ApiVideoLiveStreamPlugin.h" +#if __has_include() +#import +#else +// Support project import fallback if the generated compatibility header +// is not copied when this plugin is created as a library. +// https://forums.swift.org/t/swift-static-libraries-dont-copy-generated-objective-c-header/19816 +#import "apivideo_live_stream-Swift.h" +#endif + +@implementation ApiVideoLiveStreamPlugin ++ (void)registerWithRegistrar:(NSObject*)registrar { + [SwiftApiVideoLiveStreamPlugin registerWithRegistrar:registrar]; +} +@end diff --git a/plugins/apivideo_live_stream/ios/Classes/FlutterLiveStreamView.swift b/plugins/apivideo_live_stream/ios/Classes/FlutterLiveStreamView.swift new file mode 100644 index 0000000..5471ad1 --- /dev/null +++ b/plugins/apivideo_live_stream/ios/Classes/FlutterLiveStreamView.swift @@ -0,0 +1,148 @@ +import ApiVideoLiveStream +import AVFoundation +import Foundation + +class FlutterLiveStreamView: NSObject { + private let previewTexture: PreviewTexture + private let liveStream: ApiVideoLiveStream + + private let eventChannel: FlutterEventChannel + private var eventSink: FlutterEventSink? + + init(binaryMessenger: FlutterBinaryMessenger, textureRegistry: FlutterTextureRegistry) throws { + previewTexture = PreviewTexture(registry: textureRegistry) + liveStream = try ApiVideoLiveStream(preview: previewTexture, initialAudioConfig: nil, initialVideoConfig: nil, initialCamera: nil) + eventChannel = FlutterEventChannel(name: "video.api.livestream/events", binaryMessenger: binaryMessenger) + + super.init() + + liveStream.delegate = self + eventChannel.setStreamHandler(self) + } + + var textureId: Int64 { + previewTexture.textureId + } + + private(set) var isStreaming = false + + var videoConfig: VideoConfig { + get { + liveStream.videoConfig + } + set { + sendEvent(["type": "videoSizeChanged", "width": Double(newValue.resolution.width), "height": Double(newValue.resolution.height)]) + + liveStream.videoConfig = newValue + } + } + + var audioConfig: AudioConfig { + get { + liveStream.audioConfig + } + set { + liveStream.audioConfig = newValue + } + } + + var isMuted: Bool { + get { + liveStream.isMuted + } + set { + liveStream.isMuted = newValue + } + } + + var cameraPosition: String { + get { + if liveStream.cameraPosition == AVCaptureDevice.Position.back { + return "back" + } else if liveStream.cameraPosition == AVCaptureDevice.Position.front { + return "front" + } else { + return "other" + } + } + set { + if newValue == "back" { + liveStream.cameraPosition = AVCaptureDevice.Position.back + } else if newValue == "front" { + liveStream.cameraPosition = AVCaptureDevice.Position.front + } + } + } + + func dispose() { + liveStream.stopStreaming() + liveStream.stopPreview() + + previewTexture.dispose() + } + + func startPreview() { + liveStream.startPreview() + } + + func stopPreview() { + liveStream.stopPreview() + } + + func startStreaming(streamKey: String, url: String) throws { + try liveStream.startStreaming(streamKey: streamKey, url: url) + isStreaming = true + } + + func stopStreaming() { + liveStream.stopStreaming() + isStreaming = false + } +} + +extension FlutterLiveStreamView: FlutterStreamHandler { + func onListen(withArguments _: Any?, eventSink events: @escaping FlutterEventSink) -> FlutterError? { + eventSink = events + return nil + } + + func onCancel(withArguments _: Any?) -> FlutterError? { + eventSink = nil + return nil + } + + private func sendEvent(_ event: [String: Any]) { + DispatchQueue.main.async { + self.eventSink?(event) + } + } +} + +extension FlutterLiveStreamView: ApiVideoLiveStreamDelegate { + /// Called when the connection to the rtmp server is successful + func connectionSuccess() { + sendEvent(["type": "connected"]) + } + + /// Called when the connection to the rtmp server failed + func connectionFailed(_: String) { + isStreaming = false + sendEvent(["type": "connectionFailed", "message": "Failed to connect"]) + } + + /// Called when the connection to the rtmp server is closed + func disconnection() { + isStreaming = false + sendEvent(["type": "disconnected"]) + } + + /// Called if an error happened during the audio configuration + func audioError(_ error: Error) { + print("audio error: \(error)") + } + + /// Called if an error happened during the video configuration + func videoError(_ error: Error) { + print("video error: \(error)") + } +} diff --git a/plugins/apivideo_live_stream/ios/Classes/FlutterTexture.swift b/plugins/apivideo_live_stream/ios/Classes/FlutterTexture.swift new file mode 100644 index 0000000..12f9f23 --- /dev/null +++ b/plugins/apivideo_live_stream/ios/Classes/FlutterTexture.swift @@ -0,0 +1,56 @@ +import AVFoundation +import Foundation +import HaishinKit + +class PreviewTexture: NSObject, FlutterTexture { + var videoOrientation: AVCaptureVideoOrientation = .portrait + var isCaptureVideoPreviewEnabled: Bool = false + + private weak var currentStream: IOStream? { + didSet { + currentStream?.drawable = self + } + } + + private var currentSampleBuffer: CMSampleBuffer? + private let registry: FlutterTextureRegistry + private(set) var textureId: Int64 = 0 + + public init(registry: FlutterTextureRegistry) { + self.registry = registry + super.init() + textureId = self.registry.register(self) + } + + func copyPixelBuffer() -> Unmanaged? { + guard let currentSampleBuffer = currentSampleBuffer, + let imageBuffer = CMSampleBufferGetImageBuffer(currentSampleBuffer) + else { + return nil + } + + return Unmanaged.passRetained(imageBuffer) + } + + func dispose() { + registry.unregisterTexture(textureId) + } +} + +extension PreviewTexture: IOStreamDrawable { + // MARK: - IOStreamDrawable + func attachStream(_ stream: IOStream?) { + if Thread.isMainThread { + currentStream = stream + } else { + DispatchQueue.main.async { + self.currentStream = stream + } + } + } + + func enqueue(_ sampleBuffer: CMSampleBuffer?) { + currentSampleBuffer = sampleBuffer + registry.textureFrameAvailable(textureId) + } +} diff --git a/plugins/apivideo_live_stream/ios/Classes/SwiftApiVideoLiveStreamPlugin.swift b/plugins/apivideo_live_stream/ios/Classes/SwiftApiVideoLiveStreamPlugin.swift new file mode 100644 index 0000000..37a9464 --- /dev/null +++ b/plugins/apivideo_live_stream/ios/Classes/SwiftApiVideoLiveStreamPlugin.swift @@ -0,0 +1,205 @@ +import ApiVideoLiveStream +import AVFoundation +import Flutter +import HaishinKit +import Network +import UIKit + +enum ApiVideoLiveStreamError: Error { + case invalidAVSession +} + +public class SwiftApiVideoLiveStreamPlugin: NSObject, FlutterPlugin { + private let binaryMessenger: FlutterBinaryMessenger + private let channel: FlutterMethodChannel + private let registry: FlutterTextureRegistry + private var flutterView: FlutterLiveStreamView? + + public static func register(with registrar: FlutterPluginRegistrar) { + let instance = SwiftApiVideoLiveStreamPlugin(registrar: registrar) + registrar.publish(instance) + } + + public init(registrar: FlutterPluginRegistrar) { + binaryMessenger = registrar.messenger() + channel = FlutterMethodChannel(name: "video.api.livestream/controller", binaryMessenger: binaryMessenger) + registry = registrar.textures() + super.init() + + registrar.addMethodCallDelegate(self, channel: channel) + } + + public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) { + switch call.method { + case "create": + flutterView?.dispose() + do { + flutterView = try FlutterLiveStreamView(binaryMessenger: binaryMessenger, textureRegistry: registry) + if let previewTexture = flutterView?.textureId { + result(["textureId": previewTexture]) + } else { + result(FlutterError(code: "failed_to_create_live_stream", message: "Failed to create camera preview surface", details: nil)) + } + } catch { + result(FlutterError(code: "failed_to_create_live_stream", message: error.localizedDescription, details: nil)) + } + case "dispose": + flutterView?.dispose() + case "setVideoConfig": + guard let flutterView = flutterView else { + result(FlutterError(code: "missing_live_stream", message: "Live stream must exist at this point", details: nil)) + return + } + guard let videoParameters = call.arguments as? [String: Any] else { + result(FlutterError(code: "invalid_parameter", message: "Invalid video config", details: nil)) + return + } + applyVideoConfig(config: videoParameters, flutterView: flutterView, result: result) + case "setAudioConfig": + guard let flutterView = flutterView else { + result(FlutterError(code: "missing_live_stream", message: "Live stream must exist at this point", details: nil)) + return + } + guard let audioParameters = call.arguments as? [String: Any] else { + result(FlutterError(code: "invalid_parameter", message: "Invalid audio config", details: nil)) + return + } + applyAudioConfig(config: audioParameters, flutterView: flutterView, result: result) + case "startPreview": + guard let flutterView = flutterView else { + result(FlutterError(code: "missing_live_stream", message: "Live stream must exist at this point", details: nil)) + return + } + flutterView.startPreview() + result(nil) + case "stopPreview": + guard let flutterView = flutterView else { + result(FlutterError(code: "missing_live_stream", message: "Live stream must exist at this point", details: nil)) + return + } + flutterView.stopPreview() + result(nil) + case "startStreaming": + if let args = call.arguments as? [String: Any] { + let streamKey = args["streamKey"] as? String + let url = args["url"] as? String + if streamKey == nil { + result(FlutterError(code: "missing_stream_key", message: "Stream key is missing", details: nil)) + } else if url == nil { + result(FlutterError(code: "missing_rtmp_url", message: "RTMP URL is missing", details: nil)) + } else { + guard let flutterView = flutterView else { + result(FlutterError(code: "missing_live_stream", message: "Live stream must exist at this point", details: nil)) + return + } + do { + try flutterView.startStreaming(streamKey: streamKey!, url: url!) + result(nil) + } catch { + result(FlutterError(code: "missing_live_stream", message: error.localizedDescription, details: nil)) + } + } + } + case "stopStreaming": + guard let flutterView = flutterView else { + result(FlutterError(code: "missing_live_stream", message: "Live stream must exist at this point", details: nil)) + return + } + flutterView.stopStreaming() + result(nil) + case "getIsStreaming": + guard let flutterView = flutterView else { + result(FlutterError(code: "missing_live_stream", message: "Live stream must exist at this point", details: nil)) + return + } + result(["isStreaming": flutterView.isStreaming]) + case "getCameraPosition": + guard let flutterView = flutterView else { + result(FlutterError(code: "missing_live_stream", message: "Live stream must exist at this point", details: nil)) + return + } + result(["position": flutterView.cameraPosition]) + case "setCameraPosition": + guard let flutterView = flutterView else { + result(FlutterError(code: "missing_live_stream", message: "Live stream must exist at this point", details: nil)) + return + } + guard let args = call.arguments as? [String: Any], + let cameraPosition = args["position"] as? String + else { + result(FlutterError(code: "invalid_parameter", message: "Invalid camera position", details: nil)) + return + } + flutterView.cameraPosition = cameraPosition + result(nil) + case "getIsMuted": + guard let flutterView = flutterView else { + result(FlutterError(code: "missing_live_stream", message: "Live stream must exist at this point", details: nil)) + return + } + result(["isMuted": flutterView.isMuted]) + case "setIsMuted": + guard let flutterView = flutterView else { + result(FlutterError(code: "missing_live_stream", message: "Live stream must exist at this point", details: nil)) + return + } + guard let args = call.arguments as? [String: Any], + let isMuted = args["isMuted"] as? Bool + else { + result(FlutterError(code: "invalid_parameter", message: "Invalid isMuted", details: nil)) + return + } + flutterView.isMuted = isMuted + result(nil) + case "getVideoSize": + guard let flutterView = flutterView else { + result(FlutterError(code: "missing_live_stream", message: "Live stream must exist at this point", details: nil)) + return + } + result(["width": flutterView.videoConfig.resolution.width, "height": flutterView.videoConfig.resolution.height]) + default: + result(FlutterMethodNotImplemented) + } + } + + private func applyVideoConfig(config: Dictionary, flutterView: FlutterLiveStreamView, result: @escaping FlutterResult) { + let resolutionString = config["resolution"] as! String? + guard let resolutionString else { + result(FlutterError(code: "missing_parameter", message: "Resolution is missing", details: nil)) + return + } + let resolution = resolutionString.toResolution() + guard let resolution else { + result(FlutterError(code: "invalid_parameter", message: "Invalid resolution \(resolutionString)", details: nil)) + return + } + flutterView.videoConfig = VideoConfig(bitrate: config["bitrate"] as! Int, + resolution: resolution.rawValue, + fps: config["fps"] as! Float64) + result(nil) + } + + private func applyAudioConfig(config: Dictionary, flutterView: FlutterLiveStreamView, result: @escaping FlutterResult) { + flutterView.audioConfig = AudioConfig(bitrate: config["bitrate"] as! Int) + result(nil) + } +} + +extension String { + func toResolution() -> Resolution? { + switch self { + case "240p": + return Resolution.RESOLUTION_16_9_240P + case "360p": + return Resolution.RESOLUTION_16_9_360P + case "480p": + return Resolution.RESOLUTION_16_9_480P + case "720p": + return Resolution.RESOLUTION_16_9_720P + case "1080p": + return Resolution.RESOLUTION_16_9_1080P + default: + return nil + } + } +} diff --git a/plugins/apivideo_live_stream/ios/apivideo_live_stream.podspec b/plugins/apivideo_live_stream/ios/apivideo_live_stream.podspec new file mode 100644 index 0000000..a83fe7f --- /dev/null +++ b/plugins/apivideo_live_stream/ios/apivideo_live_stream.podspec @@ -0,0 +1,24 @@ +# +# To learn more about a Podspec see http://guides.cocoapods.org/syntax/podspec.html. +# Run `pod lib lint apivideo_live_stream.podspec` to validate before publishing. +# +Pod::Spec.new do |s| + s.name = 'apivideo_live_stream' + s.version = '0.0.1' + s.summary = 'A new flutter plugin project.' + s.description = <<-DESC +A new flutter plugin project. + DESC + s.homepage = 'http://example.com' + s.license = { :file => '../LICENSE' } + s.author = { 'Your Company' => 'email@example.com' } + s.source = { :path => '.' } + s.source_files = 'Classes/**/*' + s.dependency 'Flutter' + s.dependency 'ApiVideoLiveStream', "1.4.1" + s.platform = :ios, '12.0' + + # Flutter.framework does not contain a i386 slice. + s.pod_target_xcconfig = { 'DEFINES_MODULE' => 'YES', 'EXCLUDED_ARCHS[sdk=iphonesimulator*]' => 'i386' } + s.swift_version = '5.0' +end diff --git a/plugins/apivideo_live_stream/lib/apivideo_live_stream.dart b/plugins/apivideo_live_stream/lib/apivideo_live_stream.dart new file mode 100644 index 0000000..c98a4b7 --- /dev/null +++ b/plugins/apivideo_live_stream/lib/apivideo_live_stream.dart @@ -0,0 +1,4 @@ +export 'src/apivideo_camera_preview.dart'; +export 'src/apivideo_live_stream_controller.dart'; +export 'src/apivideo_live_stream_mobile_platform.dart'; +export 'src/types.dart'; diff --git a/plugins/apivideo_live_stream/lib/src/apivideo_camera_preview.dart b/plugins/apivideo_live_stream/lib/src/apivideo_camera_preview.dart new file mode 100644 index 0000000..75e802b --- /dev/null +++ b/plugins/apivideo_live_stream/lib/src/apivideo_camera_preview.dart @@ -0,0 +1,183 @@ +import 'package:flutter/foundation.dart'; +import 'package:flutter/widgets.dart'; +import 'package:native_device_orientation/native_device_orientation.dart'; + +import 'apivideo_live_stream_controller.dart'; + +/// Widget that displays the camera preview of [controller]. +/// +class ApiVideoCameraPreview extends StatefulWidget { + /// Creates a new [ApiVideoCameraPreview] instance for [controller] and a [child] overlay. + const ApiVideoCameraPreview( + {super.key, + required this.controller, + this.fit = BoxFit.contain, + this.child}); + + /// The controller for the camera to display the preview for. + final ApiVideoLiveStreamController controller; + + /// The [BoxFit] for the video. The [child] is scale to the preview box. + final BoxFit fit; + + /// A widget to overlay on top of the camera preview. It is scaled to the camera preview [FittedBox]. + final Widget? child; + + @override + State createState() => _ApiVideoCameraPreviewState(); +} + +class _ApiVideoCameraPreviewState extends State { + _ApiVideoCameraPreviewState() { + _widgetListener = ApiVideoLiveStreamWidgetListener(onTextureReady: () { + final int newTextureId = widget.controller.textureId; + if (newTextureId != _textureId) { + setState(() { + _textureId = newTextureId; + }); + } + }); + + _eventsListener = + ApiVideoLiveStreamEventsListener(onVideoSizeChanged: (size) { + _updateAspectRatio(size); + }); + } + + late ApiVideoLiveStreamWidgetListener _widgetListener; + late ApiVideoLiveStreamEventsListener _eventsListener; + late int _textureId; + + double _aspectRatio = 1.77; + Size _size = const Size(1280, 720); + + @override + void initState() { + super.initState(); + _textureId = widget.controller.textureId; + widget.controller.addWidgetListener(_widgetListener); + widget.controller.addEventsListener(_eventsListener); + if (widget.controller.isInitialized) { + widget.controller.videoSize.then((size) { + if (size != null) { + _updateAspectRatio(size); + } + }); + } + } + + @override + void dispose() { + widget.controller.stopPreview(); + widget.controller.removeWidgetListener(_widgetListener); + widget.controller.removeEventsListener(_eventsListener); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + return _textureId == ApiVideoLiveStreamController.kUninitializedTextureId + ? Container() + : _buildPreview(context); + } + + Widget _buildPreview(BuildContext context) { + return NativeDeviceOrientationReader(builder: (context) { + final orientation = NativeDeviceOrientationReader.orientation(context); + return LayoutBuilder( + builder: (BuildContext context, BoxConstraints constraints) { + return Stack(alignment: Alignment.center, children: [ + _buildFittedPreview(constraints, orientation), + _buildFittedOverlay(constraints, orientation) + ]); + }); + }); + } + + Widget _buildFittedPreview( + BoxConstraints constraints, NativeDeviceOrientation orientation) { + final orientedSize = _size.orientate(orientation); + // See https://github.com/flutter/flutter/issues/17287 + return SizedBox( + width: constraints.maxWidth, + height: constraints.maxHeight, + child: FittedBox( + fit: widget.fit, + clipBehavior: Clip.hardEdge, + child: Center( + child: SizedBox( + width: orientedSize.width, + height: orientedSize.height, + child: _wrapInRotatedBox( + orientation: orientation, + child: widget.controller.buildPreview()))))); + } + + Widget _buildFittedOverlay( + BoxConstraints constraints, NativeDeviceOrientation orientation) { + final orientedSize = _size.orientate(orientation); + final fittedSize = + applyBoxFit(widget.fit, orientedSize, constraints.biggest); + return SizedBox( + width: fittedSize.destination.width, + height: fittedSize.destination.height, + child: widget.child ?? Container()); + } + + Widget _wrapInRotatedBox( + {required NativeDeviceOrientation orientation, required Widget child}) { + if (defaultTargetPlatform != TargetPlatform.android) { + return child; + } + + return RotatedBox( + quarterTurns: orientation.getQuarterTurns(), + child: child, + ); + } + + void _updateAspectRatio(Size newSize) async { + final double newAspectRatio = newSize.aspectRatio; + if ((newAspectRatio != _aspectRatio) || (newSize != _size)) { + if (mounted) { + setState(() { + _size = newSize; + _aspectRatio = newAspectRatio; + }); + } + } + } +} + +extension OrientationHelper on NativeDeviceOrientation { + /// Returns true if the orientation is portrait. + bool isLandscape() { + return [ + NativeDeviceOrientation.landscapeLeft, + NativeDeviceOrientation.landscapeRight + ].contains(this); + } + + /// Returns the number of clockwise quarter turns the orientation is rotated + int getQuarterTurns() { + Map turns = { + NativeDeviceOrientation.unknown: 0, + NativeDeviceOrientation.portraitUp: 0, + NativeDeviceOrientation.landscapeRight: 1, + NativeDeviceOrientation.portraitDown: 2, + NativeDeviceOrientation.landscapeLeft: 3, + }; + return turns[this]!; + } +} + +extension OrientedSize on Size { + /// Returns the size with width and height swapped if [orientation] is portrait. + Size orientate(NativeDeviceOrientation orientation) { + if (orientation.isLandscape()) { + return Size(width, height); + } else { + return Size(height, width); + } + } +} diff --git a/plugins/apivideo_live_stream/lib/src/apivideo_live_stream_controller.dart b/plugins/apivideo_live_stream/lib/src/apivideo_live_stream_controller.dart new file mode 100644 index 0000000..578a861 --- /dev/null +++ b/plugins/apivideo_live_stream/lib/src/apivideo_live_stream_controller.dart @@ -0,0 +1,335 @@ +import 'dart:async'; + +import 'package:apivideo_live_stream/apivideo_live_stream.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:meta/meta.dart'; + +import 'apivideo_live_stream_platform_interface.dart'; +import 'types.dart'; + +ApiVideoLiveStreamPlatform get _platform { + return ApiVideoLiveStreamPlatform.instance; +} + +/// Controller of the live streaming +class ApiVideoLiveStreamController { + final VideoConfig _initialVideoConfig; + final AudioConfig _initialAudioConfig; + final CameraPosition _initialCameraPosition; + + static const int kUninitializedTextureId = -1; + int _textureId = kUninitializedTextureId; + + /// This is just exposed for testing. Do not use it. + @internal + int get textureId => _textureId; + + bool _isInitialized = false; + + /// Gets the current state of the video player. + bool get isInitialized => _isInitialized; + + /// Events + StreamSubscription? _eventSubscription; + List _eventsListeners = []; + List _widgetListeners = []; + + /// Creates a new [ApiVideoLiveStreamController] instance. + ApiVideoLiveStreamController( + {required AudioConfig initialAudioConfig, + required VideoConfig initialVideoConfig, + CameraPosition initialCameraPosition = CameraPosition.back, + VoidCallback? onConnectionSuccess, + Function(String)? onConnectionFailed, + VoidCallback? onDisconnection, + Function(Exception)? onError}) + : _initialVideoConfig = initialVideoConfig, + _initialAudioConfig = initialAudioConfig, + _initialCameraPosition = initialCameraPosition { + _eventsListeners.add(ApiVideoLiveStreamEventsListener( + onConnectionSuccess: onConnectionSuccess, + onConnectionFailed: onConnectionFailed, + onDisconnection: onDisconnection, + onError: onError)); + } + + ApiVideoLiveStreamController.fromListener( + {required AudioConfig initialAudioConfig, + required VideoConfig initialVideoConfig, + CameraPosition initialCameraPosition = CameraPosition.back, + ApiVideoLiveStreamEventsListener? listener}) + : _initialVideoConfig = initialVideoConfig, + _initialAudioConfig = initialAudioConfig, + _initialCameraPosition = initialCameraPosition { + if (listener != null) { + _eventsListeners.add(listener); + } + } + + /// Creates a new live stream instance with initial audio and video configurations. + Future initialize() async { + _textureId = await _platform.initialize() ?? kUninitializedTextureId; + + _eventSubscription = _platform + .liveStreamingEventsFor(_textureId) + .listen(_eventListener, onError: _errorListener); + + for (var listener in [..._widgetListeners]) { + if (listener.onTextureReady != null) { + listener.onTextureReady!(); + } + } + + await setCameraPosition(_initialCameraPosition); + await setVideoConfig(_initialVideoConfig); + await setAudioConfig(_initialAudioConfig); + + await startPreview(); + _isInitialized = true; + return; + } + + /// Disposes the live stream instance. + Future dispose() async { + await _eventSubscription?.cancel(); + _eventsListeners.clear(); + _widgetListeners.clear(); + await _platform.dispose(); + return; + } + + /// Sets new video parameters. + /// + /// Do not call when in live or when preview is running. + Future setVideoConfig(VideoConfig videoConfig) { + return _platform.setVideoConfig(videoConfig); + } + + /// Sets new audio parameters. + /// + /// Do not call when in live or when preview is running. + Future setAudioConfig(AudioConfig audioConfig) { + return _platform.setAudioConfig(audioConfig); + } + + /// Starts the live stream to the specified "[url]/[streamKey]". + Future startStreaming( + {required String streamKey, + String url = "rtmp://broadcast.api.video/s/"}) async { + return _platform.startStreaming(streamKey: streamKey, url: url); + } + + /// Stops the live stream. + Future stopStreaming() { + return _platform.stopStreaming(); + } + + /// Starts the camera preview. + /// + /// The purpose of this method is to be called when application is sent + /// to foreground. + Future startPreview() { + return _platform.startPreview(); + } + + /// Stops the camera preview. + /// + /// The purpose of this method is to be called when application is sent + /// to background. + Future stopPreview() { + return _platform.stopPreview(); + } + + /// Same as [stopStreaming] and [stopPreview] + Future stop() async { + await stopStreaming(); + await stopPreview(); + } + + /// Gets if live stream is streaming or not. + Future get isStreaming { + return _platform.getIsStreaming(); + } + + /// Changes current back/front camera to front/back camera + Future switchCamera() async { + final cameraPosition = await this.cameraPosition; + if (cameraPosition == CameraPosition.back) { + return setCameraPosition(CameraPosition.front); + } else { + return setCameraPosition(CameraPosition.back); + } + } + + /// Gets the current camera position + Future get cameraPosition { + return _platform.getCameraPosition(); + } + + /// Sets the current camera position + Future setCameraPosition(CameraPosition position) { + return _platform.setCameraPosition(position); + } + + /// Lists back cameras exposed by Android CameraManager. + Future> getBackCameras() async { + final cameras = await _platform.getBackCameras(); + return cameras + .map(ApiVideoBackCamera.fromJson) + .where((camera) => camera.cameraId.isNotEmpty) + .toList(growable: false); + } + + /// Selects a concrete camera id. Android-only extension. + Future setCameraId(String cameraId) { + return _platform.setCameraId(cameraId); + } + + /// Toggle mutes/unmutes from the microphone. See [isMuted] and [setIsMuted]. + Future toggleMute() async { + final isMuted = await this.isMuted; + await setIsMuted(!isMuted); + } + + /// Gets if live stream is muted or not. + Future get isMuted { + return _platform.getIsMuted(); + } + + /// Mutes/unmutes the microphone. + Future setIsMuted(bool isMuted) { + return _platform.setIsMuted(isMuted); + } + + Future get videoSize { + return _platform.getVideoSize(); + } + + /// Builds the preview widget. + @internal + Widget buildPreview() { + return Texture(textureId: textureId); + } + + void addEventsListener(ApiVideoLiveStreamEventsListener listener) { + _eventsListeners.add(listener); + } + + void removeEventsListener(ApiVideoLiveStreamEventsListener listener) { + _eventsListeners.remove(listener); + } + + /// This is exposed for internal use only. Do not use it. + @internal + void addWidgetListener(ApiVideoLiveStreamWidgetListener listener) { + _widgetListeners.add(listener); + } + + /// This is exposed for internal use only. Do not use it. + @internal + void removeWidgetListener(ApiVideoLiveStreamWidgetListener listener) { + _widgetListeners.remove(listener); + } + + void _errorListener(Object obj) { + final PlatformException e = obj as PlatformException; + for (var listener in [..._eventsListeners]) { + if (listener.onError != null) { + listener.onError!(e); + } + } + } + + void _eventListener(LiveStreamingEvent event) { + switch (event.type) { + case LiveStreamingEventType.connected: + for (var listener in [..._eventsListeners]) { + if (listener.onConnectionSuccess != null) { + listener.onConnectionSuccess!(); + } + } + break; + case LiveStreamingEventType.disconnected: + for (var listener in [..._eventsListeners]) { + if (listener.onDisconnection != null) { + listener.onDisconnection!(); + } + } + break; + case LiveStreamingEventType.connectionFailed: + for (var listener in [..._eventsListeners]) { + if (listener.onConnectionFailed != null) { + listener.onConnectionFailed!(event.data as String); + } + } + break; + case LiveStreamingEventType.videoSizeChanged: + for (var listener in [..._eventsListeners]) { + if (listener.onVideoSizeChanged != null) { + listener.onVideoSizeChanged!(event.data as Size); + } + } + break; + case LiveStreamingEventType.unknown: + // Nothing to do + break; + } + } +} + +class ApiVideoBackCamera { + const ApiVideoBackCamera({ + required this.cameraId, + required this.minFocalLength, + required this.sensorWidth, + required this.sensorHeight, + required this.horizontalFov, + }); + + final String cameraId; + final double minFocalLength; + final double sensorWidth; + final double sensorHeight; + final double horizontalFov; + + factory ApiVideoBackCamera.fromJson(Map json) { + return ApiVideoBackCamera( + cameraId: json['cameraId'] as String? ?? '', + minFocalLength: (json['minFocalLength'] as num?)?.toDouble() ?? 0, + sensorWidth: (json['sensorWidth'] as num?)?.toDouble() ?? 0, + sensorHeight: (json['sensorHeight'] as num?)?.toDouble() ?? 0, + horizontalFov: (json['horizontalFov'] as num?)?.toDouble() ?? 0, + ); + } +} + +class ApiVideoLiveStreamEventsListener { + /// Gets notified when the connection is successful + final VoidCallback? onConnectionSuccess; + + /// Gets notified when the connection failed + final Function(String)? onConnectionFailed; + + /// Gets notified when the device has been disconnected + final VoidCallback? onDisconnection; + + /// Gets notified when the video size has changed. Mostly designed to update Widget aspect ratio. + final Function(Size)? onVideoSizeChanged; + + /// Gets notified when an error occurs + final Function(Exception)? onError; + + ApiVideoLiveStreamEventsListener( + {this.onConnectionSuccess, + this.onConnectionFailed, + this.onDisconnection, + this.onVideoSizeChanged, + this.onError}); +} + +class ApiVideoLiveStreamWidgetListener { + final VoidCallback? onTextureReady; + + ApiVideoLiveStreamWidgetListener({this.onTextureReady}); +} diff --git a/plugins/apivideo_live_stream/lib/src/apivideo_live_stream_mobile_platform.dart b/plugins/apivideo_live_stream/lib/src/apivideo_live_stream_mobile_platform.dart new file mode 100644 index 0000000..e3ab582 --- /dev/null +++ b/plugins/apivideo_live_stream/lib/src/apivideo_live_stream_mobile_platform.dart @@ -0,0 +1,155 @@ +import 'package:flutter/services.dart'; +import 'package:flutter/widgets.dart'; + +import 'apivideo_live_stream_platform_interface.dart'; +import 'types.dart'; + +/// Controller of the live streaming +class ApiVideoMobileLiveStreamPlatform extends ApiVideoLiveStreamPlatform { + final MethodChannel _channel = + const MethodChannel('video.api.livestream/controller'); + + /// Registers this class as the default instance of [PathProviderPlatform]. + static void registerWith() { + ApiVideoLiveStreamPlatform.instance = ApiVideoMobileLiveStreamPlatform(); + } + + @override + Future initialize() async { + final Map? reply = + await _channel.invokeMapMethod('create'); + return reply!['textureId']! as int; + } + + @override + Future dispose() { + return _channel.invokeMapMethod('dispose'); + } + + @override + Future setVideoConfig(VideoConfig videoConfig) { + return _channel.invokeMethod('setVideoConfig', videoConfig.toJson()); + } + + @override + Future setAudioConfig(AudioConfig audioConfig) { + return _channel.invokeMethod('setAudioConfig', audioConfig.toJson()); + } + + @override + Future startStreaming( + {required String streamKey, required String url}) { + return _channel.invokeMethod('startStreaming', { + 'streamKey': streamKey, + 'url': url, + }); + } + + @override + Future stopStreaming() { + return _channel.invokeMethod('stopStreaming'); + } + + @override + Future startPreview() { + return _channel.invokeMethod('startPreview'); + } + + @override + Future stopPreview() { + return _channel.invokeMethod('stopPreview'); + } + + @override + Future getIsStreaming() async { + final Map reply = + await _channel.invokeMethod('getIsStreaming') as Map; + return reply['isStreaming'] as bool; + } + + @override + Future setCameraPosition(CameraPosition cameraPosition) { + return _channel.invokeMethod('setCameraPosition', + {'position': cameraPosition.toJson()}); + } + + @override + Future>> getBackCameras() async { + final List reply = + await _channel.invokeMethod('getBackCameras') as List; + return reply + .whereType>() + .map((item) => Map.from(item)) + .toList(growable: false); + } + + @override + Future setCameraId(String cameraId) { + return _channel.invokeMethod( + 'setCameraId', + {'cameraId': cameraId}, + ); + } + + @override + Future getCameraPosition() async { + final Map reply = + await _channel.invokeMethod('getCameraPosition') as Map; + return CameraPosition.fromJson(reply['position'] as String); + } + + @override + Future setIsMuted(bool isMuted) { + return _channel + .invokeMethod('setIsMuted', {'isMuted': isMuted}); + } + + @override + Future getIsMuted() async { + final Map reply = + await _channel.invokeMethod('getIsMuted') as Map; + return reply['isMuted'] as bool; + } + + @override + Future getVideoSize() async { + final Map reply = + await _channel.invokeMethod('getVideoSize') as Map; + if (reply.containsKey("width") && reply.containsKey("height")) { + return Size(reply["width"] as double, reply["height"] as double); + } else { + return null; + } + } + + /// Builds the preview widget. + @override + Widget buildPreview(int textureId) { + return Texture(textureId: textureId); + } + + @override + Stream liveStreamingEventsFor(int textureId) { + return EventChannel('video.api.livestream/events') + .receiveBroadcastStream() + .map((dynamic map) { + final Map event = map as Map; + switch (event['type']) { + case 'connected': + return LiveStreamingEvent(type: LiveStreamingEventType.connected); + case 'disconnected': + return LiveStreamingEvent(type: LiveStreamingEventType.disconnected); + case 'connectionFailed': + return LiveStreamingEvent( + type: LiveStreamingEventType.connectionFailed, + data: event['message']); + case 'videoSizeChanged': + return LiveStreamingEvent( + type: LiveStreamingEventType.videoSizeChanged, + data: Size(event['width'] as double, event['height'] as double)); + default: + return LiveStreamingEvent(type: LiveStreamingEventType.unknown); + } + }); + } +} diff --git a/plugins/apivideo_live_stream/lib/src/apivideo_live_stream_platform_interface.dart b/plugins/apivideo_live_stream/lib/src/apivideo_live_stream_platform_interface.dart new file mode 100644 index 0000000..59bfcc4 --- /dev/null +++ b/plugins/apivideo_live_stream/lib/src/apivideo_live_stream_platform_interface.dart @@ -0,0 +1,132 @@ +import 'package:flutter/widgets.dart'; +import 'package:plugin_platform_interface/plugin_platform_interface.dart'; + +import 'types.dart'; + +abstract class ApiVideoLiveStreamPlatform extends PlatformInterface { + /// Constructs a ApiVideoPlayerPlatform. + ApiVideoLiveStreamPlatform() : super(token: _token); + + static final Object _token = Object(); + + static ApiVideoLiveStreamPlatform _instance = _PlatformImplementation(); + + /// The default instance of [ApiVideoLiveStreamPlatform] to use. + /// + /// Defaults to [_PlatformImplementation]. + static ApiVideoLiveStreamPlatform get instance => _instance; + + /// Platform-specific implementations should set this with their own + /// platform-specific class that extends [ApiVideoLiveStreamPlatform] when + /// they register themselves. + static set instance(ApiVideoLiveStreamPlatform instance) { + PlatformInterface.verifyToken(instance, _token); + _instance = instance; + } + + /// Creates a new live stream instance + Future initialize() { + throw UnimplementedError('initialize() has not been implemented.'); + } + + /// Disposes the live stream instance + Future dispose() { + throw UnimplementedError('dispose() has not been implemented.'); + } + + Future setVideoConfig(VideoConfig videoConfig) { + throw UnimplementedError('setVideoConfig() has not been implemented.'); + } + + Future setAudioConfig(AudioConfig audioConfig) { + throw UnimplementedError('setAudioConfig() has not been implemented.'); + } + + Future startStreaming( + {required String streamKey, required String url}) { + throw UnimplementedError('startStreaming() has not been implemented.'); + } + + Future stopStreaming() { + throw UnimplementedError('stopStreaming() has not been implemented.'); + } + + Future startPreview() { + throw UnimplementedError('startPreview() has not been implemented.'); + } + + Future stopPreview() { + throw UnimplementedError('stopPreview() has not been implemented.'); + } + + Future getIsStreaming() { + throw UnimplementedError('getIsStreaming() has not been implemented.'); + } + + Future getCameraPosition() { + throw UnimplementedError('getCameraPosition() has not been implemented.'); + } + + Future setCameraPosition(CameraPosition cameraPosition) { + throw UnimplementedError('setCameraPosition() has not been implemented.'); + } + + Future>> getBackCameras() { + throw UnimplementedError('getBackCameras() has not been implemented.'); + } + + Future setCameraId(String cameraId) { + throw UnimplementedError('setCameraId() has not been implemented.'); + } + + Future getIsMuted() { + throw UnimplementedError('getIsMuted() has not been implemented.'); + } + + Future setIsMuted(bool isMuted) { + throw UnimplementedError('setIsMuted() has not been implemented.'); + } + + Future getVideoSize() { + throw UnimplementedError('getVideoSize() has not been implemented.'); + } + + /// Returns a Stream of [LiveStreamingEvent]s. + Stream liveStreamingEventsFor(int textureId) { + throw UnimplementedError( + 'liveStreamingEventsFor() has not been implemented.'); + } + + Widget buildPreview(int textureId) { + throw UnimplementedError('buildPreview() has not been implemented.'); + } +} + +class _PlatformImplementation extends ApiVideoLiveStreamPlatform {} + +class LiveStreamingEvent { + /// Adds optional parameters here if needed + final Object? data; + + /// The [LiveStreamingEventType] + final LiveStreamingEventType type; + + LiveStreamingEvent({required this.type, this.data}); +} + +enum LiveStreamingEventType { + /// The live streaming is connected. + connected, + + /// The live streaming has just been disconnected. + disconnected, + + /// The connection to the server failed. + connectionFailed, + + /// The video size has changed. + videoSizeChanged, + + /// Unknown event + unknown +} diff --git a/plugins/apivideo_live_stream/lib/src/types.dart b/plugins/apivideo_live_stream/lib/src/types.dart new file mode 100644 index 0000000..fcef735 --- /dev/null +++ b/plugins/apivideo_live_stream/lib/src/types.dart @@ -0,0 +1,6 @@ +export 'types/audio_config.dart'; +export 'types/camera_position.dart'; +export 'types/channel.dart'; +export 'types/resolution.dart'; +export 'types/sample_rate.dart'; +export 'types/video_config.dart'; diff --git a/plugins/apivideo_live_stream/lib/src/types/audio_config.dart b/plugins/apivideo_live_stream/lib/src/types/audio_config.dart new file mode 100644 index 0000000..bbdb153 --- /dev/null +++ b/plugins/apivideo_live_stream/lib/src/types/audio_config.dart @@ -0,0 +1,48 @@ +import 'package:json_annotation/json_annotation.dart'; + +import 'channel.dart'; +import 'sample_rate.dart'; + +part 'audio_config.g.dart'; + +/// Live streaming audio configuration. +@JsonSerializable() +class AudioConfig { + /// The video bitrate in bps + int bitrate; + + /// The number of audio channels + /// Only available on Android + Channel channel; + + /// The sample rate of the audio capture + /// Only available on Android + SampleRate sampleRate; + + /// Enable the echo cancellation + /// Only available on Android + bool enableEchoCanceler; + + /// Enable the noise suppressor + /// Only available on Android + bool enableNoiseSuppressor; + + /// Creates a new [AudioConfig] instance. + /// + /// [sampleRate] is only supported on Android. + /// [channel] is only supported on Android. + AudioConfig( + {this.bitrate = 128000, + this.channel = Channel.stereo, + this.sampleRate = SampleRate.kHz_44_1, + this.enableEchoCanceler = true, + this.enableNoiseSuppressor = true}) + : assert(bitrate > 0); + + /// Creates a [AudioConfig] from a [json] map. + factory AudioConfig.fromJson(Map json) => + _$AudioConfigFromJson(json); + + /// Creates a json map from a [AudioConfig]. + Map toJson() => _$AudioConfigToJson(this); +} diff --git a/plugins/apivideo_live_stream/lib/src/types/audio_config.g.dart b/plugins/apivideo_live_stream/lib/src/types/audio_config.g.dart new file mode 100644 index 0000000..6d5f68e --- /dev/null +++ b/plugins/apivideo_live_stream/lib/src/types/audio_config.g.dart @@ -0,0 +1,38 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND + +part of 'audio_config.dart'; + +// ************************************************************************** +// JsonSerializableGenerator +// ************************************************************************** + +AudioConfig _$AudioConfigFromJson(Map json) => AudioConfig( + bitrate: json['bitrate'] as int? ?? 128000, + channel: $enumDecodeNullable(_$ChannelEnumMap, json['channel']) ?? + Channel.stereo, + sampleRate: + $enumDecodeNullable(_$SampleRateEnumMap, json['sampleRate']) ?? + SampleRate.kHz_44_1, + enableEchoCanceler: json['enableEchoCanceler'] as bool? ?? true, + enableNoiseSuppressor: json['enableNoiseSuppressor'] as bool? ?? true, + ); + +Map _$AudioConfigToJson(AudioConfig instance) => + { + 'bitrate': instance.bitrate, + 'channel': _$ChannelEnumMap[instance.channel]!, + 'sampleRate': _$SampleRateEnumMap[instance.sampleRate]!, + 'enableEchoCanceler': instance.enableEchoCanceler, + 'enableNoiseSuppressor': instance.enableNoiseSuppressor, + }; + +const _$ChannelEnumMap = { + Channel.stereo: 'stereo', + Channel.mono: 'mono', +}; + +const _$SampleRateEnumMap = { + SampleRate.kHz_11: 11025, + SampleRate.kHz_22: 22050, + SampleRate.kHz_44_1: 44100, +}; diff --git a/plugins/apivideo_live_stream/lib/src/types/camera_position.dart b/plugins/apivideo_live_stream/lib/src/types/camera_position.dart new file mode 100644 index 0000000..a9340ea --- /dev/null +++ b/plugins/apivideo_live_stream/lib/src/types/camera_position.dart @@ -0,0 +1,15 @@ +/// Camera facing direction +enum CameraPosition { + /// Front camera + front, + + /// Back camera + back, + + /// Other camera (external for example) + other; + + String toJson() => name; + + static CameraPosition fromJson(String json) => values.byName(json); +} diff --git a/plugins/apivideo_live_stream/lib/src/types/channel.dart b/plugins/apivideo_live_stream/lib/src/types/channel.dart new file mode 100644 index 0000000..06af53c --- /dev/null +++ b/plugins/apivideo_live_stream/lib/src/types/channel.dart @@ -0,0 +1,12 @@ +import 'package:json_annotation/json_annotation.dart'; + +/// Audio channel +enum Channel { + /// Stereo (2 channels) + @JsonValue("stereo") + stereo, + + /// Mono (1 channel) + @JsonValue("mono") + mono, +} diff --git a/plugins/apivideo_live_stream/lib/src/types/resolution.dart b/plugins/apivideo_live_stream/lib/src/types/resolution.dart new file mode 100644 index 0000000..9763fc4 --- /dev/null +++ b/plugins/apivideo_live_stream/lib/src/types/resolution.dart @@ -0,0 +1,31 @@ +import 'dart:ui'; + +import 'package:json_annotation/json_annotation.dart'; + +/// Enumeration for camera resolution +/// Only 16/9 resolutions are supported. +enum Resolution { + /// 426x240 + @JsonValue("240p") + RESOLUTION_240(size: Size(426, 240)), + + /// 640x360 + @JsonValue("360p") + RESOLUTION_360(size: Size(640, 360)), + + /// 854x480 + @JsonValue("480p") + RESOLUTION_480(size: Size(854, 480)), + + /// 1280x720 + @JsonValue("720p") + RESOLUTION_720(size: Size(1280, 720)), + + /// 1920x1080 + @JsonValue("1080p") + RESOLUTION_1080(size: Size(1920, 1080)); + + const Resolution({required this.size}); + + final Size size; +} diff --git a/plugins/apivideo_live_stream/lib/src/types/sample_rate.dart b/plugins/apivideo_live_stream/lib/src/types/sample_rate.dart new file mode 100644 index 0000000..f39d35e --- /dev/null +++ b/plugins/apivideo_live_stream/lib/src/types/sample_rate.dart @@ -0,0 +1,18 @@ +import 'package:json_annotation/json_annotation.dart'; + +/// Enumeration for supported RTMP sample rate +@JsonEnum(valueField: 'value') +enum SampleRate { + /// 11025 Hz + kHz_11(value: 11025), + + /// 22050 Hz + kHz_22(value: 22050), + + /// 44100 Hz + kHz_44_1(value: 44100); + + const SampleRate({required this.value}); + + final int value; +} diff --git a/plugins/apivideo_live_stream/lib/src/types/video_config.dart b/plugins/apivideo_live_stream/lib/src/types/video_config.dart new file mode 100644 index 0000000..848f6f9 --- /dev/null +++ b/plugins/apivideo_live_stream/lib/src/types/video_config.dart @@ -0,0 +1,55 @@ +import 'package:json_annotation/json_annotation.dart'; + +import 'resolution.dart'; + +part 'video_config.g.dart'; + +/// Live streaming video configuration. +@JsonSerializable() +class VideoConfig { + /// The video bitrate in bps + int bitrate; + + /// The live streaming video resolution + Resolution resolution; + + /// The video frame rate in fps + int fps; + + /// Creates a [VideoConfig] instance + VideoConfig( + {required this.bitrate, + this.resolution = Resolution.RESOLUTION_720, + this.fps = 30}) + : assert(bitrate > 0), + assert(fps > 0); + + /// Creates a [VideoConfig] instance where bitrate is set according to the given [resolution]. + VideoConfig.withDefaultBitrate( + {this.resolution = Resolution.RESOLUTION_720, this.fps = 30}) + : assert(fps > 0), + bitrate = _getDefaultBitrate(resolution); + + /// Creates a [VideoConfig] from a [json] map. + factory VideoConfig.fromJson(Map json) => + _$VideoConfigFromJson(json); + + /// Creates a json map from a [VideoConfig]. + Map toJson() => _$VideoConfigToJson(this); + + /// Returns the default bitrate for the given [resolution]. + static int _getDefaultBitrate(Resolution resolution) { + switch (resolution) { + case Resolution.RESOLUTION_240: + return 800000; + case Resolution.RESOLUTION_360: + return 1000000; + case Resolution.RESOLUTION_480: + return 1300000; + case Resolution.RESOLUTION_720: + return 2000000; + case Resolution.RESOLUTION_1080: + return 3500000; + } + } +} diff --git a/plugins/apivideo_live_stream/lib/src/types/video_config.g.dart b/plugins/apivideo_live_stream/lib/src/types/video_config.g.dart new file mode 100644 index 0000000..4ee55d5 --- /dev/null +++ b/plugins/apivideo_live_stream/lib/src/types/video_config.g.dart @@ -0,0 +1,30 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND + +part of 'video_config.dart'; + +// ************************************************************************** +// JsonSerializableGenerator +// ************************************************************************** + +VideoConfig _$VideoConfigFromJson(Map json) => VideoConfig( + bitrate: json['bitrate'] as int, + resolution: + $enumDecodeNullable(_$ResolutionEnumMap, json['resolution']) ?? + Resolution.RESOLUTION_720, + fps: json['fps'] as int? ?? 30, + ); + +Map _$VideoConfigToJson(VideoConfig instance) => + { + 'bitrate': instance.bitrate, + 'resolution': _$ResolutionEnumMap[instance.resolution]!, + 'fps': instance.fps, + }; + +const _$ResolutionEnumMap = { + Resolution.RESOLUTION_240: '240p', + Resolution.RESOLUTION_360: '360p', + Resolution.RESOLUTION_480: '480p', + Resolution.RESOLUTION_720: '720p', + Resolution.RESOLUTION_1080: '1080p', +}; diff --git a/plugins/apivideo_live_stream/pubspec.yaml b/plugins/apivideo_live_stream/pubspec.yaml new file mode 100644 index 0000000..508ea76 --- /dev/null +++ b/plugins/apivideo_live_stream/pubspec.yaml @@ -0,0 +1,74 @@ +name: apivideo_live_stream +description: Flutter RTMP live stream client for your audio/video application. Made with ♥ by api.video. +version: 1.2.0 +repository: https://github.com/apivideo/api.video-flutter-live-stream +issue_tracker: https://github.com/apivideo/api.video-flutter-live-stream/issues +homepage: https://api.video + +environment: + sdk: ">=2.17.1 <4.0.0" + flutter: ">=2.5.0" + +dependencies: + flutter: + sdk: flutter + json_annotation: ^4.8.1 + native_device_orientation: ^1.2.1 + plugin_platform_interface: ^2.1.6 + meta: ^1.9.0 + +dev_dependencies: + flutter_test: + sdk: flutter + build_runner: ^2.4.6 + json_serializable: ^6.7.1 + +# For information on the generic Dart part of this file, see the +# following page: https://dart.dev/tools/pub/pubspec + +# The following section is specific to Flutter. +flutter: + # This section identifies this Flutter project as a plugin project. + # The 'pluginClass' and Android 'package' identifiers should not ordinarily + # be modified. They are used by the tooling to maintain consistency when + # adding or updating assets for this project. + plugin: + platforms: + android: + dartPluginClass: ApiVideoMobileLiveStreamPlatform + package: video.api.flutter.livestream + pluginClass: ApiVideoLiveStreamPlugin + ios: + dartPluginClass: ApiVideoMobileLiveStreamPlatform + pluginClass: ApiVideoLiveStreamPlugin + + # To add assets to your plugin package, add an assets section, like this: + # assets: + # - images/a_dot_burr.jpeg + # - images/a_dot_ham.jpeg + # + # For details regarding assets in packages, see + # https://flutter.dev/assets-and-images/#from-packages + # + # An image asset can refer to one or more resolution-specific "variants", see + # https://flutter.dev/assets-and-images/#resolution-aware. + + # To add custom fonts to your plugin package, add a fonts section here, + # in this "flutter" section. Each entry in this list should have a + # "family" key with the font family name, and a "fonts" key with a + # list giving the asset and other descriptors for the font. For + # example: + # fonts: + # - family: Schyler + # fonts: + # - asset: fonts/Schyler-Regular.ttf + # - asset: fonts/Schyler-Italic.ttf + # style: italic + # - family: Trajan Pro + # fonts: + # - asset: fonts/TrajanPro.ttf + # - asset: fonts/TrajanPro_Bold.ttf + # weight: 700 + # + # For details regarding fonts in packages, see + # https://flutter.dev/custom-fonts/#from-packages diff --git a/pubspec.yaml b/pubspec.yaml index 1cc1d6d..fa5f8b9 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -51,6 +51,9 @@ dependencies: webview_flutter_android: ^4.13.0 webview_flutter_wkwebview: ^3.26.0 webview_flutter: ^4.14.0 + apivideo_live_stream: + path: plugins/apivideo_live_stream + jwt_decoder: ^2.0.1 dev_dependencies: flutter_test: @@ -79,6 +82,8 @@ flutter: # To add assets to your application, add an assets section, like this: assets: - assets/images/ + - assets/html/ + # To add assets to your application, add an assets section, like this: # assets: # - images/a_dot_burr.jpeg