diff --git a/app/src/main/cpp/CMakeLists.txt b/app/src/main/cpp/CMakeLists.txt index 34c83694..022c40e3 100644 --- a/app/src/main/cpp/CMakeLists.txt +++ b/app/src/main/cpp/CMakeLists.txt @@ -460,6 +460,7 @@ target_link_libraries( log ) add_library(my-native-lib SHARED + native_runtime.cpp native-lib.cpp spektrafilm/spectral_data.cpp spektrafilm/spectral_filming.cpp diff --git a/app/src/main/cpp/native_runtime.cpp b/app/src/main/cpp/native_runtime.cpp new file mode 100644 index 00000000..95ab64b3 --- /dev/null +++ b/app/src/main/cpp/native_runtime.cpp @@ -0,0 +1,15 @@ +#include +#include +#include + +extern "C" JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM *, void *) { + // Configure libomp before any JNI entry point can start a parallel region. + // Android controls the CPUs available to app threads; libomp must not restore + // a cached affinity mask when creating/reusing a team. A rejected affinity + // syscall is fatal in libomp, even with its default KMP_AFFINITY=none policy. + // "disabled" turns off those interfaces while retaining parallel execution. + kmp_set_defaults("KMP_AFFINITY=disabled"); + __android_log_print(ANDROID_LOG_INFO, "PLog_NativeRuntime", + "OpenMP initialized: affinity=disabled, scheduling=system"); + return JNI_VERSION_1_6; +} diff --git a/app/src/main/cpp/raw10_unpack_jni.cpp b/app/src/main/cpp/raw10_unpack_jni.cpp index 5f7003d1..1502e030 100644 --- a/app/src/main/cpp/raw10_unpack_jni.cpp +++ b/app/src/main/cpp/raw10_unpack_jni.cpp @@ -1,8 +1,40 @@ #include "raw10_unpack.h" +#include #include #include +extern "C" JNIEXPORT jboolean JNICALL +Java_com_hinnka_mycamera_raw_Raw10Unpacker_validateHardwareBufferNative( + JNIEnv *env, jobject, jobject hardwareBuffer, jint width, jint height) { + if (!hardwareBuffer) return JNI_FALSE; + AHardwareBuffer *buffer = AHardwareBuffer_fromHardwareBuffer(env, hardwareBuffer); + if (!buffer) return JNI_FALSE; + AHardwareBuffer_Desc desc{}; + AHardwareBuffer_describe(buffer, &desc); + + // RAW10 has no named NDK AHardwareBuffer format constant. Its HAL format + // (and ImageFormat.RAW10 value) is 0x25. For this packed format, framework + // getLockedImageInfo interprets the GraphicBuffer stride as bytes and aborts + // if it is smaller than width * 10 / 8. Inspect the same descriptor without + // locking pixels or calling Image.getPlanes(), which would hit that abort. + constexpr uint32_t kRaw10Format = 0x25; + const uint64_t packedRowBytes = uint64_t(desc.width) * 10 / 8; + const bool valid = width > 0 && height > 0 && desc.layers == 1 && + desc.format == kRaw10Format && desc.width == uint32_t(width) && + desc.height == uint32_t(height) && desc.width % 4 == 0 && + desc.height % 2 == 0 && desc.stride >= packedRowBytes; + if (!valid) { + __android_log_print(ANDROID_LOG_ERROR, "PLog_Raw10Unpacker", + "Rejecting RAW10 buffer before getPlanes: image=%dx%d buffer=%ux%u " + "format=0x%x layers=%u stride=%u minRowBytes=%llu usage=0x%llx", + width, height, desc.width, desc.height, desc.format, desc.layers, + desc.stride, static_cast(packedRowBytes), + static_cast(desc.usage)); + } + return valid ? JNI_TRUE : JNI_FALSE; +} + extern "C" JNIEXPORT jboolean JNICALL Java_com_hinnka_mycamera_raw_Raw10Unpacker_unpackNative( JNIEnv *env, jobject, jobject sourceBuffer, jint sourceLimit, diff --git a/app/src/main/java/com/hinnka/mycamera/camera/Camera2Controller.kt b/app/src/main/java/com/hinnka/mycamera/camera/Camera2Controller.kt index 1fa86da1..a1462471 100644 --- a/app/src/main/java/com/hinnka/mycamera/camera/Camera2Controller.kt +++ b/app/src/main/java/com/hinnka/mycamera/camera/Camera2Controller.kt @@ -2062,6 +2062,8 @@ class Camera2Controller(private val context: Context) { } private fun clearCameraSessionState(reason: String, closeImageReader: Boolean = true) { + burstCapturing = false + _state.update { it.copy(burstCapturing = false) } photoCaptures.values.toList().forEach { failPhotoCapture(it, "session cleared: $reason", drainQueue = false) disposeFailedPhotoCapture(it) @@ -3047,6 +3049,9 @@ class Camera2Controller(private val context: Context) { } val device = cameraDevice ?: return val surface = previewSurface ?: return + // createCaptureSession closes the previous session before onConfigured runs. + // Stop exposing it while the replacement is being configured. + invalidateCaptureSession(captureSession, "preview session replacement") val captureMode = _state.value.captureMode val reader = imageReader val stabilizationReader = ensureStabilizationImageReader() @@ -3117,6 +3122,10 @@ class Camera2Controller(private val context: Context) { }, Executor { handler.post(it) }, object : CameraCaptureSession.StateCallback() { + override fun onClosed(session: CameraCaptureSession) { + invalidateCaptureSession(session, "video session closed") + } + override fun onConfigured(session: CameraCaptureSession) { if (openGeneration != cameraOpenGeneration || sessionGeneration != previewSessionGeneration) { PLog.w(TAG, "Closing stale video preview session") @@ -3180,6 +3189,10 @@ class Camera2Controller(private val context: Context) { outputConfigs, Executor { handler.post(it) }, object : CameraCaptureSession.StateCallback() { + override fun onClosed(session: CameraCaptureSession) { + invalidateCaptureSession(session, "photo session closed") + } + override fun onConfigured(session: CameraCaptureSession) { if (openGeneration != cameraOpenGeneration || sessionGeneration != previewSessionGeneration) { PLog.w(TAG, "Closing stale preview session") @@ -8655,7 +8668,30 @@ class Camera2Controller(private val context: Context) { } } + private fun invalidateCaptureSession(session: CameraCaptureSession?, reason: String) { + // A delayed close callback from the old session must not clear its replacement. + if (session == null || captureSession !== session) return + captureSession = null + previewRequestBuilder = null + val wasBurstCapturing = _state.value.burstCapturing + burstCapturing = false + _state.update { + it.copy( + isPreviewActive = false, + previewFirstFrameTimestampNs = null, + burstCapturing = false, + isCapturing = if (wasBurstCapturing) false else it.isCapturing, + ) + } + if (wasBurstCapturing) { + // Release burst preparation without submitting requests to the retired session. + resetPreviewAfterCapture() + } + PLog.d(TAG, "Capture session invalidated: $reason") + } + private fun safeCloseCaptureSession(session: CameraCaptureSession?, reason: String) { + invalidateCaptureSession(session, reason) try { session?.close() } catch (e: SecurityException) { @@ -8701,6 +8737,8 @@ class Camera2Controller(private val context: Context) { shot: PhotoCaptureContext, ) { try { + // Reject malformed HAL buffers while this capture still owns its failure/cleanup path. + image.validateBufferLayout() val width = image.width val height = image.height val reportedPhysicalCameraId = result @@ -9064,14 +9102,23 @@ class Camera2Controller(private val context: Context) { } return } + if (!_state.value.burstCapturing) return PLog.d(TAG, "Stop Burst Capture") - try { - captureSession?.abortCaptures() - } catch (e: CameraAccessException) { - PLog.w(TAG, "camera inaccessible during burst stop") - } - resetPreviewAfterCapture() + val session = captureSession + // Disable continuation before aborting; completion callbacks must not queue another batch. burstCapturing = false - _state.value = _state.value.copy(burstCapturing = false, isCapturing = false) + _state.update { it.copy(burstCapturing = false, isCapturing = false) } + try { + session?.abortCaptures() + } catch (e: CameraAccessException) { + PLog.w(TAG, "Camera inaccessible during burst stop", e) + invalidateCaptureSession(session, "camera inaccessible during burst stop") + } catch (e: IllegalStateException) { + // The framework can close the session before its onClosed callback reaches us. + PLog.w(TAG, "Capture session closed during burst stop", e) + invalidateCaptureSession(session, "session closed during burst stop") + } finally { + resetPreviewAfterCapture() + } } } diff --git a/app/src/main/java/com/hinnka/mycamera/model/SafeImage.kt b/app/src/main/java/com/hinnka/mycamera/model/SafeImage.kt index b9adc490..ff7dcb67 100644 --- a/app/src/main/java/com/hinnka/mycamera/model/SafeImage.kt +++ b/app/src/main/java/com/hinnka/mycamera/model/SafeImage.kt @@ -12,6 +12,7 @@ class SafeImage(val image: Image, private val camera2Controller: Camera2Controll private val closed = AtomicBoolean(false) private var unpackedRawBuffer: ByteBuffer? = null private var processingPlanes: Array? = null + private var bufferLayoutValidated = false /** Original camera output; [format] and [planes] describe the processing representation. */ val sourceFormat: Int = image.format @@ -32,6 +33,7 @@ class SafeImage(val image: Image, private val camera2Controller: Camera2Controll get() = synchronized(this) { check(!closed.get()) { "Image is already closed" } processingPlanes?.let { return@synchronized it } + validateBufferLayout() val resolved = if (sourceFormat == ImageFormat.RAW10) { // Decode on first pixel access, on the processing thread rather than the camera callback. val sourcePlane = image.planes.single() @@ -58,6 +60,17 @@ class SafeImage(val image: Image, private val camera2Controller: Camera2Controll val timestamp: Long get() = image.timestamp + /** Validate descriptors before handing a frame to consumers, without unpacking pixels. */ + @Synchronized + internal fun validateBufferLayout() { + check(!closed.get()) { "Image is already closed" } + if (bufferLayoutValidated) return + if (sourceFormat == ImageFormat.RAW10) { + Raw10Unpacker.validateImageLayout(image) + } + bufferLayoutValidated = true + } + @Synchronized override fun close() { if (closed.compareAndSet(false, true)) { diff --git a/app/src/main/java/com/hinnka/mycamera/raw/Raw10Unpacker.kt b/app/src/main/java/com/hinnka/mycamera/raw/Raw10Unpacker.kt index dc7c6618..30449bf4 100644 --- a/app/src/main/java/com/hinnka/mycamera/raw/Raw10Unpacker.kt +++ b/app/src/main/java/com/hinnka/mycamera/raw/Raw10Unpacker.kt @@ -1,5 +1,7 @@ package com.hinnka.mycamera.raw +import android.hardware.HardwareBuffer +import android.media.Image import com.hinnka.mycamera.utils.LargeDirectBuffer import com.hinnka.mycamera.utils.PLog import java.nio.ByteBuffer @@ -10,6 +12,22 @@ internal object Raw10Unpacker { System.loadLibrary("my-native-lib") } + private external fun validateHardwareBufferNative( + buffer: HardwareBuffer, + width: Int, + height: Int, + ): Boolean + + /** Must run before getPlanes(): malformed RAW10 strides abort inside the framework. */ + fun validateImageLayout(image: Image) { + val hardwareBuffer = checkNotNull(image.hardwareBuffer) { "RAW10 image has no hardware buffer" } + hardwareBuffer.use { + check(validateHardwareBufferNative(it, image.width, image.height)) { + "Invalid RAW10 hardware buffer layout for ${image.width}x${image.height}" + } + } + } + private external fun unpackNative( source: ByteBuffer, sourceLimit: Int,