diff --git a/app/src/main/cpp/CMakeLists.txt b/app/src/main/cpp/CMakeLists.txt index 94889cf8..9560a6ef 100644 --- a/app/src/main/cpp/CMakeLists.txt +++ b/app/src/main/cpp/CMakeLists.txt @@ -5,6 +5,10 @@ enable_language(ASM) set(ADOBE_DNG_SOURCE_DIR ${CMAKE_CURRENT_SOURCE_DIR}/dcp/dng_sdk/source) set(ADOBE_XMP_STUB_DIR ${CMAKE_CURRENT_SOURCE_DIR}/dcp/XMPStub/include) set(ULTRAHDR_SOURCE_DIR ${CMAKE_CURRENT_SOURCE_DIR}/libultrahdr) +set( + MGC_EIS_RECONSTRUCTION_DIR + "${CMAKE_CURRENT_SOURCE_DIR}/../../../../research/mgc_eis_reconstruction" +) option(PHOTON_ENABLE_DNG_JXL "Enable Adobe DNG SDK JPEG XL support" OFF) set( @@ -158,6 +162,7 @@ include_directories(${CMAKE_CURRENT_BINARY_DIR}/libjpeg-turbo) include_directories(${ULTRAHDR_SOURCE_DIR}) include_directories(${ADOBE_DNG_SOURCE_DIR}) include_directories(${ADOBE_XMP_STUB_DIR}) +include_directories(${MGC_EIS_RECONSTRUCTION_DIR}) # 启用 OpenMP find_package(OpenMP REQUIRED) @@ -233,6 +238,12 @@ add_library(my-native-lib SHARED raw_signal_stats_jni.cpp raw_legacy_auto_exposure_solver.cpp mgc_strength_map_scaler.cpp + mgc_eis_reconstruction_jni.cpp + "${MGC_EIS_RECONSTRUCTION_DIR}/mgc_eis_reconstruction.cpp" + "${MGC_EIS_RECONSTRUCTION_DIR}/mgc_type18_engine.cpp" + "${MGC_EIS_RECONSTRUCTION_DIR}/mgc_type18_gyro.cpp" + "${MGC_EIS_RECONSTRUCTION_DIR}/mgc_type18_lookahead.cpp" + "${MGC_EIS_RECONSTRUCTION_DIR}/mgc_type18_projection.cpp" jpeg_export_jni.cpp jpeg_r_encoder.cpp yuv_utils.cpp @@ -282,6 +293,20 @@ set_source_files_properties( COMPILE_OPTIONS "-fno-fast-math;-ffp-contract=off" ) +# The reconstructed MGC type-18 state machine relies on ordered quaternion, +# crop-feasibility and homography arithmetic. It also rejects non-finite JNI +# output. Keep that path independent of the target-wide fast-math setting. +set_source_files_properties( + mgc_eis_reconstruction_jni.cpp + "${MGC_EIS_RECONSTRUCTION_DIR}/mgc_eis_reconstruction.cpp" + "${MGC_EIS_RECONSTRUCTION_DIR}/mgc_type18_engine.cpp" + "${MGC_EIS_RECONSTRUCTION_DIR}/mgc_type18_gyro.cpp" + "${MGC_EIS_RECONSTRUCTION_DIR}/mgc_type18_lookahead.cpp" + "${MGC_EIS_RECONSTRUCTION_DIR}/mgc_type18_projection.cpp" + PROPERTIES + COMPILE_OPTIONS "-fno-fast-math;-ffp-contract=off" +) + # MGC host-side tuning and noise-model builders rely on scalar IEEE behavior. # Keep them independent of the target-wide fast-math flags. set_source_files_properties( diff --git a/app/src/main/cpp/mgc_eis_reconstruction_jni.cpp b/app/src/main/cpp/mgc_eis_reconstruction_jni.cpp new file mode 100644 index 00000000..9f0bb36c --- /dev/null +++ b/app/src/main/cpp/mgc_eis_reconstruction_jni.cpp @@ -0,0 +1,393 @@ +#include + +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +#include "mgc_eis_reconstruction.hpp" + +namespace { + +using mgc_eis_reconstruction::Engine; +using mgc_eis_reconstruction::EngineConfig; +using mgc_eis_reconstruction::FrameMetadata; +using mgc_eis_reconstruction::GyroSample; +using mgc_eis_reconstruction::LensOffsetSample; +using mgc_eis_reconstruction::Quaternion; +using mgc_eis_reconstruction::Vec2; +using mgc_eis_reconstruction::Vec3; +using mgc_eis_reconstruction::norm; +using mgc_eis_reconstruction::quaternionLog; + +constexpr char kLogTag[] = "PhotonMgcEis"; +constexpr jlong kPendingTimestamp = -1; +// `device_key=blueline` resolves to iyk.c / product profile 7 in the installed +// MGC build. The factory fixes these values; keeping them here prevents a UI +// or JNI caller from silently constructing an unrelated profile. +constexpr int kMgcProfileStripCount = 12; +constexpr int kMgcProfileLookaheadFrames = 7; + +struct HardwareBufferEglImage { + EGLDisplay display = EGL_NO_DISPLAY; + EGLImageKHR image = EGL_NO_IMAGE_KHR; + AHardwareBuffer *buffer = nullptr; +}; + +struct Handle { + Handle(EngineConfig config, bool front_camera_coordinate_mode) + : engine(std::move(config)), + front_camera_coordinate_mode(front_camera_coordinate_mode) {} + Engine engine; + bool front_camera_coordinate_mode = false; + std::uint64_t submitted_frames = 0; + std::uint64_t emitted_frames = 0; + std::uint64_t dropped_frames = 0; + Vec3 latest_native_gyro; + Quaternion previous_measured_pose = Quaternion::identity(); + Quaternion previous_virtual_pose = Quaternion::identity(); + Vec2 previous_warp_center; + bool has_previous_output = false; +}; + +Handle *fromJlong(jlong value) { + return reinterpret_cast(static_cast(value)); +} + +jlong toJlong(Handle *value) { + return static_cast(reinterpret_cast(value)); +} + +void logFailure(const char *operation, const std::exception &error) { + __android_log_print(ANDROID_LOG_ERROR, kLogTag, "%s failed: %s", operation, + error.what()); +} + +template +Procedure eglProcedure(const char *name) { + return reinterpret_cast(eglGetProcAddress(name)); +} + +HardwareBufferEglImage *fromHardwareBufferImageJlong(jlong value) { + return reinterpret_cast( + static_cast(value)); +} + +jlong toHardwareBufferImageJlong(HardwareBufferEglImage *value) { + return static_cast(reinterpret_cast(value)); +} + +} // namespace + +extern "C" JNIEXPORT jlong JNICALL +Java_com_hinnka_mycamera_stabilization_MgcEisNativeBridge_create( + JNIEnv *, jobject, jint width, jint height, jboolean front_facing, + jfloat strength, jint lookahead_frames) { + try { + EngineConfig config; + config.output_width = width; + config.output_height = height; + config.active_array_width = width; + config.active_array_height = height; + config.crop_width = width; + config.crop_height = height; + config.num_strips = kMgcProfileStripCount; + config.lookahead_frames = std::clamp(static_cast(lookahead_frames), 3, 10); + config.stabilization_strength = + std::clamp(static_cast(strength), 0.0, 1.0); + return toJlong( + new Handle(std::move(config), front_facing == JNI_TRUE)); + } catch (const std::exception &error) { + logFailure("create", error); + return 0; + } +} + +extern "C" JNIEXPORT void JNICALL +Java_com_hinnka_mycamera_stabilization_MgcEisNativeBridge_release( + JNIEnv *, jobject, jlong handle) { + delete fromJlong(handle); +} + +extern "C" JNIEXPORT jboolean JNICALL +Java_com_hinnka_mycamera_stabilization_MgcEisNativeBridge_processGyro( + JNIEnv *, jobject, jlong handle, jfloat x, jfloat y, jfloat z, + jlong timestamp_ns) { + Handle *state = fromJlong(handle); + if (!state) { + return JNI_FALSE; + } + try { + // V25 0x22C097C writes `STP S1, S0, [SP]`: the native gyro sample therefore + // receives Java Y then Java X. Front-camera mode negates Java Y and Z + // before that ordered store. + const double native_x = state->front_camera_coordinate_mode ? -y : y; + const double native_y = x; + const double native_z = state->front_camera_coordinate_mode ? -z : z; + state->latest_native_gyro = {native_x, native_y, native_z}; + return state->engine.pushGyro( + GyroSample{timestamp_ns, + Vec3{native_x, native_y, native_z}}) + ? JNI_TRUE + : JNI_FALSE; + } catch (const std::exception &error) { + logFailure("processGyro", error); + return JNI_FALSE; + } +} + +extern "C" JNIEXPORT jboolean JNICALL +Java_com_hinnka_mycamera_stabilization_MgcEisNativeBridge_processLensOffset( + JNIEnv *, jobject, jlong handle, jfloat x_shift_pixels, + jfloat y_shift_pixels, jlong timestamp_ns, jint camera_type) { + Handle *state = fromJlong(handle); + if (!state) { + return JNI_FALSE; + } + try { + return state->engine.pushLensOffset(LensOffsetSample{ + timestamp_ns, + Vec2{x_shift_pixels, y_shift_pixels}, + camera_type, + }) + ? JNI_TRUE + : JNI_FALSE; + } catch (const std::exception &error) { + logFailure("processLensOffset", error); + return JNI_FALSE; + } +} + +extern "C" JNIEXPORT jlong JNICALL +Java_com_hinnka_mycamera_stabilization_MgcEisNativeBridge_processFrame( + JNIEnv *env, jobject, jlong handle, jlong source_timestamp_ns, + jlong first_row_center_timestamp_ns, + jlong exposure_time_ns, jlong rolling_shutter_skew_ns, + jfloat inverse_focal_length, + jint active_width, jint active_height, jint crop_width, jint crop_height, + jfloatArray row_homographies, jfloatArray output_state) { + Handle *state = fromJlong(handle); + if (!state || !row_homographies || + env->GetArrayLength(row_homographies) < 12 * 9) { + return kPendingTimestamp; + } + try { + ++state->submitted_frames; + state->engine.setActiveArraySize(active_width, active_height); + state->engine.setCropWindowSize(crop_width, crop_height); + FrameMetadata frame; + frame.source_timestamp_ns = source_timestamp_ns; + frame.frame_timestamp_ns = first_row_center_timestamp_ns; + frame.exposure_time_ns = exposure_time_ns; + frame.rolling_shutter_skew_ns = rolling_shutter_skew_ns; + frame.inverse_focal_length = inverse_focal_length; + const auto result = state->engine.processFrame(frame); + if (!result) { + return kPendingTimestamp; + } + if (result->strip_input_to_output.size() != 12) { + ++state->dropped_frames; + if (state->dropped_frames <= 3 || state->dropped_frames % 30 == 0) { + __android_log_print( + ANDROID_LOG_WARN, kLogTag, + "MGC profile dropped output ts=%lld submitted=%llu dropped=%llu", + static_cast(result->timestamp_ns), + static_cast(state->submitted_frames), + static_cast(state->dropped_frames)); + } + return -result->source_timestamp_ns; + } + + for (const auto &matrix : result->strip_input_to_output) { + for (const double value : matrix.v) { + if (!std::isfinite(value)) { + ++state->dropped_frames; + __android_log_print(ANDROID_LOG_ERROR, kLogTag, + "MGC profile rejected non-finite matrix ts=%lld", + static_cast(result->timestamp_ns)); + return -result->source_timestamp_ns; + } + } + } + ++state->emitted_frames; + const auto &first_matrix = result->strip_input_to_output.front(); + const Vec2 warp_center = first_matrix.transformPoint({}); + double minimum_row_x = warp_center.x; + double maximum_row_x = warp_center.x; + double minimum_row_y = warp_center.y; + double maximum_row_y = warp_center.y; + for (const auto &row_matrix : result->strip_input_to_output) { + const Vec2 row_center = row_matrix.transformPoint({}); + minimum_row_x = std::min(minimum_row_x, row_center.x); + maximum_row_x = std::max(maximum_row_x, row_center.x); + minimum_row_y = std::min(minimum_row_y, row_center.y); + maximum_row_y = std::max(maximum_row_y, row_center.y); + } + double measured_delta = 0.0; + double virtual_delta = 0.0; + Vec2 warp_delta; + if (state->has_previous_output) { + measured_delta = norm(quaternionLog( + result->diagnostic_measured_pose * + state->previous_measured_pose.inverse())); + virtual_delta = norm(quaternionLog( + result->diagnostic_virtual_pose * + state->previous_virtual_pose.inverse())); + warp_delta = {warp_center.x - state->previous_warp_center.x, + warp_center.y - state->previous_warp_center.y}; + } + state->previous_measured_pose = result->diagnostic_measured_pose; + state->previous_virtual_pose = result->diagnostic_virtual_pose; + state->previous_warp_center = warp_center; + state->has_previous_output = true; + __android_log_print( + ANDROID_LOG_INFO, kLogTag, + "MGC profile trace ts=%lld n=%llu gyro=%.6f measuredD=%.6f " + "virtualD=%.6f center=(%.6f,%.6f) centerD=(%.6f,%.6f) " + "rowSpan=(%.6f,%.6f) tripod=%d", + static_cast(result->timestamp_ns), + static_cast(state->emitted_frames), + norm(state->latest_native_gyro), measured_delta, virtual_delta, + warp_center.x, warp_center.y, warp_delta.x, warp_delta.y, + maximum_row_x - minimum_row_x, maximum_row_y - minimum_row_y, + result->tripod_mode ? 1 : 0); + if (state->emitted_frames <= 3 || state->emitted_frames % 30 == 0) { + const auto &matrix = result->strip_input_to_output.front().v; + __android_log_print( + ANDROID_LOG_INFO, kLogTag, + "MGC profile output ts=%lld submitted=%llu emitted=%llu h00=%.6f " + "h02=%.6f h11=%.6f h12=%.6f h22=%.6f", + static_cast(result->timestamp_ns), + static_cast(state->submitted_frames), + static_cast(state->emitted_frames), matrix[0], + matrix[2], matrix[4], matrix[5], matrix[8]); + } + + jfloat *matrices = env->GetFloatArrayElements(row_homographies, nullptr); + if (!matrices) { + return -result->source_timestamp_ns; + } + for (std::size_t strip = 0; strip < result->strip_input_to_output.size(); + ++strip) { + const auto &matrix = result->strip_input_to_output[strip].v; + for (std::size_t value = 0; value < matrix.size(); ++value) { + matrices[strip * 9 + value] = static_cast(matrix[value]); + } + } + env->ReleaseFloatArrayElements(row_homographies, matrices, 0); + + if (output_state && env->GetArrayLength(output_state) >= 2) { + const jfloat values[2] = { + static_cast(result->applied_strength), + result->tripod_mode ? 1.0f : 0.0f, + }; + env->SetFloatArrayRegion(output_state, 0, 2, values); + } + return result->source_timestamp_ns; + } catch (const std::exception &error) { + logFailure("processFrame", error); + return kPendingTimestamp; + } +} + +extern "C" JNIEXPORT jlong JNICALL +Java_com_hinnka_mycamera_stabilization_MgcEisNativeBridge_createHardwareBufferImage( + JNIEnv *env, jobject, jobject hardware_buffer) { + if (!hardware_buffer) { + return 0; + } + const EGLDisplay display = eglGetCurrentDisplay(); + if (display == EGL_NO_DISPLAY) { + __android_log_print(ANDROID_LOG_WARN, kLogTag, + "MGC EGLImage import without a current EGL display"); + return 0; + } + const auto get_native_client_buffer = + eglProcedure( + "eglGetNativeClientBufferANDROID"); + const auto create_image = + eglProcedure("eglCreateImageKHR"); + if (!get_native_client_buffer || !create_image) { + __android_log_print(ANDROID_LOG_WARN, kLogTag, + "MGC EGLImage extensions unavailable"); + return 0; + } + AHardwareBuffer *buffer = + AHardwareBuffer_fromHardwareBuffer(env, hardware_buffer); + if (!buffer) { + __android_log_print(ANDROID_LOG_WARN, kLogTag, + "MGC cannot unwrap Java HardwareBuffer"); + return 0; + } + const EGLClientBuffer client_buffer = get_native_client_buffer(buffer); + if (!client_buffer) { + __android_log_print(ANDROID_LOG_WARN, kLogTag, + "MGC cannot create native EGL client buffer"); + return 0; + } + AHardwareBuffer_acquire(buffer); + const EGLImageKHR image = create_image( + display, EGL_NO_CONTEXT, EGL_NATIVE_BUFFER_ANDROID, client_buffer, + nullptr); + if (image == EGL_NO_IMAGE_KHR) { + const EGLint error = eglGetError(); + AHardwareBuffer_release(buffer); + __android_log_print(ANDROID_LOG_WARN, kLogTag, + "MGC eglCreateImageKHR failed: 0x%x", error); + return 0; + } + auto *result = new HardwareBufferEglImage{display, image, buffer}; + return toHardwareBufferImageJlong(result); +} + +extern "C" JNIEXPORT jboolean JNICALL +Java_com_hinnka_mycamera_stabilization_MgcEisNativeBridge_bindHardwareBufferImage( + JNIEnv *, jobject, jlong image_handle, jint texture_id) { + auto *source = fromHardwareBufferImageJlong(image_handle); + if (!source || source->display != eglGetCurrentDisplay() || texture_id == 0) { + return JNI_FALSE; + } + const auto bind_image = eglProcedure( + "glEGLImageTargetTexture2DOES"); + if (!bind_image) { + __android_log_print(ANDROID_LOG_WARN, kLogTag, + "MGC glEGLImageTargetTexture2DOES unavailable"); + return JNI_FALSE; + } + glBindTexture(GL_TEXTURE_EXTERNAL_OES, static_cast(texture_id)); + bind_image(GL_TEXTURE_EXTERNAL_OES, source->image); + const GLenum error = glGetError(); + if (error != GL_NO_ERROR) { + __android_log_print(ANDROID_LOG_WARN, kLogTag, + "MGC EGLImage external texture bind failed: 0x%x", + error); + return JNI_FALSE; + } + return JNI_TRUE; +} + +extern "C" JNIEXPORT void JNICALL +Java_com_hinnka_mycamera_stabilization_MgcEisNativeBridge_destroyHardwareBufferImage( + JNIEnv *, jobject, jlong image_handle) { + std::unique_ptr source( + fromHardwareBufferImageJlong(image_handle)); + if (!source) { + return; + } + const auto destroy_image = + eglProcedure("eglDestroyImageKHR"); + if (destroy_image && source->display != EGL_NO_DISPLAY && + source->image != EGL_NO_IMAGE_KHR) { + destroy_image(source->display, source->image); + } + if (source->buffer) { + AHardwareBuffer_release(source->buffer); + } +} 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 7fd12595..ed288a1b 100644 --- a/app/src/main/java/com/hinnka/mycamera/camera/Camera2Controller.kt +++ b/app/src/main/java/com/hinnka/mycamera/camera/Camera2Controller.kt @@ -41,6 +41,8 @@ import com.hinnka.mycamera.lut.VideoColorEffectLayer import com.hinnka.mycamera.model.SafeImage import com.hinnka.mycamera.model.ColorRecipeParams import com.hinnka.mycamera.stabilization.RealtimeStabilizationCoordinator +import com.hinnka.mycamera.stabilization.normalizeStabilizationLookahead +import com.hinnka.mycamera.stabilization.normalizeStabilizationStrength import com.hinnka.mycamera.utils.DeviceUtil import com.hinnka.mycamera.utils.OrientationObserver import com.hinnka.mycamera.video.CaptureMode @@ -275,6 +277,7 @@ class Camera2Controller(private val context: Context) { private var previewSurface: Surface? = null private var previewSurfaceTexture: SurfaceTexture? = null private var imageReader: ImageReader? = null + private var stabilizationImageReader: ImageReader? = null // 降噪等级 (0=Off, 1=Fast, 2=High Quality, 3=ZSL, 4=Minimal, 5=Auto) private var nrLevel = 5 @@ -692,7 +695,11 @@ class Camera2Controller(private val context: Context) { ) { super.onCaptureCompleted(session, request, result) - realtimeStabilizationCoordinator.submitCaptureResult(result) + realtimeStabilizationCoordinator.submitCaptureResult( + result = result, + request = request, + outputPhysicalCameraId = activeOutputPhysicalCameraId, + ) val timestamp = result.get(CaptureResult.SENSOR_TIMESTAMP) if (timestamp != null && isRawCaptureReader(imageReader)) { @@ -1698,6 +1705,8 @@ class Camera2Controller(private val context: Context) { if (closeImageReader) { safeCloseImageReader(imageReader) imageReader = null + safeCloseImageReader(stabilizationImageReader) + stabilizationImageReader = null } } @@ -2605,6 +2614,7 @@ class Camera2Controller(private val context: Context) { val surface = previewSurface ?: return val captureMode = _state.value.captureMode val reader = imageReader + val stabilizationReader = ensureStabilizationImageReader() val videoSurface = if ( captureMode == CaptureMode.VIDEO && _state.value.videoRecordingState.shouldAttachCameraInput() @@ -2625,6 +2635,7 @@ class Camera2Controller(private val context: Context) { try { previewRequestBuilder = device.createCaptureRequest(templateType).apply { addTarget(surface) + stabilizationReader?.surface?.let(::addTarget) videoSurface?.let(::addTarget) // 应用所有相机参数(曝光、白平衡、闪光灯、变焦、色调映射) @@ -2632,6 +2643,7 @@ class Camera2Controller(private val context: Context) { } val surfaces = mutableListOf(surface) + stabilizationReader?.surface?.let(surfaces::add) videoSurface?.let(surfaces::add) if (captureMode == CaptureMode.PHOTO) { val captureReader = reader ?: return @@ -2639,7 +2651,10 @@ class Camera2Controller(private val context: Context) { } if (captureMode == CaptureMode.VIDEO) { - val useHlgCapture = _state.value.useHlg10 && activeOutputPhysicalCameraId == null && !forceStandardSession + val useHlgCapture = _state.value.useHlg10 && + stabilizationReader == null && + activeOutputPhysicalCameraId == null && + !forceStandardSession val sessionConfig = SessionConfiguration( SessionConfiguration.SESSION_REGULAR, buildList { @@ -2650,6 +2665,15 @@ class Camera2Controller(private val context: Context) { outputType = CameraOutputType.PREVIEW ) ) + stabilizationReader?.surface?.let { eisSurface -> + add( + createOutputConfiguration( + surface = eisSurface, + useHlgCapture = false, + outputType = CameraOutputType.PREVIEW, + ) + ) + } videoSurface?.let { encoderSurface -> add( createOutputConfiguration( @@ -2673,6 +2697,7 @@ class Camera2Controller(private val context: Context) { } else if (_state.value.currentDynamicRangeProfile != "STANDARD") { _state.value = _state.value.copy(currentDynamicRangeProfile = "STANDARD") } + closeUnusedStabilizationImageReader(stabilizationReader) onSessionConfigured(session, openGeneration, sessionGeneration) } @@ -2718,6 +2743,7 @@ class Camera2Controller(private val context: Context) { // Android 9+ 使用 SessionConfiguration val useHlgCapture = _state.value.useHlg10 && + stabilizationReader == null && activeOutputPhysicalCameraId == null && !isRawCaptureReader(reader) && !forceStandardSession @@ -2736,6 +2762,15 @@ class Camera2Controller(private val context: Context) { outputType = CameraOutputType.PREVIEW ) ) + stabilizationReader?.surface?.let { eisSurface -> + add( + createOutputConfiguration( + surface = eisSurface, + useHlgCapture = false, + outputType = CameraOutputType.PREVIEW, + ) + ) + } reader?.surface?.let { captureSurface -> add( createOutputConfiguration( @@ -2766,6 +2801,7 @@ class Camera2Controller(private val context: Context) { } else if (_state.value.currentDynamicRangeProfile != "STANDARD") { _state.value = _state.value.copy(currentDynamicRangeProfile = "STANDARD") } + closeUnusedStabilizationImageReader(stabilizationReader) onSessionConfigured(session, openGeneration, sessionGeneration) } @@ -2856,6 +2892,53 @@ class Camera2Controller(private val context: Context) { } } + private fun ensureStabilizationImageReader(): ImageReader? { + val state = _state.value + val enabled = when (state.captureMode) { + CaptureMode.PHOTO -> state.photoPreviewStabilizationEnabled && + realtimeStabilizationCoordinator.isCurrentCameraSupported + CaptureMode.VIDEO -> shouldUseVideoEnhancedStabilization() + } + if (!enabled) return null + val size = state.currentPreviewSize + if (size.width <= 0 || size.height <= 0) return null + stabilizationImageReader?.let { existing -> + if (existing.width == size.width && existing.height == size.height && + existing.imageFormat == ImageFormat.YUV_420_888 + ) { + return existing + } + safeCloseImageReader(existing) + stabilizationImageReader = null + } + return ImageReader.newInstance( + size.width, + size.height, + ImageFormat.YUV_420_888, + RealtimeStabilizationCoordinator.STABILIZATION_IMAGE_READER_MAX_IMAGES, + ).also { reader -> + reader.setOnImageAvailableListener({ source -> + while (true) { + val image = try { + source.acquireNextImage() + } catch (error: IllegalStateException) { + PLog.e(TAG, "Cannot acquire MGC YUV image", error) + null + } ?: break + realtimeStabilizationCoordinator.submitStabilizationImage(image) + } + }, cameraHandler) + stabilizationImageReader = reader + PLog.i(TAG, "MGC YUV input configured: ${size.width}x${size.height}") + } + } + + private fun closeUnusedStabilizationImageReader(activeReader: ImageReader?) { + if (activeReader != null) return + safeCloseImageReader(stabilizationImageReader) + stabilizationImageReader = null + } + private fun retryPreviewSessionWithoutVendorSessionParameters( reason: String, forceStandardSession: Boolean, @@ -3163,6 +3246,7 @@ class Camera2Controller(private val context: Context) { return when (format) { NO_IMAGE_READER_FORMAT -> "NO_IMAGE_READER" ImageFormat.RAW_SENSOR -> "RAW_SENSOR" + ImageFormat.PRIVATE -> "PRIVATE" ImageFormat.YCBCR_P010 -> "YCBCR_P010" ImageFormat.YUV_420_888 -> "YUV_420_888" ImageFormat.JPEG -> "JPEG" @@ -3272,7 +3356,7 @@ class Camera2Controller(private val context: Context) { applyFlashSettings(builder, currentState, isCapture, useStillFlashTrigger) // 4. 变焦设置 - applyZoomSettings(builder, currentState) + applyZoomSettings(builder, currentState, isCapture) // 5. 对焦设置 applyFocusSettings(builder, currentState) @@ -3286,7 +3370,7 @@ class Camera2Controller(private val context: Context) { } // 8. 防抖设置 - applyStabilizationSettings(builder, currentState) + applyStabilizationSettings(builder, currentState, isCapture) if (!isRawCapture) { // 9. 静态拍照后处理质量设置 @@ -4289,7 +4373,11 @@ class Camera2Controller(private val context: Context) { /** * 应用变焦设置 */ - private fun applyZoomSettings(builder: CaptureRequest.Builder, state: CameraState) { + private fun applyZoomSettings( + builder: CaptureRequest.Builder, + state: CameraState, + isCapture: Boolean = false, + ) { val openCameraId = getActiveOpenCameraId() if (openCameraId.isEmpty()) return @@ -4299,7 +4387,8 @@ class Camera2Controller(private val context: Context) { val zoomRatioRange = characteristics.get(CameraCharacteristics.CONTROL_ZOOM_RATIO_RANGE) val minZoom = zoomRatioRange?.lower ?: 1f val maxSupportedZoom = zoomRatioRange?.upper ?: maxZoom - val zoomRatio = state.zoomRatio.coerceIn(minZoom, maxSupportedZoom) + val userZoomRatio = state.zoomRatio.coerceIn(minZoom, maxSupportedZoom) + val zoomRatio = userZoomRatio val activeRect = characteristics.get(CameraCharacteristics.SENSOR_INFO_ACTIVE_ARRAY_SIZE) applyZoomRequestSettings( @@ -4382,9 +4471,14 @@ class Camera2Controller(private val context: Context) { /** * 应用防抖设置 * - * 视频模式按用户选项启用 EIS/OIS;EIS 优先使用预览防抖以匹配当前 GL 录制链路。 + * 视频模式按用户选项启用 EIS/OIS。算法防抖与 MGC 请求链一致,关闭 Camera2 + * 硬件 EIS 和 HAL OIS,由同一套陀螺仪滚快门网格同时处理预览与录制。 */ - private fun applyStabilizationSettings(builder: CaptureRequest.Builder, state: CameraState) { + private fun applyStabilizationSettings( + builder: CaptureRequest.Builder, + state: CameraState, + isCapture: Boolean = false, + ) { try { if (state.captureMode == CaptureMode.VIDEO) { val mode = state.videoConfig.stabilizationMode @@ -4412,20 +4506,38 @@ class Camera2Controller(private val context: Context) { } ) } + applyOisDataMode(builder, enhancedSelected) return } if (availableOpticalStabilizationModes.contains(CaptureRequest.LENS_OPTICAL_STABILIZATION_MODE_ON)) { builder.set( CaptureRequest.LENS_OPTICAL_STABILIZATION_MODE, - CaptureRequest.LENS_OPTICAL_STABILIZATION_MODE_ON + if (state.photoPreviewStabilizationEnabled && !isCapture) { + CaptureRequest.LENS_OPTICAL_STABILIZATION_MODE_OFF + } else { + CaptureRequest.LENS_OPTICAL_STABILIZATION_MODE_ON + } ) } + applyOisDataMode(builder, state.photoPreviewStabilizationEnabled && !isCapture) } catch (e: Exception) { PLog.e(TAG, "Failed to apply stabilization settings", e) } } + private fun applyOisDataMode(builder: CaptureRequest.Builder, enabled: Boolean) { + if (!isCaptureRequestKeyAvailable(CaptureRequest.STATISTICS_OIS_DATA_MODE.name)) return + builder.set( + CaptureRequest.STATISTICS_OIS_DATA_MODE, + if (enabled) { + CaptureRequest.STATISTICS_OIS_DATA_MODE_ON + } else { + CaptureRequest.STATISTICS_OIS_DATA_MODE_OFF + }, + ) + } + private fun resolveVideoStabilizationRequestMode(mode: VideoStabilizationMode): Int? { return when (mode) { VideoStabilizationMode.EIS -> when { @@ -6192,18 +6304,9 @@ class Camera2Controller(private val context: Context) { fun setVideoFps(fps: VideoFpsPreset) { val currentConfig = _state.value.videoConfig - val stabilizationMode = if ( - currentConfig.stabilizationMode == VideoStabilizationMode.ENHANCED && - fps != VideoFpsPreset.FPS_30 - ) { - preferredHardwareVideoStabilizationMode() - } else { - currentConfig.stabilizationMode - } _state.value = _state.value.copy( videoConfig = currentConfig.copy( fps = fps, - stabilizationMode = stabilizationMode ) ) refreshVideoCapabilities() @@ -6236,16 +6339,6 @@ class Camera2Controller(private val context: Context) { val previousConfig = _state.value.videoConfig _state.value = _state.value.copy( videoConfig = previousConfig.copy( - resolution = if (mode == VideoStabilizationMode.ENHANCED) { - VideoResolutionPreset.FHD_1080P - } else { - previousConfig.resolution - }, - fps = if (mode == VideoStabilizationMode.ENHANCED) { - VideoFpsPreset.FPS_30 - } else { - previousConfig.fps - }, stabilizationMode = mode, ) ) @@ -6285,8 +6378,35 @@ class Camera2Controller(private val context: Context) { videoRecorder.setPreferredAudioInputId(normalizedAudioInputId) } + fun setVideoEnhancedStabilizationStrength(strength: Float) { + _state.value = _state.value.copy( + videoConfig = _state.value.videoConfig.copy( + enhancedStabilizationStrength = normalizeStabilizationStrength(strength) + ) + ) + } + + fun setVideoEnhancedStabilizationLookahead(lookahead: Int) { + _state.value = _state.value.copy( + videoConfig = _state.value.videoConfig.copy( + enhancedStabilizationLookahead = normalizeStabilizationLookahead(lookahead) + ) + ) + } + fun setPhotoPreviewStabilizationEnabled(enabled: Boolean) { + if (_state.value.photoPreviewStabilizationEnabled == enabled) return _state.value = _state.value.copy(photoPreviewStabilizationEnabled = enabled) + if (_state.value.captureMode == CaptureMode.PHOTO && + cameraDevice != null && previewSurface != null + ) { + createPreviewSession(openGeneration = cameraOpenGeneration) + return + } + previewRequestBuilder?.apply { + applyBaseCameraSettings(this, isCapture = false) + updatePreview() + } } fun setVideoRecordingPath(recordingPath: VideoRecordingPath, recordingTreeUri: String? = null) { @@ -6379,13 +6499,17 @@ class Camera2Controller(private val context: Context) { hasActiveLut = _state.value.lutEnabled && _state.value.currentLutName != null ), colorLayers = colorLayers, - hlgInput = _state.value.useHlg10, + hlgInput = _state.value.useHlg10 && !useEnhancedStabilization, cameraTimestampSource = getActiveOpenCameraCharacteristics() ?.get(CameraCharacteristics.SENSOR_INFO_TIMESTAMP_SOURCE) ?: CameraCharacteristics.SENSOR_INFO_TIMESTAMP_SOURCE_UNKNOWN, orientationHintDegrees = resolveDedicatedVideoOrientationHintDegrees(orientationOffsetDegrees), flipEncodedFrame = shouldFlipEncodedFrame, enhancedStabilization = useEnhancedStabilization, + enhancedStabilizationStrength = + _state.value.videoConfig.enhancedStabilizationStrength, + enhancedStabilizationLookahead = + _state.value.videoConfig.enhancedStabilizationLookahead, recordingPath = _state.value.videoConfig.recordingPath, recordingTreeUri = _state.value.videoConfig.recordingTreeUri, onError = { message -> @@ -6423,7 +6547,6 @@ class Camera2Controller(private val context: Context) { return state.videoConfig.stabilizationMode == VideoStabilizationMode.ENHANCED && state.captureMode == CaptureMode.VIDEO && state.videoConfig.resolution == VideoResolutionPreset.FHD_1080P && - state.videoConfig.fps == VideoFpsPreset.FPS_30 && !isCurrentCameraFrontFacing() && realtimeStabilizationCoordinator.isCurrentCameraSupported } @@ -6502,6 +6625,9 @@ class Camera2Controller(private val context: Context) { return try { val builder = device.createCaptureRequest(CameraDevice.TEMPLATE_RECORD).apply { addTarget(previewTarget) + stabilizationImageReader?.surface + ?.takeIf { shouldUseVideoEnhancedStabilization() } + ?.let(::addTarget) encoderTarget?.takeIf { includeVideoSurface }?.let(::addTarget) applyBaseCameraSettings(this, isCapture = false) } diff --git a/app/src/main/java/com/hinnka/mycamera/data/UserPreferencesRepository.kt b/app/src/main/java/com/hinnka/mycamera/data/UserPreferencesRepository.kt index f6920545..bed7fdd2 100644 --- a/app/src/main/java/com/hinnka/mycamera/data/UserPreferencesRepository.kt +++ b/app/src/main/java/com/hinnka/mycamera/data/UserPreferencesRepository.kt @@ -38,6 +38,10 @@ import com.hinnka.mycamera.raw.RawSharpeningDefaults import com.hinnka.mycamera.processor.PhotonCoreImagingTuning import com.hinnka.mycamera.processor.PhotonSensorSizeTuning import com.hinnka.mycamera.screencapture.PhantomPipCrop +import com.hinnka.mycamera.stabilization.DEFAULT_VIDEO_STABILIZATION_LOOKAHEAD +import com.hinnka.mycamera.stabilization.DEFAULT_VIDEO_STABILIZATION_STRENGTH +import com.hinnka.mycamera.stabilization.normalizeStabilizationLookahead +import com.hinnka.mycamera.stabilization.normalizeStabilizationStrength import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.map import com.hinnka.mycamera.video.CaptureMode @@ -235,6 +239,8 @@ data class UserPreferences( val videoRecordingPath: VideoRecordingPath = VideoRecordingPath.DCIM_PHOTON, val videoRecordingTreeUri: String? = null, val videoStabilizationMode: VideoStabilizationMode = VideoStabilizationMode.OIS, + val videoEnhancedStabilizationStrength: Float = DEFAULT_VIDEO_STABILIZATION_STRENGTH, + val videoEnhancedStabilizationLookahead: Int = DEFAULT_VIDEO_STABILIZATION_LOOKAHEAD, val photoPreviewStabilizationEnabled: Boolean = false, val videoTorchEnabled: Boolean = false, val videoLensLockEnabled: Boolean = false, @@ -496,6 +502,10 @@ class UserPreferencesRepository(private val context: Context) { private val VIDEO_STABILIZATION_MODE = stringPreferencesKey("video_stabilization_mode") private val VIDEO_ENHANCED_STABILIZATION_ENABLED = booleanPreferencesKey("video_enhanced_stabilization_enabled") + private val VIDEO_ENHANCED_STABILIZATION_STRENGTH = + floatPreferencesKey("video_enhanced_stabilization_strength") + private val VIDEO_ENHANCED_STABILIZATION_LOOKAHEAD = + intPreferencesKey("video_enhanced_stabilization_lookahead") private val PHOTO_PREVIEW_STABILIZATION_ENABLED = booleanPreferencesKey("photo_preview_stabilization_enabled") private val VIDEO_TORCH_ENABLED = booleanPreferencesKey("video_torch_enabled") @@ -791,11 +801,7 @@ class UserPreferencesRepository(private val context: Context) { } else { storedVideoResolution }, - videoFps = if (videoStabilizationMode == VideoStabilizationMode.ENHANCED) { - VideoFpsPreset.FPS_30 - } else { - storedVideoFps - }, + videoFps = storedVideoFps, videoAspectRatio = VideoAspectRatio.valueOf( preferences[VIDEO_ASPECT_RATIO] ?: VideoAspectRatio.RATIO_16_9.name ), @@ -809,6 +815,14 @@ class UserPreferencesRepository(private val context: Context) { videoRecordingPath = VideoRecordingPath.fromPersistedName(preferences[VIDEO_RECORDING_PATH]), videoRecordingTreeUri = preferences[VIDEO_RECORDING_TREE_URI]?.takeIf { it.isNotBlank() }, videoStabilizationMode = videoStabilizationMode, + videoEnhancedStabilizationStrength = normalizeStabilizationStrength( + preferences[VIDEO_ENHANCED_STABILIZATION_STRENGTH] + ?: DEFAULT_VIDEO_STABILIZATION_STRENGTH + ), + videoEnhancedStabilizationLookahead = normalizeStabilizationLookahead( + preferences[VIDEO_ENHANCED_STABILIZATION_LOOKAHEAD] + ?: DEFAULT_VIDEO_STABILIZATION_LOOKAHEAD + ), photoPreviewStabilizationEnabled = preferences[PHOTO_PREVIEW_STABILIZATION_ENABLED] ?: false, videoTorchEnabled = preferences[VIDEO_TORCH_ENABLED] ?: false, @@ -1599,6 +1613,13 @@ class UserPreferencesRepository(private val context: Context) { } } + suspend fun saveVideoStabilizationMode(mode: VideoStabilizationMode) { + context.dataStore.edit { preferences -> + preferences[VIDEO_STABILIZATION_MODE] = mode.name + preferences.remove(VIDEO_ENHANCED_STABILIZATION_ENABLED) + } + } + suspend fun saveVideoStabilizationConfig( mode: VideoStabilizationMode, resolution: VideoResolutionPreset, @@ -1612,6 +1633,20 @@ class UserPreferencesRepository(private val context: Context) { } } + suspend fun saveVideoEnhancedStabilizationStrength(strength: Float) { + context.dataStore.edit { preferences -> + preferences[VIDEO_ENHANCED_STABILIZATION_STRENGTH] = + normalizeStabilizationStrength(strength) + } + } + + suspend fun saveVideoEnhancedStabilizationLookahead(lookahead: Int) { + context.dataStore.edit { preferences -> + preferences[VIDEO_ENHANCED_STABILIZATION_LOOKAHEAD] = + normalizeStabilizationLookahead(lookahead) + } + } + suspend fun savePhotoPreviewStabilizationEnabled(enabled: Boolean) { context.dataStore.edit { preferences -> preferences[PHOTO_PREVIEW_STABILIZATION_ENABLED] = enabled diff --git a/app/src/main/java/com/hinnka/mycamera/lut/ColorPassProgram.kt b/app/src/main/java/com/hinnka/mycamera/lut/ColorPassProgram.kt index 1f2dec49..1cb6ee46 100644 --- a/app/src/main/java/com/hinnka/mycamera/lut/ColorPassProgram.kt +++ b/app/src/main/java/com/hinnka/mycamera/lut/ColorPassProgram.kt @@ -54,10 +54,7 @@ internal data class ColorPassLocations( val uLchChromaAdjustmentsLocation: Int, val uLchLightnessAdjustmentsLocation: Int, val uPrimaryCalibrationMatrixLocation: Int, - val uSTMatrixFragLocation: Int, val uCropRectLocation: Int, - val uStabilizationEnabledLocation: Int, - val uStabilizationRowsLocation: Int, val uTexelSizeLocation: Int, val uCurveTextureLocation: Int, val uCurveEnabledLocation: Int, @@ -161,16 +158,7 @@ internal class PreviewColorProgramCache { uLchChromaAdjustmentsLocation = GLES30.glGetUniformLocation(program, "uLchChromaAdjustments"), uLchLightnessAdjustmentsLocation = GLES30.glGetUniformLocation(program, "uLchLightnessAdjustments"), uPrimaryCalibrationMatrixLocation = GLES30.glGetUniformLocation(program, "uPrimaryCalibrationMatrix"), - uSTMatrixFragLocation = GLES30.glGetUniformLocation(program, "uSTMatrix"), uCropRectLocation = GLES30.glGetUniformLocation(program, "uCropRect"), - uStabilizationEnabledLocation = GLES30.glGetUniformLocation( - program, - "uStabilizationEnabled", - ), - uStabilizationRowsLocation = GLES30.glGetUniformLocation( - program, - "uStabilizationRows[0]", - ), uTexelSizeLocation = GLES30.glGetUniformLocation(program, "uTexelSize"), uCurveTextureLocation = GLES30.glGetUniformLocation(program, "uCurveTexture"), uCurveEnabledLocation = GLES30.glGetUniformLocation(program, "uCurveEnabled"), diff --git a/app/src/main/java/com/hinnka/mycamera/lut/LutRenderer.kt b/app/src/main/java/com/hinnka/mycamera/lut/LutRenderer.kt index af0faca0..83a68622 100644 --- a/app/src/main/java/com/hinnka/mycamera/lut/LutRenderer.kt +++ b/app/src/main/java/com/hinnka/mycamera/lut/LutRenderer.kt @@ -14,10 +14,11 @@ import com.hinnka.mycamera.preview.EyeFocusProcessingTiming import com.hinnka.mycamera.raw.ColorSpace import com.hinnka.mycamera.screencapture.PhantomPipCrop import com.hinnka.mycamera.camera.MeteringMode -import com.hinnka.mycamera.stabilization.AlgorithmicStabilizationTransform +import com.hinnka.mycamera.stabilization.DEFAULT_VIDEO_STABILIZATION_LOOKAHEAD import com.hinnka.mycamera.stabilization.RealtimeStabilizationCoordinator -import com.hinnka.mycamera.stabilization.STABILIZATION_ROW_COUNT import com.hinnka.mycamera.stabilization.StabilizationUseCase +import com.hinnka.mycamera.stabilization.normalizeStabilizationLookahead +import com.hinnka.mycamera.stabilization.normalizeStabilizationStrength import com.hinnka.mycamera.utils.PLog import com.hinnka.mycamera.video.VideoLogProfile import java.nio.ByteBuffer @@ -68,6 +69,8 @@ class LutRenderer(context: Context) : GLSurfaceView.Renderer { } private val colorProgramCache = PreviewColorProgramCache() + private val mgcEisHardwareBufferRenderer = MgcEisHardwareBufferRenderer(TAG) + private val mgcEisYuvRenderer = MgcEisYuvRenderer(TAG) private data class PreviewCaptureRequest( val width: Int, @@ -228,6 +231,7 @@ class LutRenderer(context: Context) : GLSurfaceView.Renderer { // SurfaceTexture 变换矩阵 private val stMatrix = FloatArray(16).apply { Matrix.setIdentityM(this, 0) } + private val mgcEisPresentationTransform = MgcEisPresentationTransform() // MVP 变换矩阵(用于 center crop) private val mvpMatrix = FloatArray(16) @@ -240,8 +244,13 @@ class LutRenderer(context: Context) : GLSurfaceView.Renderer { private var stabilizationSession: RealtimeStabilizationCoordinator.Session? = null @Volatile private var stabilizationSessionStarted = false - private var photoPreviewStabilizationEnabled = false - private var currentStabilizationTransform: AlgorithmicStabilizationTransform? = null + private var previewStabilizationUseCase: StabilizationUseCase? = null + private var previewStabilizationStrength = 0f + private var currentCameraTextureSource = PreviewColorTextureSource.EXTERNAL_OES + private var currentCameraTextureTarget = GLES11Ext.GL_TEXTURE_EXTERNAL_OES + private var currentCameraTextureId = 0 + private var currentCameraTextureMatrix: FloatArray = stMatrix + private var currentFrameTimestampNs = 0L // 标记 Surface 是否已创建(GL 上下文是否可用) private var surfaceReady = false @@ -551,7 +560,9 @@ class LutRenderer(context: Context) : GLSurfaceView.Renderer { setDefaultBufferSize(previewWidth, previewHeight) setOnFrameAvailableListener { frameAvailable.set(true) - onRequestRender?.invoke() + if (previewStabilizationUseCase == null) { + onRequestRender?.invoke() + } } } @@ -584,7 +595,14 @@ class LutRenderer(context: Context) : GLSurfaceView.Renderer { */ private fun resetGlResourceState() { colorProgramCache.reset() + mgcEisHardwareBufferRenderer.resetAfterContextLoss() + mgcEisYuvRenderer.resetAfterContextLoss() cameraTextureId = 0 + currentCameraTextureId = 0 + currentCameraTextureSource = PreviewColorTextureSource.EXTERNAL_OES + currentCameraTextureTarget = GLES11Ext.GL_TEXTURE_EXTERNAL_OES + currentCameraTextureMatrix = stMatrix + currentFrameTimestampNs = 0L lutTextureId = 0 baselineLutTextureId = 0 basicToneTextures.reset() @@ -829,7 +847,6 @@ class LutRenderer(context: Context) : GLSurfaceView.Renderer { curveEnabled: Boolean, enableVideoLog: Boolean, treatSourceAsHlgInput: Boolean, - stabilizationTransform: AlgorithmicStabilizationTransform? = null, ) { GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, targetFboId) GLES30.glViewport(0, 0, width, height) @@ -849,7 +866,6 @@ class LutRenderer(context: Context) : GLSurfaceView.Renderer { GLES30.glUniformMatrix4fv(locations.uMVPMatrixLocation, 1, false, targetMvpMatrix, 0) GLES30.glUniformMatrix4fv(locations.uSTMatrixLocation, 1, false, sourceStMatrix, 0) - GLES30.glUniformMatrix4fv(locations.uSTMatrixFragLocation, 1, false, sourceStMatrix, 0) GLES30.glUniform4f( locations.uCropRectLocation, sourceCropRect[0], @@ -857,21 +873,6 @@ class LutRenderer(context: Context) : GLSurfaceView.Renderer { sourceCropRect[2], sourceCropRect[3] ) - val stabilizationEnabled = stabilizationTransform != null && - stabilizationTransform.rowHomographies.size == STABILIZATION_ROW_COUNT * 9 - GLES30.glUniform1i( - locations.uStabilizationEnabledLocation, - if (stabilizationEnabled) 1 else 0, - ) - if (stabilizationEnabled) { - GLES30.glUniformMatrix3fv( - locations.uStabilizationRowsLocation, - STABILIZATION_ROW_COUNT, - false, - stabilizationTransform.rowHomographies, - 0, - ) - } GLES30.glUniform1f(locations.uLutSizeLocation, lutSize) GLES30.glUniform1f(locations.uLutIntensityLocation, params.lutIntensity) GLES30.glUniform1i(locations.uLutEnabledLocation, if (lutEnabled && lutTextureId != 0) 1 else 0) @@ -910,7 +911,7 @@ class LutRenderer(context: Context) : GLSurfaceView.Renderer { GLES30.glUniform1f(locations.uFilmGrainLocation, params.filmGrain) GLES30.glUniform1f( locations.uFilmGrainSeedLocation, - FilmGrainShaders.frameSeed(surfaceTexture?.timestamp ?: 0L) + FilmGrainShaders.frameSeed(currentFrameTimestampNs) ) GLES30.glUniform1f( locations.uFilmGrainPixelScaleLocation, @@ -976,15 +977,31 @@ class LutRenderer(context: Context) : GLSurfaceView.Renderer { GLES30.glBindBuffer(GLES30.GL_ARRAY_BUFFER, vertexBufferId) GLES30.glEnableVertexAttribArray(locations.aPositionLocation) - GLES30.glVertexAttribPointer(locations.aPositionLocation, POSITION_COMPONENT_COUNT, GLES30.GL_FLOAT, false, 0, 0) - + GLES30.glVertexAttribPointer( + locations.aPositionLocation, + POSITION_COMPONENT_COUNT, + GLES30.GL_FLOAT, + false, + 0, + 0, + ) GLES30.glBindBuffer(GLES30.GL_ARRAY_BUFFER, texCoordBufferId) GLES30.glEnableVertexAttribArray(locations.aTexCoordLocation) - GLES30.glVertexAttribPointer(locations.aTexCoordLocation, TEXTURE_COORD_COMPONENT_COUNT, GLES30.GL_FLOAT, false, 0, 0) - + GLES30.glVertexAttribPointer( + locations.aTexCoordLocation, + TEXTURE_COORD_COMPONENT_COUNT, + GLES30.GL_FLOAT, + false, + 0, + 0, + ) GLES30.glBindBuffer(GLES30.GL_ELEMENT_ARRAY_BUFFER, indexBufferId) - GLES30.glDrawElements(GLES30.GL_TRIANGLES, Shaders.DRAW_ORDER.size, GLES30.GL_UNSIGNED_SHORT, 0) - + GLES30.glDrawElements( + GLES30.GL_TRIANGLES, + Shaders.DRAW_ORDER.size, + GLES30.GL_UNSIGNED_SHORT, + 0, + ) GLES30.glDisableVertexAttribArray(locations.aPositionLocation) GLES30.glDisableVertexAttribArray(locations.aTexCoordLocation) GLES30.glBindBuffer(GLES30.GL_ARRAY_BUFFER, 0) @@ -1012,23 +1029,14 @@ class LutRenderer(context: Context) : GLSurfaceView.Renderer { if (renderingPaused) return if (viewportWidth <= 0 || viewportHeight <= 0) return - // 更新 SurfaceTexture - var cameraFrameUpdated = false - if (frameAvailable.getAndSet(false)) { - try { - surfaceTexture?.updateTexImage() - surfaceTexture?.getTransformMatrix(stMatrix) - cameraFrameUpdated = true - } catch (e: RuntimeException) { - PLog.e( - TAG, - "updateTexImage failed, surfaceReady=$surfaceReady, cameraTextureId=$cameraTextureId", - e - ) - } + val delayedStabilizationEnabled = previewStabilizationUseCase != null + if (delayedStabilizationEnabled && !stabilizationSessionStarted) { + stabilizationSessionStarted = stabilizationSession?.start() == true } + val oesFrameUpdated = frameAvailable.getAndSet(false) && acquireLatestCameraFrame() + var cameraFrameUpdated = oesFrameUpdated - if (cameraFrameUpdated && photoPreviewStabilizationEnabled) { + if (delayedStabilizationEnabled) { val session = stabilizationSession if (stabilizationSessionStarted && stabilizationCoordinator?.isCurrentCameraSupported == false @@ -1039,20 +1047,29 @@ class LutRenderer(context: Context) : GLSurfaceView.Renderer { if (!stabilizationSessionStarted) { stabilizationSessionStarted = session?.start() == true } - currentStabilizationTransform = if (stabilizationSessionStarted) { - surfaceTexture?.timestamp?.let { timestampNs -> - session?.transformForFrame( - timestampNs = timestampNs, - baseCropRect = cropRect, - textureAxesSwapped = isTextureTransformAxesSwapped(stMatrix), - displayRotationDegrees = deviceRotation, - ) + if (stabilizationSessionStarted) { + val completedFrame = session?.dequeueFrame() + if (completedFrame != null) { + renderMgcEisFrame(completedFrame)?.let { rendered -> + currentCameraTextureSource = PreviewColorTextureSource.TEXTURE_2D + currentCameraTextureTarget = GLES30.GL_TEXTURE_2D + currentCameraTextureId = rendered.textureId + currentCameraTextureMatrix = mgcEisPresentationTransform.matrix + currentFrameTimestampNs = rendered.timestampNs + cameraFrameUpdated = true + } + } + if ((session?.pendingResultCount() ?: 0) > 0) { + onRequestRender?.invoke() } - } else { - null } - } else if (!photoPreviewStabilizationEnabled) { - currentStabilizationTransform = null + if (currentCameraTextureSource != PreviewColorTextureSource.TEXTURE_2D) { + GLES30.glClearColor(0f, 0f, 0f, 1f) + GLES30.glClear(GLES30.GL_COLOR_BUFFER_BIT) + return + } + } else if (cameraFrameUpdated) { + useCurrentOesFrame() } val liveRecorder = livePhotoRecorder @@ -1110,7 +1127,9 @@ class LutRenderer(context: Context) : GLSurfaceView.Renderer { params = creativeParams, enableVideoLog = false, treatSourceAsHlgInput = false, - ) ?: return + ) ?: run { + return + } drawColorPass( locations = secondPassLocations, targetFboId = stackFboId, @@ -1165,7 +1184,7 @@ class LutRenderer(context: Context) : GLSurfaceView.Renderer { width = currentWidth, height = currentHeight, amount = filmGrain, - frameSeed = FilmGrainShaders.frameSeed(surfaceTexture?.timestamp ?: 0L), + frameSeed = FilmGrainShaders.frameSeed(currentFrameTimestampNs), drawQuad = ::drawSimpleQuad, ) if (grainOutput != null) { @@ -1196,7 +1215,7 @@ class LutRenderer(context: Context) : GLSurfaceView.Renderer { transformMatrix = rotationMatrix, width = targetWidth, height = targetHeight, - timestampNs = surfaceTexture?.timestamp ?: 0L, + timestampNs = currentFrameTimestampNs, lutConfig = currentLutConfig, params = getCurrentRecipeParams(), sharedContext = EGL14.eglGetCurrentContext(), @@ -1283,6 +1302,34 @@ class LutRenderer(context: Context) : GLSurfaceView.Renderer { } } + private fun useCurrentOesFrame() { + currentCameraTextureSource = PreviewColorTextureSource.EXTERNAL_OES + currentCameraTextureTarget = GLES11Ext.GL_TEXTURE_EXTERNAL_OES + currentCameraTextureId = cameraTextureId + currentCameraTextureMatrix = stMatrix + currentFrameTimestampNs = surfaceTexture?.timestamp ?: 0L + } + + private fun acquireLatestCameraFrame(): Boolean { + return try { + surfaceTexture?.updateTexImage() + surfaceTexture?.getTransformMatrix(stMatrix) + if (previewStabilizationUseCase != null && + !mgcEisPresentationTransform.captureFromOes(stMatrix) + ) { + PLog.w(TAG, "MGC cannot derive a cardinal presentation orientation yet") + } + surfaceTexture != null + } catch (error: RuntimeException) { + PLog.e( + TAG, + "updateTexImage failed, surfaceReady=$surfaceReady, cameraTextureId=$cameraTextureId", + error, + ) + false + } + } + /** * 将 FBO 纹理绘制到屏幕 (Copy Shader) */ @@ -1379,23 +1426,24 @@ class LutRenderer(context: Context) : GLSurfaceView.Renderer { false } val enableVideoLog = true + val currentSourceIsHlg = isHlgInput && previewStabilizationUseCase == null val locations = getColorPassLocations( - textureSource = PreviewColorTextureSource.EXTERNAL_OES, + textureSource = currentCameraTextureSource, lutConfig = layerLutConfig, lutEnabled = layerLutEnabled, params = layerParams, enableVideoLog = enableVideoLog, - treatSourceAsHlgInput = isHlgInput, + treatSourceAsHlgInput = currentSourceIsHlg, ) ?: return drawColorPass( locations = locations, targetFboId = fboId, width = width, height = height, - sourceTextureTarget = GLES11Ext.GL_TEXTURE_EXTERNAL_OES, - sourceTextureId = cameraTextureId, - sourceStMatrix = stMatrix, - sourceCropRect = currentStabilizationTransform?.cropRect ?: cropRect, + sourceTextureTarget = currentCameraTextureTarget, + sourceTextureId = currentCameraTextureId, + sourceStMatrix = currentCameraTextureMatrix, + sourceCropRect = cropRect, targetMvpMatrix = targetMvpMatrix, lutConfig = layerLutConfig, lutTextureId = layerLutTextureId, @@ -1405,8 +1453,7 @@ class LutRenderer(context: Context) : GLSurfaceView.Renderer { curveTextureId = layerCurveTextureId, curveEnabled = layerCurveEnabled, enableVideoLog = enableVideoLog, - treatSourceAsHlgInput = isHlgInput, - stabilizationTransform = currentStabilizationTransform, + treatSourceAsHlgInput = currentSourceIsHlg, ) // 测光和直方图(按需) @@ -2566,9 +2613,15 @@ class LutRenderer(context: Context) : GLSurfaceView.Renderer { * 设置预览尺寸 */ fun setPreviewSize(width: Int, height: Int) { + val sizeChanged = previewWidth != width || previewHeight != height previewWidth = width previewHeight = height surfaceTexture?.setDefaultBufferSize(width, height) + if (sizeChanged && previewStabilizationUseCase != null) { + mgcEisHardwareBufferRenderer.release() + mgcEisYuvRenderer.release() + recreatePreviewStabilizationSession() + } // 更新 MVP 矩阵以处理 center crop updateMVPMatrix() updateCaptureSize() @@ -2576,21 +2629,72 @@ class LutRenderer(context: Context) : GLSurfaceView.Renderer { fun setStabilizationCoordinator(coordinator: RealtimeStabilizationCoordinator?) { if (stabilizationCoordinator === coordinator) return - stabilizationSession?.stop() stabilizationCoordinator = coordinator - stabilizationSession = coordinator?.createSession(StabilizationUseCase.PHOTO_PREVIEW) - stabilizationSessionStarted = false - currentStabilizationTransform = null + recreatePreviewStabilizationSession() } - fun setPhotoPreviewStabilizationEnabled(enabled: Boolean) { - if (photoPreviewStabilizationEnabled == enabled) return - photoPreviewStabilizationEnabled = enabled - PLog.i(TAG, "Photo preview stabilization enabled=$enabled") - if (!enabled) { - stabilizationSession?.stop() - stabilizationSessionStarted = false - currentStabilizationTransform = null + private var previewStabilizationLookahead = DEFAULT_VIDEO_STABILIZATION_LOOKAHEAD + + fun setPreviewStabilization( + useCase: StabilizationUseCase?, + strength: Float, + lookaheadFrames: Int = DEFAULT_VIDEO_STABILIZATION_LOOKAHEAD, + ) { + val normalizedStrength = normalizeStabilizationStrength(strength) + val normalizedLookahead = normalizeStabilizationLookahead(lookaheadFrames) + if (previewStabilizationUseCase == useCase && + abs(previewStabilizationStrength - normalizedStrength) <= 0.0001f && + previewStabilizationLookahead == normalizedLookahead + ) { + return + } + previewStabilizationUseCase = useCase + previewStabilizationStrength = normalizedStrength + previewStabilizationLookahead = normalizedLookahead + PLog.i( + TAG, + "Preview stabilization useCase=${useCase?.name ?: "OFF"}, " + + "strength=$normalizedStrength, lookahead=$normalizedLookahead" + ) + recreatePreviewStabilizationSession() + } + + private fun recreatePreviewStabilizationSession() { + stabilizationSession?.stop() + mgcEisPresentationTransform.reset() + stabilizationSession = previewStabilizationUseCase?.let { useCase -> + stabilizationCoordinator?.createSession( + useCase = useCase, + strength = previewStabilizationStrength, + frameWidth = previewWidth, + frameHeight = previewHeight, + lookaheadFrames = previewStabilizationLookahead, + onFrameAvailable = { onRequestRender?.invoke() }, + ) + } + stabilizationSessionStarted = stabilizationSession?.start() == true + currentCameraTextureSource = PreviewColorTextureSource.EXTERNAL_OES + currentCameraTextureTarget = GLES11Ext.GL_TEXTURE_EXTERNAL_OES + currentCameraTextureId = cameraTextureId + currentCameraTextureMatrix = stMatrix + currentFrameTimestampNs = 0L + } + + /** + * Uses MGC's HardwareBuffer/EGLImage renderer whenever the camera buffer and current EGL + * context support it. The CPU YUV implementation is retained only for devices without that + * platform import path. + */ + private fun renderMgcEisFrame( + frame: com.hinnka.mycamera.stabilization.StabilizationFrame, + ): MgcEisHardwareBufferRenderer.Frame? { + val hardwareRendered = mgcEisHardwareBufferRenderer.render(frame) + if (hardwareRendered != null) { + frame.image.close() + return hardwareRendered + } + return mgcEisYuvRenderer.render(frame)?.let { rendered -> + MgcEisHardwareBufferRenderer.Frame(rendered.timestampNs, rendered.textureId) } } @@ -3137,7 +3241,7 @@ class LutRenderer(context: Context) : GLSurfaceView.Renderer { if (paused) { stabilizationSession?.stop() stabilizationSessionStarted = false - currentStabilizationTransform = null + currentFrameTimestampNs = 0L } } @@ -3287,7 +3391,7 @@ class LutRenderer(context: Context) : GLSurfaceView.Renderer { stabilizationSession = null stabilizationCoordinator = null stabilizationSessionStarted = false - currentStabilizationTransform = null + currentFrameTimestampNs = 0L try { meteringExecutor.shutdown() } catch (e: Exception) { @@ -3411,6 +3515,8 @@ class LutRenderer(context: Context) : GLSurfaceView.Renderer { stackTextureId = 0 } basicToneTextures.release() + mgcEisHardwareBufferRenderer.release() + mgcEisYuvRenderer.release() // 删除程序 colorProgramCache.release() GlUtils.deleteProgram(passthroughProgramId) diff --git a/app/src/main/java/com/hinnka/mycamera/lut/MgcEisHardwareBufferRenderer.kt b/app/src/main/java/com/hinnka/mycamera/lut/MgcEisHardwareBufferRenderer.kt new file mode 100644 index 00000000..d451d21b --- /dev/null +++ b/app/src/main/java/com/hinnka/mycamera/lut/MgcEisHardwareBufferRenderer.kt @@ -0,0 +1,279 @@ +package com.hinnka.mycamera.lut + +import android.media.Image +import android.opengl.EGL14 +import android.opengl.EGL15 +import android.opengl.EGLSync +import android.opengl.GLES11Ext +import android.opengl.GLES30 +import android.opengl.GLES31 +import com.hinnka.mycamera.stabilization.MgcEisNativeBridge +import com.hinnka.mycamera.stabilization.STABILIZATION_ROW_COUNT +import com.hinnka.mycamera.stabilization.StabilizationFrame +import com.hinnka.mycamera.utils.PLog + +/** + * MGC's production image path: Camera2 HardwareBuffer -> EGLImage -> external texture -> mesh. + * + * This mirrors the original jxg renderer. The caller retains ownership of [StabilizationFrame]'s + * Image and closes it after a successful draw; a null result leaves it available for the explicit + * CPU YUV fallback on devices that cannot import the buffer into EGL. + */ +internal class MgcEisHardwareBufferRenderer(private val tag: String) { + data class Frame(val timestampNs: Long, val textureId: Int) + + private val mesh = MgcEisMesh() + // Native output matrices pass through convertPixelHomographyToClip then + // applyCropZoomToClipHomography(kOutputCropZoom), where: + // kLookaheadCropMargin = 0.05 + // kOutputCropZoom = 1.0 / (1.0 - 2.0 * 0.05) ≈ 1.1111 + // applyCropZoomToClipHomography divides the W row (h20, h21, h22) by zoom. + // A Dropped frame must use the same crop so that the viewport does not jump + // between 1.0x and 1.111x on every stabilization gap. + private val droppedFrameHomographies = FloatArray(STABILIZATION_ROW_COUNT * 9).also { values -> + val h22 = 1.0f - 2.0f * 0.05f // = 1.0f / kOutputCropZoom = 0.9f + repeat(STABILIZATION_ROW_COUNT) { row -> + val offset = row * 9 + values[offset] = 1f // h00 + values[offset + 4] = 1f // h11 + values[offset + 8] = h22 // h22: W-row crop zoom + } + } + + private var programId = 0 + private var positionLocation = -1 + private var textureCoordinateLocation = -1 + private var sourceSamplerLocation = -1 + private var sourceTextureId = 0 + private var outputTextureId = 0 + private var outputFramebufferId = 0 + private var width = 0 + private var height = 0 + private var loggedImportFailure = false + private var loggedZeroCopy = false + + /** + * Attempts the zero-copy path without closing the source image. The image must remain open + * until this function returns because the EGLImage is created from its HardwareBuffer. + */ + fun render(frame: StabilizationFrame): Frame? { + val width = frame.image.width + val height = frame.image.height + if (width <= 0 || height <= 0) return null + val source = frame.image.image + val hardwareBuffer = try { + source.hardwareBuffer + } catch (error: IllegalStateException) { + PLog.w(tag, "MGC cannot access HardwareBuffer ts=${frame.timestampNs}: ${error.message}") + return null + } ?: return null + if (!ensure(width, height)) return null + + val imageHandle = MgcEisNativeBridge.createHardwareBufferImage(hardwareBuffer) + if (imageHandle == 0L) { + if (!loggedImportFailure) { + loggedImportFailure = true + PLog.w(tag, "MGC EGLImage import unavailable; using CPU YUV fallback") + } + return null + } + + return try { + if (!MgcEisNativeBridge.bindHardwareBufferImage(imageHandle, sourceTextureId)) { + PLog.w(tag, "MGC EGLImage bind failed ts=${frame.timestampNs}") + return null + } + GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, outputFramebufferId) + GLES30.glViewport(0, 0, source.width, source.height) + GLES30.glClearColor(0f, 0f, 0f, 1f) + GLES30.glClear(GLES30.GL_COLOR_BUFFER_BIT) + GLES30.glUseProgram(programId) + GLES30.glActiveTexture(GLES30.GL_TEXTURE0) + GLES30.glBindTexture(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, sourceTextureId) + GLES30.glUniform1i(sourceSamplerLocation, 0) + mesh.draw( + positionLocation = positionLocation, + textureCoordinateLocation = textureCoordinateLocation, + rowHomographies = frame.transform?.rowHomographies ?: droppedFrameHomographies, + ) + // The camera owns this HardwareBuffer and may recycle it as soon as Image.close() + // returns. A GL draw only enqueues sampling work, so a memory barrier alone cannot + // protect that lifetime. MGC's jwn/jxg renderers insert and wait on an EGL fence at + // this exact hand-off before releasing their input EGLImage/HardwareBuffer. + awaitSourceSampling() + GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, 0) + GLES31.glMemoryBarrier( + GLES31.GL_FRAMEBUFFER_BARRIER_BIT or GLES31.GL_TEXTURE_FETCH_BARRIER_BIT, + ) + GLES30.glBindTexture(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, 0) + GLES30.glActiveTexture(GLES30.GL_TEXTURE0) + if (!loggedZeroCopy) { + loggedZeroCopy = true + PLog.i(tag, "MGC HardwareBuffer EGLImage renderer active") + } + Frame(frame.timestampNs, outputTextureId) + } catch (error: RuntimeException) { + PLog.w(tag, "MGC EGLImage draw failed ts=${frame.timestampNs}: ${error.message}") + null + } finally { + MgcEisNativeBridge.destroyHardwareBufferImage(imageHandle) + } + } + + /** + * Completes the submitted external-texture sampling before its Camera2 buffer is returned to + * ImageReader. The normal path is the same EGL fence hand-off used by MGC. If this context + * cannot create a fence, glFinish is the only safe fallback: returning the buffer early would + * let a later camera frame overwrite pixels while this draw still reads them. + */ + private fun awaitSourceSampling() { + val display = EGL14.eglGetCurrentDisplay() + if (display == EGL14.EGL_NO_DISPLAY) { + GLES30.glFinish() + return + } + val fence: EGLSync = EGL15.eglCreateSync( + display, + EGL15.EGL_SYNC_FENCE, + longArrayOf(EGL14.EGL_NONE.toLong()), + 0, + ) + if (fence == EGL15.EGL_NO_SYNC) { + GLES30.glFinish() + return + } + try { + val waitResult = EGL15.eglClientWaitSync( + display, + fence, + EGL15.EGL_SYNC_FLUSH_COMMANDS_BIT, + EGL15.EGL_FOREVER, + ) + if (waitResult != EGL15.EGL_CONDITION_SATISFIED) { + PLog.w(tag, "MGC EGL fence wait failed result=$waitResult; forcing GL completion") + GLES30.glFinish() + } + } finally { + EGL15.eglDestroySync(display, fence) + } + } + + fun resetAfterContextLoss() { + programId = 0 + positionLocation = -1 + textureCoordinateLocation = -1 + sourceSamplerLocation = -1 + sourceTextureId = 0 + outputTextureId = 0 + outputFramebufferId = 0 + width = 0 + height = 0 + mesh.resetAfterContextLoss() + } + + fun release() { + val textures = intArrayOf(sourceTextureId, outputTextureId) + .filter { it != 0 } + .toIntArray() + if (textures.isNotEmpty()) GLES30.glDeleteTextures(textures.size, textures, 0) + if (outputFramebufferId != 0) { + GLES30.glDeleteFramebuffers(1, intArrayOf(outputFramebufferId), 0) + } + if (programId != 0) GLES30.glDeleteProgram(programId) + mesh.release() + resetAfterContextLoss() + } + + private fun ensure(requestedWidth: Int, requestedHeight: Int): Boolean { + if (programId != 0 && width == requestedWidth && height == requestedHeight) return true + release() + val vertexShader = GlUtils.compileShader(GLES30.GL_VERTEX_SHADER, VERTEX_SHADER) + val fragmentShader = GlUtils.compileShader(GLES30.GL_FRAGMENT_SHADER, FRAGMENT_SHADER) + programId = GlUtils.linkProgram(vertexShader, fragmentShader) + GLES30.glDeleteShader(vertexShader) + GLES30.glDeleteShader(fragmentShader) + if (programId == 0) return false + positionLocation = GLES30.glGetAttribLocation(programId, "aPosition") + textureCoordinateLocation = GLES30.glGetAttribLocation(programId, "aTexCoord") + sourceSamplerLocation = GLES30.glGetUniformLocation(programId, "uCameraTexture") + mesh.initialize() + sourceTextureId = GlUtils.createOESTexture() + outputTextureId = createTexture(requestedWidth, requestedHeight) + if (sourceTextureId == 0 || outputTextureId == 0 || + !createOutputTarget(outputTextureId) + ) { + release() + return false + } + width = requestedWidth + height = requestedHeight + return true + } + + private fun createTexture(textureWidth: Int, textureHeight: Int): Int { + val ids = IntArray(1) + GLES30.glGenTextures(1, ids, 0) + GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, ids[0]) + GLES30.glTexParameteri(GLES30.GL_TEXTURE_2D, GLES30.GL_TEXTURE_MIN_FILTER, GLES30.GL_LINEAR) + GLES30.glTexParameteri(GLES30.GL_TEXTURE_2D, GLES30.GL_TEXTURE_MAG_FILTER, GLES30.GL_LINEAR) + GLES30.glTexParameteri(GLES30.GL_TEXTURE_2D, GLES30.GL_TEXTURE_WRAP_S, GLES30.GL_CLAMP_TO_EDGE) + GLES30.glTexParameteri(GLES30.GL_TEXTURE_2D, GLES30.GL_TEXTURE_WRAP_T, GLES30.GL_CLAMP_TO_EDGE) + GLES30.glTexImage2D( + GLES30.GL_TEXTURE_2D, + 0, + GLES30.GL_RGBA8, + textureWidth, + textureHeight, + 0, + GLES30.GL_RGBA, + GLES30.GL_UNSIGNED_BYTE, + null, + ) + GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, 0) + return ids[0] + } + + private fun createOutputTarget(textureId: Int): Boolean { + val framebuffers = IntArray(1) + GLES30.glGenFramebuffers(1, framebuffers, 0) + outputFramebufferId = framebuffers[0] + GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, outputFramebufferId) + GLES30.glFramebufferTexture2D( + GLES30.GL_FRAMEBUFFER, + GLES30.GL_COLOR_ATTACHMENT0, + GLES30.GL_TEXTURE_2D, + textureId, + 0, + ) + val complete = GLES30.glCheckFramebufferStatus(GLES30.GL_FRAMEBUFFER) == + GLES30.GL_FRAMEBUFFER_COMPLETE + GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, 0) + if (!complete) PLog.e(tag, "Cannot allocate MGC HardwareBuffer output ${width}x$height") + return complete + } + + private companion object { + val VERTEX_SHADER = """ + #version 300 es + in vec4 aPosition; + in vec2 aTexCoord; + out vec2 vTexCoord; + void main() { + gl_Position = aPosition; + vTexCoord = aTexCoord; + } + """.trimIndent() + + val FRAGMENT_SHADER = """ + #version 300 es + #extension GL_OES_EGL_image_external_essl3 : require + precision highp float; + uniform samplerExternalOES uCameraTexture; + in vec2 vTexCoord; + out vec4 fragColor; + void main() { + fragColor = texture(uCameraTexture, vTexCoord); + } + """.trimIndent() + } +} diff --git a/app/src/main/java/com/hinnka/mycamera/lut/MgcEisMesh.kt b/app/src/main/java/com/hinnka/mycamera/lut/MgcEisMesh.kt new file mode 100644 index 00000000..49f7f2b6 --- /dev/null +++ b/app/src/main/java/com/hinnka/mycamera/lut/MgcEisMesh.kt @@ -0,0 +1,179 @@ +package com.hinnka.mycamera.lut + +import android.opengl.GLES30 +import com.hinnka.mycamera.stabilization.STABILIZATION_ROW_COUNT +import java.nio.ByteBuffer +import java.nio.ByteOrder + +/** Exact CPU-side strip geometry built by MGC's iha class. */ +internal class MgcEisMesh { + companion object { + private const val POSITION_COMPONENT_COUNT = 4 + private const val TEX_COORD_COMPONENT_COUNT = 2 + private const val VERTEX_COUNT = (STABILIZATION_ROW_COUNT + 1) * 2 + const val INDEX_COUNT = STABILIZATION_ROW_COUNT * 6 + + internal val textureCoordinates: FloatArray = buildTextureCoordinates() + internal val indices: ShortArray = ShortArray(INDEX_COUNT).also { output -> + for (triangle in 0 until STABILIZATION_ROW_COUNT * 2) { + for (corner in 0 until 3) { + output[triangle * 3 + corner] = (triangle + corner).toShort() + } + } + } + + internal fun warpedPositions(rowHomographies: FloatArray): FloatArray { + require(rowHomographies.size == STABILIZATION_ROW_COUNT * 9) + val output = FloatArray(VERTEX_COUNT * POSITION_COMPONENT_COUNT) + for (boundary in 0..STABILIZATION_ROW_COUNT) { + val matrixIndex = if (boundary == 0) 0 else boundary - 1 + val matrixOffset = matrixIndex * 9 + val y = 1f - 2f * boundary.toFloat() / STABILIZATION_ROW_COUNT.toFloat() + for (side in 0..1) { + val x = if (side == 0) -1f else 1f + val outputOffset = (boundary * 2 + side) * POSITION_COMPONENT_COUNT + output[outputOffset] = + x * rowHomographies[matrixOffset] + + y * rowHomographies[matrixOffset + 1] + + rowHomographies[matrixOffset + 2] + output[outputOffset + 1] = + x * rowHomographies[matrixOffset + 3] + + y * rowHomographies[matrixOffset + 4] + + rowHomographies[matrixOffset + 5] + output[outputOffset + 2] = 0f + output[outputOffset + 3] = + x * rowHomographies[matrixOffset + 6] + + y * rowHomographies[matrixOffset + 7] + + rowHomographies[matrixOffset + 8] + } + } + return output + } + + private fun buildTextureCoordinates(): FloatArray { + val output = FloatArray(VERTEX_COUNT * TEX_COORD_COMPONENT_COUNT) + for (boundary in 0..STABILIZATION_ROW_COUNT) { + val y = boundary.toFloat() / STABILIZATION_ROW_COUNT.toFloat() + val offset = boundary * 4 + output[offset] = 0f + output[offset + 1] = y + output[offset + 2] = 1f + output[offset + 3] = y + } + return output + } + } + + private var positionBufferId = 0 + private var textureCoordinateBufferId = 0 + private var indexBufferId = 0 + + fun initialize() { + release() + val ids = IntArray(3) + GLES30.glGenBuffers(ids.size, ids, 0) + positionBufferId = ids[0] + textureCoordinateBufferId = ids[1] + indexBufferId = ids[2] + + GLES30.glBindBuffer(GLES30.GL_ARRAY_BUFFER, positionBufferId) + GLES30.glBufferData( + GLES30.GL_ARRAY_BUFFER, + VERTEX_COUNT * POSITION_COMPONENT_COUNT * Float.SIZE_BYTES, + null, + GLES30.GL_DYNAMIC_DRAW, + ) + GLES30.glBindBuffer(GLES30.GL_ARRAY_BUFFER, textureCoordinateBufferId) + GLES30.glBufferData( + GLES30.GL_ARRAY_BUFFER, + textureCoordinates.size * Float.SIZE_BYTES, + floatBuffer(textureCoordinates), + GLES30.GL_STATIC_DRAW, + ) + GLES30.glBindBuffer(GLES30.GL_ELEMENT_ARRAY_BUFFER, indexBufferId) + GLES30.glBufferData( + GLES30.GL_ELEMENT_ARRAY_BUFFER, + indices.size * Short.SIZE_BYTES, + ByteBuffer.allocateDirect(indices.size * Short.SIZE_BYTES) + .order(ByteOrder.nativeOrder()) + .asShortBuffer() + .apply { + put(indices) + position(0) + }, + GLES30.GL_STATIC_DRAW, + ) + GLES30.glBindBuffer(GLES30.GL_ARRAY_BUFFER, 0) + GLES30.glBindBuffer(GLES30.GL_ELEMENT_ARRAY_BUFFER, 0) + } + + fun draw( + positionLocation: Int, + textureCoordinateLocation: Int, + rowHomographies: FloatArray, + ) { + if (positionBufferId == 0) initialize() + val positions = warpedPositions(rowHomographies) + GLES30.glBindBuffer(GLES30.GL_ARRAY_BUFFER, positionBufferId) + GLES30.glBufferSubData( + GLES30.GL_ARRAY_BUFFER, + 0, + positions.size * Float.SIZE_BYTES, + floatBuffer(positions), + ) + GLES30.glEnableVertexAttribArray(positionLocation) + GLES30.glVertexAttribPointer( + positionLocation, + POSITION_COMPONENT_COUNT, + GLES30.GL_FLOAT, + false, + 0, + 0, + ) + + GLES30.glBindBuffer(GLES30.GL_ARRAY_BUFFER, textureCoordinateBufferId) + GLES30.glEnableVertexAttribArray(textureCoordinateLocation) + GLES30.glVertexAttribPointer( + textureCoordinateLocation, + TEX_COORD_COMPONENT_COUNT, + GLES30.GL_FLOAT, + false, + 0, + 0, + ) + GLES30.glBindBuffer(GLES30.GL_ELEMENT_ARRAY_BUFFER, indexBufferId) + GLES30.glDrawElements( + GLES30.GL_TRIANGLES, + INDEX_COUNT, + GLES30.GL_UNSIGNED_SHORT, + 0, + ) + GLES30.glDisableVertexAttribArray(positionLocation) + GLES30.glDisableVertexAttribArray(textureCoordinateLocation) + GLES30.glBindBuffer(GLES30.GL_ARRAY_BUFFER, 0) + GLES30.glBindBuffer(GLES30.GL_ELEMENT_ARRAY_BUFFER, 0) + } + + fun resetAfterContextLoss() { + positionBufferId = 0 + textureCoordinateBufferId = 0 + indexBufferId = 0 + } + + fun release() { + val ids = intArrayOf(positionBufferId, textureCoordinateBufferId, indexBufferId) + .filter { it != 0 } + .toIntArray() + if (ids.isNotEmpty()) GLES30.glDeleteBuffers(ids.size, ids, 0) + resetAfterContextLoss() + } + + private fun floatBuffer(values: FloatArray) = + ByteBuffer.allocateDirect(values.size * Float.SIZE_BYTES) + .order(ByteOrder.nativeOrder()) + .asFloatBuffer() + .apply { + put(values) + position(0) + } +} diff --git a/app/src/main/java/com/hinnka/mycamera/lut/MgcEisPresentationTransform.kt b/app/src/main/java/com/hinnka/mycamera/lut/MgcEisPresentationTransform.kt new file mode 100644 index 00000000..8a94a242 --- /dev/null +++ b/app/src/main/java/com/hinnka/mycamera/lut/MgcEisPresentationTransform.kt @@ -0,0 +1,56 @@ +package com.hinnka.mycamera.lut + +import android.opengl.Matrix +import kotlin.math.abs + +/** Retains the cardinal OES orientation for the delayed ImageReader output presentation. */ +internal class MgcEisPresentationTransform { + val matrix = FloatArray(16).also { Matrix.setIdentityM(it, 0) } + private var captured = false + + /** + * Captures the configured stream orientation once. Camera2 may update the + * OES crop every frame, whereas its cardinal orientation is a stream + * property; freezing it prevents producer-buffer state from leaking into + * MGC's independent 2D texture. + */ + fun captureFromOes(oesMatrix: FloatArray): Boolean { + if (captured) return true + if (oesMatrix.size < 16) return false + + val uAlongX = abs(oesMatrix[0]) >= abs(oesMatrix[1]) + val vAlongX = abs(oesMatrix[4]) >= abs(oesMatrix[5]) + val uMagnitude = maxOf(abs(oesMatrix[0]), abs(oesMatrix[1])) + val vMagnitude = maxOf(abs(oesMatrix[4]), abs(oesMatrix[5])) + if (uAlongX == vAlongX || uMagnitude < 0.5f || vMagnitude < 0.5f) { + return false + } + + Matrix.setIdentityM(matrix, 0) + if (!uAlongX) { + // The OES transform is a cardinal 90° rotation. Convert its + // bottom-left OES origin to the regular 2D texture's orientation. + // setIdentityM() leaves m00/m11 as one; they must be cleared + // before installing the off-diagonal cardinal rotation. Leaving + // them in place produces a rotation-plus-shear matrix. + matrix[0] = 0f + matrix[5] = 0f + matrix[4] = if (oesMatrix[4] >= 0f) 1f else -1f + matrix[1] = if (oesMatrix[1] >= 0f) -1f else 1f + matrix[12] = if (oesMatrix[4] >= 0f) 0f else 1f + matrix[13] = if (oesMatrix[1] >= 0f) 1f else 0f + } else { + matrix[0] = if (oesMatrix[0] >= 0f) 1f else -1f + matrix[5] = if (oesMatrix[5] >= 0f) -1f else 1f + matrix[12] = if (oesMatrix[0] >= 0f) 0f else 1f + matrix[13] = if (oesMatrix[5] >= 0f) 1f else 0f + } + captured = true + return true + } + + fun reset() { + Matrix.setIdentityM(matrix, 0) + captured = false + } +} diff --git a/app/src/main/java/com/hinnka/mycamera/lut/MgcEisYuvRenderer.kt b/app/src/main/java/com/hinnka/mycamera/lut/MgcEisYuvRenderer.kt new file mode 100644 index 00000000..a4b7ca68 --- /dev/null +++ b/app/src/main/java/com/hinnka/mycamera/lut/MgcEisYuvRenderer.kt @@ -0,0 +1,377 @@ +package com.hinnka.mycamera.lut + +import android.media.Image +import android.opengl.GLES30 +import android.opengl.GLES31 +import com.hinnka.mycamera.stabilization.STABILIZATION_ROW_COUNT +import com.hinnka.mycamera.stabilization.StabilizationFrame +import com.hinnka.mycamera.utils.PLog +import java.nio.ByteBuffer + +/** + * Materializes one timestamp-matched Camera2 image after applying MGC's rolling-strip mesh. + * + * Center crop, orientation, mirroring and color effects remain in the normal preview or encoder + * presentation pass. + */ +internal class MgcEisYuvRenderer(private val tag: String) { + data class Frame(val timestampNs: Long, val textureId: Int) + + private val mesh = MgcEisMesh() + // Native output matrices pass through convertPixelHomographyToClip then + // applyCropZoomToClipHomography(kOutputCropZoom), where: + // kLookaheadCropMargin = 0.05 + // kOutputCropZoom = 1.0 / (1.0 - 2.0 * 0.05) ≈ 1.1111 + // applyCropZoomToClipHomography divides the W row (h20, h21, h22) by zoom. + // A Dropped frame must use the same crop so that the viewport does not jump + // between 1.0x and 1.111x on every stabilization gap. + private val droppedFrameHomographies = FloatArray(STABILIZATION_ROW_COUNT * 9).also { values -> + val h22 = 1.0f - 2.0f * 0.05f // = 1.0f / kOutputCropZoom = 0.9f + repeat(STABILIZATION_ROW_COUNT) { row -> + val offset = row * 9 + values[offset] = 1f // h00 + values[offset + 4] = 1f // h11 + values[offset + 8] = h22 // h22: W-row crop zoom + } + } + + private var programId = 0 + private var positionLocation = -1 + private var textureCoordinateLocation = -1 + private var ySamplerLocation = -1 + private var cbSamplerLocation = -1 + private var crSamplerLocation = -1 + private var imageSizeLocation = -1 + private var cbSizeLocation = -1 + private var crSizeLocation = -1 + private var cbStepLocation = -1 + private var crStepLocation = -1 + + private var yTextureId = 0 + private var cbTextureId = 0 + private var crTextureId = 0 + private var outputTextureId = 0 + private var outputFramebufferId = 0 + private var width = 0 + private var height = 0 + private var cbWidth = 0 + private var crWidth = 0 + private var chromaHeight = 0 + + /** Consumes ownership of [frame.image], including when rendering fails. */ + fun render(frame: StabilizationFrame): Frame? { + val source = frame.image.image + return try { + if (source.planes.size < 3 || source.width <= 0 || source.height <= 0) return null + val cbPlane = source.planes[1] + val crPlane = source.planes[2] + val logicalChromaWidth = (source.width + 1) / 2 + val logicalChromaHeight = (source.height + 1) / 2 + val requestedCbWidth = (logicalChromaWidth - 1) * cbPlane.pixelStride + 1 + val requestedCrWidth = (logicalChromaWidth - 1) * crPlane.pixelStride + 1 + if (!ensure( + source.width, + source.height, + requestedCbWidth, + requestedCrWidth, + logicalChromaHeight, + ) + ) { + return null + } + if (!uploadPlane(source.planes[0], yTextureId, source.width, source.height, "Y") || + !uploadPlane(cbPlane, cbTextureId, requestedCbWidth, logicalChromaHeight, "Cb") || + !uploadPlane(crPlane, crTextureId, requestedCrWidth, logicalChromaHeight, "Cr") + ) { + return null + } + + GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, outputFramebufferId) + GLES30.glViewport(0, 0, source.width, source.height) + GLES30.glClearColor(0f, 0f, 0f, 1f) + GLES30.glClear(GLES30.GL_COLOR_BUFFER_BIT) + GLES30.glUseProgram(programId) + bindTexture(0, yTextureId, ySamplerLocation) + bindTexture(1, cbTextureId, cbSamplerLocation) + bindTexture(2, crTextureId, crSamplerLocation) + GLES30.glUniform2i(imageSizeLocation, source.width, source.height) + GLES30.glUniform2i(cbSizeLocation, requestedCbWidth, logicalChromaHeight) + GLES30.glUniform2i(crSizeLocation, requestedCrWidth, logicalChromaHeight) + GLES30.glUniform1i(cbStepLocation, cbPlane.pixelStride) + GLES30.glUniform1i(crStepLocation, crPlane.pixelStride) + mesh.draw( + positionLocation = positionLocation, + textureCoordinateLocation = textureCoordinateLocation, + rowHomographies = frame.transform?.rowHomographies ?: droppedFrameHomographies, + ) + GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, 0) + GLES31.glMemoryBarrier( + GLES31.GL_FRAMEBUFFER_BARRIER_BIT or GLES31.GL_TEXTURE_FETCH_BARRIER_BIT, + ) + repeat(3) { unit -> + GLES30.glActiveTexture(GLES30.GL_TEXTURE0 + unit) + GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, 0) + } + GLES30.glActiveTexture(GLES30.GL_TEXTURE0) + Frame(frame.timestampNs, outputTextureId) + } catch (error: IllegalStateException) { + // Camera2 may revoke an acquired Image when the underlying + // ImageReader is torn down during a delayed-EIS session change. + // The timestamped result is no longer renderable, but it must not + // take the GL thread down with it. + PLog.w(tag, "MGC dropped revoked YUV image ts=${frame.timestampNs}: ${error.message}") + null + } finally { + // glTexSubImage2D has consumed the client memory when it returns; the Camera2 image + // is no longer referenced by later GPU commands in the CPU fallback path. + frame.image.close() + } + } + + fun resetAfterContextLoss() { + programId = 0 + positionLocation = -1 + textureCoordinateLocation = -1 + ySamplerLocation = -1 + cbSamplerLocation = -1 + crSamplerLocation = -1 + imageSizeLocation = -1 + cbSizeLocation = -1 + crSizeLocation = -1 + cbStepLocation = -1 + crStepLocation = -1 + yTextureId = 0 + cbTextureId = 0 + crTextureId = 0 + outputTextureId = 0 + outputFramebufferId = 0 + width = 0 + height = 0 + cbWidth = 0 + crWidth = 0 + chromaHeight = 0 + mesh.resetAfterContextLoss() + } + + fun release() { + val textures = intArrayOf( + yTextureId, + cbTextureId, + crTextureId, + outputTextureId, + ) + .filter { it != 0 } + .toIntArray() + if (textures.isNotEmpty()) GLES30.glDeleteTextures(textures.size, textures, 0) + if (outputFramebufferId != 0) { + GLES30.glDeleteFramebuffers(1, intArrayOf(outputFramebufferId), 0) + } + if (programId != 0) GLES30.glDeleteProgram(programId) + mesh.release() + resetAfterContextLoss() + } + + private fun ensure( + requestedWidth: Int, + requestedHeight: Int, + requestedCbWidth: Int, + requestedCrWidth: Int, + requestedChromaHeight: Int, + ): Boolean { + if (programId != 0 && width == requestedWidth && height == requestedHeight && + cbWidth == requestedCbWidth && crWidth == requestedCrWidth && + chromaHeight == requestedChromaHeight + ) { + return true + } + release() + val vertexShader = GlUtils.compileShader(GLES30.GL_VERTEX_SHADER, VERTEX_SHADER) + val fragmentShader = GlUtils.compileShader(GLES30.GL_FRAGMENT_SHADER, FRAGMENT_SHADER) + programId = GlUtils.linkProgram(vertexShader, fragmentShader) + GLES30.glDeleteShader(vertexShader) + GLES30.glDeleteShader(fragmentShader) + if (programId == 0) return false + positionLocation = GLES30.glGetAttribLocation(programId, "aPosition") + textureCoordinateLocation = GLES30.glGetAttribLocation(programId, "aTexCoord") + ySamplerLocation = GLES30.glGetUniformLocation(programId, "uY") + cbSamplerLocation = GLES30.glGetUniformLocation(programId, "uCb") + crSamplerLocation = GLES30.glGetUniformLocation(programId, "uCr") + imageSizeLocation = GLES30.glGetUniformLocation(programId, "uImageSize") + cbSizeLocation = GLES30.glGetUniformLocation(programId, "uCbSize") + crSizeLocation = GLES30.glGetUniformLocation(programId, "uCrSize") + cbStepLocation = GLES30.glGetUniformLocation(programId, "uCbStep") + crStepLocation = GLES30.glGetUniformLocation(programId, "uCrStep") + mesh.initialize() + + yTextureId = createTexture(requestedWidth, requestedHeight, GLES30.GL_R8) + cbTextureId = createTexture(requestedCbWidth, requestedChromaHeight, GLES30.GL_R8) + crTextureId = createTexture(requestedCrWidth, requestedChromaHeight, GLES30.GL_R8) + if (!createOutputTarget(requestedWidth, requestedHeight)) return false + width = requestedWidth + height = requestedHeight + cbWidth = requestedCbWidth + crWidth = requestedCrWidth + chromaHeight = requestedChromaHeight + return true + } + + private fun createOutputTarget(requestedWidth: Int, requestedHeight: Int): Boolean { + outputTextureId = createTexture(requestedWidth, requestedHeight, GLES30.GL_RGBA8) + val framebuffer = IntArray(1) + GLES30.glGenFramebuffers(1, framebuffer, 0) + outputFramebufferId = framebuffer[0] + GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, outputFramebufferId) + GLES30.glFramebufferTexture2D( + GLES30.GL_FRAMEBUFFER, + GLES30.GL_COLOR_ATTACHMENT0, + GLES30.GL_TEXTURE_2D, + outputTextureId, + 0, + ) + val complete = GLES30.glCheckFramebufferStatus(GLES30.GL_FRAMEBUFFER) == + GLES30.GL_FRAMEBUFFER_COMPLETE + GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, 0) + if (!complete) { + PLog.e(tag, "Cannot allocate MGC canonical output ${requestedWidth}x$requestedHeight") + release() + return false + } + return true + } + + + private fun createTexture(textureWidth: Int, textureHeight: Int, internalFormat: Int): Int { + val ids = IntArray(1) + GLES30.glGenTextures(1, ids, 0) + GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, ids[0]) + GLES30.glTexParameteri(GLES30.GL_TEXTURE_2D, GLES30.GL_TEXTURE_MIN_FILTER, GLES30.GL_LINEAR) + GLES30.glTexParameteri(GLES30.GL_TEXTURE_2D, GLES30.GL_TEXTURE_MAG_FILTER, GLES30.GL_LINEAR) + GLES30.glTexParameteri(GLES30.GL_TEXTURE_2D, GLES30.GL_TEXTURE_WRAP_S, GLES30.GL_CLAMP_TO_EDGE) + GLES30.glTexParameteri(GLES30.GL_TEXTURE_2D, GLES30.GL_TEXTURE_WRAP_T, GLES30.GL_CLAMP_TO_EDGE) + val format = if (internalFormat == GLES30.GL_RGBA8) GLES30.GL_RGBA else GLES30.GL_RED + GLES30.glTexImage2D( + GLES30.GL_TEXTURE_2D, + 0, + internalFormat, + textureWidth, + textureHeight, + 0, + format, + GLES30.GL_UNSIGNED_BYTE, + null, + ) + GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, 0) + return ids[0] + } + + private fun uploadPlane( + plane: Image.Plane, + textureId: Int, + uploadWidth: Int, + uploadHeight: Int, + label: String, + ): Boolean { + if (plane.pixelStride <= 0 || plane.rowStride < uploadWidth || uploadWidth <= 0 || + uploadHeight <= 0 + ) { + PLog.w(tag, "MGC $label invalid plane row=${plane.rowStride} pixel=${plane.pixelStride}") + return false + } + val buffer = plane.buffer.duplicate().apply { position(0) } + val required = (uploadHeight - 1).toLong() * plane.rowStride + uploadWidth + if (required > buffer.limit().toLong()) { + PLog.w(tag, "MGC $label buffer too small: required=$required available=${buffer.limit()}") + return false + } + uploadTexture(textureId, uploadWidth, uploadHeight, plane.rowStride, buffer) + return true + } + + private fun uploadTexture( + textureId: Int, + uploadWidth: Int, + uploadHeight: Int, + rowLength: Int, + buffer: ByteBuffer, + ) { + GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, textureId) + GLES30.glPixelStorei(GLES30.GL_UNPACK_ALIGNMENT, 1) + GLES30.glPixelStorei(GLES30.GL_UNPACK_ROW_LENGTH, rowLength) + GLES30.glTexSubImage2D( + GLES30.GL_TEXTURE_2D, + 0, + 0, + 0, + uploadWidth, + uploadHeight, + GLES30.GL_RED, + GLES30.GL_UNSIGNED_BYTE, + buffer, + ) + GLES30.glPixelStorei(GLES30.GL_UNPACK_ROW_LENGTH, 0) + GLES30.glPixelStorei(GLES30.GL_UNPACK_ALIGNMENT, 4) + GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, 0) + } + + private fun bindTexture(unit: Int, textureId: Int, samplerLocation: Int) { + GLES30.glActiveTexture(GLES30.GL_TEXTURE0 + unit) + GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, textureId) + GLES30.glUniform1i(samplerLocation, unit) + } + + private companion object { + val VERTEX_SHADER = """ + #version 300 es + in vec4 aPosition; + in vec2 aTexCoord; + out vec2 vTexCoord; + void main() { + gl_Position = aPosition; + vTexCoord = aTexCoord; + } + """.trimIndent() + + val FRAGMENT_SHADER = """ + #version 300 es + precision highp float; + uniform sampler2D uY; + uniform sampler2D uCb; + uniform sampler2D uCr; + uniform ivec2 uImageSize; + uniform ivec2 uCbSize; + uniform ivec2 uCrSize; + uniform int uCbStep; + uniform int uCrStep; + in vec2 vTexCoord; + out vec4 fragColor; + + void main() { + ivec2 p = clamp( + ivec2(vTexCoord * vec2(uImageSize)), + ivec2(0), + uImageSize - ivec2(1) + ); + ivec2 cbP = clamp( + ivec2((p.x / 2) * uCbStep, p.y / 2), + ivec2(0), + uCbSize - ivec2(1) + ); + ivec2 crP = clamp( + ivec2((p.x / 2) * uCrStep, p.y / 2), + ivec2(0), + uCrSize - ivec2(1) + ); + float y = texelFetch(uY, p, 0).r; + float cb = texelFetch(uCb, cbP, 0).r - 0.5; + float cr = texelFetch(uCr, crP, 0).r - 0.5; + vec3 rgb = vec3( + y + 1.402 * cr, + y - 0.344136 * cb - 0.714136 * cr, + y + 1.772 * cb + ); + fragColor = vec4(clamp(rgb, 0.0, 1.0), 1.0); + } + """.trimIndent() + + } +} diff --git a/app/src/main/java/com/hinnka/mycamera/lut/PreviewColorShader.kt b/app/src/main/java/com/hinnka/mycamera/lut/PreviewColorShader.kt index c8f774fa..333689f1 100644 --- a/app/src/main/java/com/hinnka/mycamera/lut/PreviewColorShader.kt +++ b/app/src/main/java/com/hinnka/mycamera/lut/PreviewColorShader.kt @@ -14,9 +14,6 @@ internal object PreviewColorShader { } val needsOklab = variant.includeOklchDensity || variant.includeLchMixer val needsClassifiers = variant.includeLchMixer || variant.includeLutMask - val supportsStabilization = - variant.textureSource == PreviewColorTextureSource.EXTERNAL_OES - return """ #version 300 es ${extension} @@ -43,10 +40,6 @@ internal object PreviewColorShader { uniform bool uColorRecipeEnabled; uniform mat4 uSTMatrix; - ${if (supportsStabilization) """ - uniform bool uStabilizationEnabled; - uniform mat3 uStabilizationRows[16]; - """ else ""} uniform float uExposure; uniform float uContrast; uniform float uSaturation; @@ -185,30 +178,8 @@ internal object PreviewColorShader { ${PreviewColorShaderModules.PRIMARY_CALIBRATION} ${PreviewColorShaderModules.LUT_COLOR_SPACE} - ${if (supportsStabilization) """ - vec2 applyStabilization(vec2 coordinate, float outputRow) { - if (!uStabilizationEnabled) { - return coordinate; - } - float rowPosition = clamp(outputRow, 0.0, 1.0) * 15.0; - int lowerIndex = clamp(int(floor(rowPosition)), 0, 14); - int upperIndex = lowerIndex + 1; - float amount = rowPosition - float(lowerIndex); - vec3 point = vec3(coordinate, 1.0); - vec3 lowerPoint = uStabilizationRows[lowerIndex] * point; - vec3 upperPoint = uStabilizationRows[upperIndex] * point; - vec2 lowerCoordinate = lowerPoint.xy / max(abs(lowerPoint.z), 0.000001); - vec2 upperCoordinate = upperPoint.xy / max(abs(upperPoint.z), 0.000001); - return mix(lowerCoordinate, upperCoordinate, amount); - } - """ else """ - vec2 applyStabilization(vec2 coordinate, float outputRow) { - return coordinate; - } - """} - void main() { - vec2 rcCoord = applyStabilization(vRawCoord, vOutputCoord.y); + vec2 rcCoord = vRawCoord; vec2 uvCoord = (uSTMatrix * vec4(rcCoord, 0.0, 1.0)).xy; if (uLowRes > 0.005) { float blocksX = mix(512.0, 32.0, uLowRes); diff --git a/app/src/main/java/com/hinnka/mycamera/lut/RealtimeVideoRenderer.kt b/app/src/main/java/com/hinnka/mycamera/lut/RealtimeVideoRenderer.kt index 426ef144..33b8722f 100644 --- a/app/src/main/java/com/hinnka/mycamera/lut/RealtimeVideoRenderer.kt +++ b/app/src/main/java/com/hinnka/mycamera/lut/RealtimeVideoRenderer.kt @@ -15,9 +15,8 @@ import android.util.Size import android.view.Surface import com.hinnka.mycamera.model.ColorPaletteMapper import com.hinnka.mycamera.model.ColorRecipeParams -import com.hinnka.mycamera.stabilization.AlgorithmicStabilizationTransform +import com.hinnka.mycamera.stabilization.DEFAULT_VIDEO_STABILIZATION_LOOKAHEAD import com.hinnka.mycamera.stabilization.RealtimeStabilizationCoordinator -import com.hinnka.mycamera.stabilization.STABILIZATION_ROW_COUNT import com.hinnka.mycamera.stabilization.StabilizationUseCase import com.hinnka.mycamera.utils.PLog import com.hinnka.mycamera.video.VideoEncoderColorConfig @@ -27,15 +26,16 @@ import java.nio.ByteBuffer import java.nio.ByteOrder import java.nio.FloatBuffer import java.nio.ShortBuffer +import java.util.concurrent.atomic.AtomicBoolean import kotlin.math.abs import kotlin.math.max /** * Camera2 录像专用实时渲染器。 * - * Camera2 将录像流写入此类拥有的独立 [SurfaceTexture];同一个专用 EGL context - * 随后把 OES 帧经过色彩层实时绘制到 MediaCodec input surface。该链路与屏幕预览 - * 完全分离,因此录像帧率不再受 GLSurfaceView 调度或预览 FBO 负载影响。 + * 普通录像从独立 [SurfaceTexture] 取 OES 帧;MGC 防抖录像改取与 CaptureResult 精确 + * 对时的共享 YUV 图像。两条路径最终都在专用 EGL context 中写入 MediaCodec surface, + * 因而录像帧率不受 GLSurfaceView 调度影响。 */ class RealtimeVideoRenderer( context: Context, @@ -49,6 +49,8 @@ class RealtimeVideoRenderer( private val encoderColorConfig: VideoEncoderColorConfig, private val stabilizationCoordinator: RealtimeStabilizationCoordinator?, private val enhancedStabilizationEnabled: Boolean, + private val enhancedStabilizationStrength: Float, + private val enhancedStabilizationLookahead: Int = DEFAULT_VIDEO_STABILIZATION_LOOKAHEAD, ) { companion object { private const val TAG = "RealtimeVideoRenderer" @@ -84,6 +86,8 @@ class RealtimeVideoRenderer( private val colorProgramCache = PreviewColorProgramCache() private val basicToneTextures = BasicToneGlTextures() private val filmGrainGl = FilmGrainGl(TAG) + private val mgcEisHardwareBufferRenderer = MgcEisHardwareBufferRenderer(TAG) + private val mgcEisYuvRenderer = MgcEisYuvRenderer(TAG) private val filmGrainAmount: Float get() = layers.lastOrNull { it.params.filmGrain > 0.001f }?.params?.filmGrain ?: 0f private val finalFilmGrainEnabled: Boolean @@ -106,6 +110,7 @@ class RealtimeVideoRenderer( private var cameraCropRect = fullCropRect private var cameraTransformAxesSwapped: Boolean? = null private val stMatrix = FloatArray(16).also { Matrix.setIdentityM(it, 0) } + private val mgcEisPresentationTransform = MgcEisPresentationTransform() private var eglDisplay: EGLDisplay = EGL14.EGL_NO_DISPLAY private var eglContext: EGLContext = EGL14.EGL_NO_CONTEXT @@ -121,6 +126,7 @@ class RealtimeVideoRenderer( private var textureCoordinateBuffer: FloatBuffer? = null private var indexBuffer: ShortBuffer? = null private var initialized = false + private val cameraFramePending = AtomicBoolean(false) @Volatile private var stabilizationSession: RealtimeStabilizationCoordinator.Session? = null @Volatile @@ -154,15 +160,21 @@ class RealtimeVideoRenderer( check(cameraTextureId != 0) { "Cannot create realtime video OES texture" } cameraSurfaceTexture = SurfaceTexture(cameraTextureId).apply { setDefaultBufferSize(cameraInputSize.width, cameraInputSize.height) - setOnFrameAvailableListener { onFrameAvailable() } + setOnFrameAvailableListener { + cameraFramePending.set(true) + if (!enhancedStabilizationEnabled) onFrameAvailable() + } } cameraSurface = Surface(cameraSurfaceTexture) if (enhancedStabilizationEnabled) { - stabilizationSession = stabilizationCoordinator?.createSession(StabilizationUseCase.VIDEO) - stabilizationSessionStarted = stabilizationSession?.start() == true - if (!stabilizationSessionStarted) { - PLog.w(TAG, "Enhanced stabilization requested but the gyro/camera session is unavailable") - } + stabilizationSession = stabilizationCoordinator?.createSession( + useCase = StabilizationUseCase.VIDEO, + strength = enhancedStabilizationStrength, + frameWidth = cameraInputSize.width, + frameHeight = cameraInputSize.height, + lookaheadFrames = enhancedStabilizationLookahead, + onFrameAvailable = onFrameAvailable, + ) } initialized = true PLog.i( @@ -171,6 +183,7 @@ class RealtimeVideoRenderer( "encoder=${encoderOutputSize.width}x${encoderOutputSize.height}, " + "layers=${layers.size}, log=${videoLogProfile.name}, hlgInput=$hlgInput, " + "enhancedStabilization=$enhancedStabilizationEnabled, " + + "stabilizationStrength=$enhancedStabilizationStrength, " + "mirrorH=$mirrorHorizontally, mirrorV=$mirrorVertically, " + "color=${encoderColorConfig.debugName}" ) @@ -188,28 +201,33 @@ class RealtimeVideoRenderer( ): Long? { if (!initialized || !makeCurrent()) return null val surfaceTexture = cameraSurfaceTexture ?: return null - try { - surfaceTexture.updateTexImage() - surfaceTexture.getTransformMatrix(stMatrix) - updateCameraTransformGeometry() - } catch (error: RuntimeException) { - PLog.e(TAG, "Failed to acquire realtime video frame", error) - return null - } + val cameraFrameUpdated = cameraFramePending.getAndSet(false) && + acquireLatestCameraFrame(surfaceTexture) + val cameraTimestampNs = surfaceTexture.timestamp - val timestampNs = surfaceTexture.timestamp + var sourceTextureSource = PreviewColorTextureSource.EXTERNAL_OES + var sourceTextureTarget = GLES11Ext.GL_TEXTURE_EXTERNAL_OES + var sourceTextureId = cameraTextureId + var sourceStMatrix = stMatrix + var sourceCropRect = cameraCropRect + var timestampNs = cameraTimestampNs + + if (enhancedStabilizationEnabled && stabilizationSessionStarted) { + val session = stabilizationSession ?: return null + val frame = session.dequeueFrame() ?: return null + val rendered = renderMgcEisFrame(frame) ?: return null + sourceTextureSource = PreviewColorTextureSource.TEXTURE_2D + sourceTextureTarget = GLES30.GL_TEXTURE_2D + sourceTextureId = rendered.textureId + sourceStMatrix = mgcEisPresentationTransform.matrix + sourceCropRect = cameraCropRect + timestampNs = rendered.timestampNs + } else { + if (!cameraFrameUpdated || cameraTimestampNs <= 0L) return null + } if (timestampNs <= 0L) return null val presentationTimeNs = mapPresentationTimeNs(timestampNs) if (presentationTimeNs <= 0L) return null - val stabilizationTransform = if (stabilizationSessionStarted) { - stabilizationSession?.transformForFrame( - timestampNs = timestampNs, - baseCropRect = cameraCropRect, - textureAxesSwapped = cameraTransformAxesSwapped == true, - ) - } else { - null - } val firstLayer = layers.first() val grainEnabled = finalFilmGrainEnabled @@ -217,16 +235,15 @@ class RealtimeVideoRenderer( drawLayer( layer = firstLayer, targetFboId = firstTargetFbo, - textureSource = PreviewColorTextureSource.EXTERNAL_OES, - textureTarget = GLES11Ext.GL_TEXTURE_EXTERNAL_OES, - textureId = cameraTextureId, - sourceStMatrix = stMatrix, - cropRect = stabilizationTransform?.cropRect ?: cameraCropRect, + textureSource = sourceTextureSource, + textureTarget = sourceTextureTarget, + textureId = sourceTextureId, + sourceStMatrix = sourceStMatrix, + cropRect = sourceCropRect, mvpMatrix = firstPassMvpMatrix, enableVideoLog = videoLogProfile.isEnabled, treatSourceAsHlgInput = hlgInput, presentationTimeNs = timestampNs, - stabilizationTransform = stabilizationTransform, ) if (layers.size > 1) { @@ -278,6 +295,36 @@ class RealtimeVideoRenderer( return presentationTimeNs } + private fun acquireLatestCameraFrame(surfaceTexture: SurfaceTexture): Boolean { + return try { + surfaceTexture.updateTexImage() + surfaceTexture.getTransformMatrix(stMatrix) + if (enhancedStabilizationEnabled && + !mgcEisPresentationTransform.captureFromOes(stMatrix) + ) { + PLog.w(TAG, "MGC cannot derive a cardinal presentation orientation yet") + } + updateCameraTransformGeometry() + true + } catch (error: RuntimeException) { + PLog.e(TAG, "Failed to acquire realtime video frame", error) + false + } + } + + private fun renderMgcEisFrame( + frame: com.hinnka.mycamera.stabilization.StabilizationFrame, + ): MgcEisHardwareBufferRenderer.Frame? { + val hardwareRendered = mgcEisHardwareBufferRenderer.render(frame) + if (hardwareRendered != null) { + frame.image.close() + return hardwareRendered + } + return mgcEisYuvRenderer.render(frame)?.let { rendered -> + MgcEisHardwareBufferRenderer.Frame(rendered.timestampNs, rendered.textureId) + } + } + private fun updateCameraTransformGeometry() { val axesSwapped = isTextureTransformAxesSwapped(stMatrix) if (cameraTransformAxesSwapped == axesSwapped) return @@ -310,7 +357,6 @@ class RealtimeVideoRenderer( enableVideoLog: Boolean, treatSourceAsHlgInput: Boolean, presentationTimeNs: Long, - stabilizationTransform: AlgorithmicStabilizationTransform? = null, ) { val lutEnabled = layer.lutConfig != null && layer.lutTextureId != 0 val variant = PreviewColorShaderVariant.forPass( @@ -350,21 +396,6 @@ class RealtimeVideoRenderer( cropRect[2], cropRect[3], ) - val stabilizationEnabled = stabilizationTransform != null && - stabilizationTransform.rowHomographies.size == STABILIZATION_ROW_COUNT * 9 - GLES30.glUniform1i( - locations.uStabilizationEnabledLocation, - if (stabilizationEnabled) 1 else 0, - ) - if (stabilizationEnabled) { - GLES30.glUniformMatrix3fv( - locations.uStabilizationRowsLocation, - STABILIZATION_ROW_COUNT, - false, - stabilizationTransform.rowHomographies, - 0, - ) - } GLES30.glUniform1f( locations.uLutSizeLocation, layer.lutConfig?.size?.toFloat() ?: 1f, @@ -434,23 +465,15 @@ class RealtimeVideoRenderer( positions.position(0) textureCoordinates.position(0) indices.position(0) + GLES30.glBindBuffer(GLES30.GL_ARRAY_BUFFER, 0) + GLES30.glBindBuffer(GLES30.GL_ELEMENT_ARRAY_BUFFER, 0) GLES30.glEnableVertexAttribArray(locations.aPositionLocation) GLES30.glVertexAttribPointer( - locations.aPositionLocation, - 2, - GLES30.GL_FLOAT, - false, - 0, - positions, + locations.aPositionLocation, 2, GLES30.GL_FLOAT, false, 0, positions, ) GLES30.glEnableVertexAttribArray(locations.aTexCoordLocation) GLES30.glVertexAttribPointer( - locations.aTexCoordLocation, - 2, - GLES30.GL_FLOAT, - false, - 0, - textureCoordinates, + locations.aTexCoordLocation, 2, GLES30.GL_FLOAT, false, 0, textureCoordinates, ) GLES30.glDrawElements( GLES30.GL_TRIANGLES, @@ -872,6 +895,8 @@ class RealtimeVideoRenderer( finalColorFboId = 0 } filmGrainGl.release() + mgcEisHardwareBufferRenderer.release() + mgcEisYuvRenderer.release() colorProgramCache.release() basicToneTextures.release() @@ -896,6 +921,13 @@ class RealtimeVideoRenderer( } } +internal fun isTextureTransformAxesSwapped(matrix: FloatArray): Boolean { + if (matrix.size < 6) return false + val transformedXAxisFollowsY = abs(matrix[1]) > abs(matrix[0]) + val transformedYAxisFollowsX = abs(matrix[4]) > abs(matrix[5]) + return transformedXAxisFollowsY && transformedYAxisFollowsX +} + private fun resolveCenterCropRect(source: Size, target: Size): FloatArray { val sourceAspect = source.width.toFloat() / max(1, source.height).toFloat() val targetAspect = target.width.toFloat() / max(1, target.height).toFloat() @@ -913,10 +945,3 @@ private fun resolveCenterCropRect(source: Size, target: Size): FloatArray { else -> floatArrayOf(0f, 0f, 1f, 1f) } } - -internal fun isTextureTransformAxesSwapped(matrix: FloatArray): Boolean { - if (matrix.size < 6) return false - val transformedXAxisFollowsY = abs(matrix[1]) > abs(matrix[0]) - val transformedYAxisFollowsX = abs(matrix[4]) > abs(matrix[5]) - return transformedXAxisFollowsY && transformedYAxisFollowsX -} diff --git a/app/src/main/java/com/hinnka/mycamera/stabilization/MgcEisDiagnosticTrace.kt b/app/src/main/java/com/hinnka/mycamera/stabilization/MgcEisDiagnosticTrace.kt new file mode 100644 index 00000000..31f9ec5b --- /dev/null +++ b/app/src/main/java/com/hinnka/mycamera/stabilization/MgcEisDiagnosticTrace.kt @@ -0,0 +1,125 @@ +package com.hinnka.mycamera.stabilization + +import com.hinnka.mycamera.BuildConfig +import com.hinnka.mycamera.utils.PLog +import java.io.File +import java.util.Locale +import java.util.concurrent.Executors + +/** + * Debug-only, bounded native-input trace for differential EIS reconstruction. + * + * This has no image payload and is deliberately outside the stabilizer's timing path: it retains + * only the exact Java-to-Native call sequence in memory, then writes one immutable snapshot from + * a background thread. The snapshot can be replayed by the isolated original-MGC oracle; it is + * never read by, packaged with, or executed by the camera pipeline. + */ +internal class MgcEisDiagnosticTrace( + private val cacheDirectory: File, +) { + companion object { + private const val TAG = "MgcEisTrace" + private const val MAX_FRAME_CALLS = 180 + private const val MAX_GYRO_SAMPLES = 8_192 + } + + private val writer = Executors.newSingleThreadExecutor { runnable -> + Thread(runnable, "Photon-MGC-EIS-Trace").apply { isDaemon = true } + } + private val entries = ArrayList(MAX_FRAME_CALLS + MAX_GYRO_SAMPLES) + + private var active = false + private var snapshotQueued = false + private var gyroCount = 0 + private var frameCount = 0 + + @Synchronized + fun start(width: Int, height: Int, frontFacing: Boolean, strength: Float) { + entries.clear() + active = BuildConfig.DEBUG + snapshotQueued = false + gyroCount = 0 + frameCount = 0 + if (!active) return + entries += listOf( + "HEADER", + width.toString(), + height.toString(), + frontFacing.toString(), + strength.toString(), + ).joinToString(",") + } + + @Synchronized + fun recordGyro(timestampNs: Long, x: Float, y: Float, z: Float) { + if (!active || snapshotQueued || gyroCount >= MAX_GYRO_SAMPLES) return + entries += listOf("G", timestampNs, x, y, z).joinToString(",") + gyroCount += 1 + } + + @Synchronized + fun recordFrame( + input: MgcEisNativeEngine.FrameInput, + firstRowCenterTimestampNs: Long, + croppedRollingShutterSkewNs: Long, + inverseFocalLength: Float, + activeWidth: Int, + activeHeight: Int, + resultTimestampNs: Long, + matrices: FloatArray, + ) { + if (!active || snapshotQueued || frameCount >= MAX_FRAME_CALLS) return + val fields = ArrayList(20 + matrices.size) + fields += "F" + fields += input.sensorTimestampNs.toString() + fields += firstRowCenterTimestampNs.toString() + fields += input.exposureTimeNs.toString() + fields += croppedRollingShutterSkewNs.toString() + fields += inverseFocalLength.toString() + fields += activeWidth.toString() + fields += activeHeight.toString() + fields += input.cropRegion.width().toString() + fields += input.cropRegion.height().toString() + fields += resultTimestampNs.toString() + if (resultTimestampNs >= 0L) { + matrices.forEach { fields += it.toString() } + } + entries += fields.joinToString(",") + frameCount += 1 + if (frameCount == MAX_FRAME_CALLS) queueSnapshotLocked() + } + + @Synchronized + fun stop() { + if (active && !snapshotQueued && frameCount > 0) queueSnapshotLocked() + active = false + } + + @Synchronized + private fun queueSnapshotLocked() { + if (snapshotQueued) return + snapshotQueued = true + val content = entries.joinToString(separator = "\n", postfix = "\n") + val savedGyroCount = gyroCount + val savedFrameCount = frameCount + writer.execute { + try { + val directory = File(cacheDirectory, "mgc-eis-traces").apply { mkdirs() } + val file = File(directory, "mgc-eis-${System.currentTimeMillis()}.csv") + file.writeText(content, Charsets.UTF_8) + PLog.i( + TAG, + String.format( + Locale.US, + "Saved differential trace: %s (gyro=%d, frames=%d)", + file.absolutePath, + savedGyroCount, + savedFrameCount, + ), + ) + } catch (error: Throwable) { + PLog.e(TAG, "Unable to save MGC differential trace", error) + } + } + } +} diff --git a/app/src/main/java/com/hinnka/mycamera/stabilization/MgcEisNativeBridge.kt b/app/src/main/java/com/hinnka/mycamera/stabilization/MgcEisNativeBridge.kt new file mode 100644 index 00000000..34a4644c --- /dev/null +++ b/app/src/main/java/com/hinnka/mycamera/stabilization/MgcEisNativeBridge.kt @@ -0,0 +1,64 @@ +package com.hinnka.mycamera.stabilization + +import android.hardware.HardwareBuffer + +/** JNI boundary for Photon’s source-reconstructed MGC EIS engine. */ +internal object MgcEisNativeBridge { + init { + System.loadLibrary("my-native-lib") + } + + external fun create( + width: Int, + height: Int, + frontFacing: Boolean, + strength: Float, + lookaheadFrames: Int, + ): Long + + external fun release(handle: Long) + + external fun processGyro( + handle: Long, + x: Float, + y: Float, + z: Float, + timestampNs: Long, + ): Boolean + + external fun processLensOffset( + handle: Long, + xShiftPixels: Float, + yShiftPixels: Float, + timestampNs: Long, + cameraType: Int, + ): Boolean + + external fun processFrame( + handle: Long, + sourceTimestampNs: Long, + firstRowCenterTimestampNs: Long, + exposureTimeNs: Long, + rollingShutterSkewNs: Long, + inverseFocalLength: Float, + activeWidth: Int, + activeHeight: Int, + cropWidth: Int, + cropHeight: Int, + rowHomographies: FloatArray, + state: FloatArray, + ): Long + + /** + * Imports a Camera2 [HardwareBuffer] into the current EGL context as an EGLImage. + * + * The returned handle owns the acquired native buffer reference and must be released on the + * same GL thread with [destroyHardwareBufferImage] after the draw that samples it. + */ + external fun createHardwareBufferImage(buffer: HardwareBuffer): Long + + /** Binds an imported EGLImage to [textureId], which must be a GL_TEXTURE_EXTERNAL_OES. */ + external fun bindHardwareBufferImage(imageHandle: Long, textureId: Int): Boolean + + external fun destroyHardwareBufferImage(imageHandle: Long) +} diff --git a/app/src/main/java/com/hinnka/mycamera/stabilization/MgcEisNativeEngine.kt b/app/src/main/java/com/hinnka/mycamera/stabilization/MgcEisNativeEngine.kt new file mode 100644 index 00000000..b7b77a4f --- /dev/null +++ b/app/src/main/java/com/hinnka/mycamera/stabilization/MgcEisNativeEngine.kt @@ -0,0 +1,249 @@ +package com.hinnka.mycamera.stabilization + +import android.graphics.Rect +import com.hinnka.mycamera.utils.PLog +import java.io.File + +/** + * Lifecycle wrapper around Photon’s source reconstruction of MGC’s sensor EIS path. + * + * MGC 9.6.080 resolves the installed `device_key=blueline` to product profile 7. The original + * factory selects method 4, 12 strips and a seven-frame look-ahead for that profile. This class + * owns the recovered gyro queues, motion filtering, look-ahead, crop constraints and rolling- + * shutter projection as ordinary app source compiled into `libmy-native-lib.so`; it never loads + * `libgcastartup.so`. The empty profile configuration has no calibrated OIS camera model, so raw + * OIS offsets are not fabricated into a separate image translation. + */ +internal class MgcEisNativeEngine(cacheDirectory: File) { + companion object { + private const val TAG = "MgcEisNativeEngine" + private const val MGC_DEVICE_KEY = "blueline" + private const val MGC_DEVICE_TYPE = 7 + const val STRIP_COUNT = 12 + const val LOOKAHEAD_FRAME_COUNT = 7 + } + + data class FrameInput( + val sensorTimestampNs: Long, + val exposureTimeNs: Long, + val rollingShutterSkewNs: Long, + val cropRegion: Rect, + val activeArray: Rect, + val physicalSensorWidthMm: Float, + val focalLengthMm: Float, + ) + + sealed interface FrameResult { + data class Stabilized( + val sensorTimestampNs: Long, + val rowHomographies: FloatArray, + val appliedStrength: Float, + val tripodMode: Boolean, + ) : FrameResult + + data class Dropped(val sensorTimestampNs: Long) : FrameResult + } + + private var handle = 0L + private var frameWidth = 0 + private var frameHeight = 0 + private var gyroSampleCount = 0L + private var firstGyroTimestampNs = 0L + private var lensOffsetCount = 0L + private var frameCallCount = 0L + private val diagnosticTrace = MgcEisDiagnosticTrace(cacheDirectory) + + @Synchronized + fun start( + width: Int, + height: Int, + frontFacing: Boolean, + strength: Float, + lookaheadFrames: Int = DEFAULT_VIDEO_STABILIZATION_LOOKAHEAD, + ): Boolean { + if (handle != 0L) { + return frameWidth == width && frameHeight == height + } + if (width <= 0 || height <= 0) return false + val normalizedLookahead = normalizeStabilizationLookahead(lookaheadFrames) + return try { + val created = MgcEisNativeBridge.create( + width, + height, + frontFacing, + strength, + normalizedLookahead, + ) + if (created == 0L) return false + handle = created + frameWidth = width + frameHeight = height + gyroSampleCount = 0L + firstGyroTimestampNs = 0L + lensOffsetCount = 0L + frameCallCount = 0L + diagnosticTrace.start(width, height, frontFacing, strength) + PLog.i( + TAG, + "Reconstructed MGC EIS started: device=$MGC_DEVICE_KEY, profile=$MGC_DEVICE_TYPE, " + + "frame=${width}x$height, " + + "strips=$STRIP_COUNT, lookahead=$normalizedLookahead, " + + "strength=$strength, front=$frontFacing", + ) + true + } catch (error: Throwable) { + PLog.e(TAG, "Unable to start reconstructed MGC EIS", error) + false + } + } + + @Synchronized + fun stop() { + diagnosticTrace.stop() + val current = handle + handle = 0L + frameWidth = 0 + frameHeight = 0 + gyroSampleCount = 0L + firstGyroTimestampNs = 0L + lensOffsetCount = 0L + frameCallCount = 0L + if (current != 0L) { + runCatching { MgcEisNativeBridge.release(current) } + .onFailure { PLog.e(TAG, "Unable to release reconstructed MGC EIS", it) } + } + } + + @Synchronized + fun processGyro(x: Float, y: Float, z: Float, timestampNs: Long) { + val current = handle + if (current != 0L) { + gyroSampleCount += 1L + val accepted = MgcEisNativeBridge.processGyro(current, x, y, z, timestampNs) + if (accepted) { + if (firstGyroTimestampNs == 0L) firstGyroTimestampNs = timestampNs + diagnosticTrace.recordGyro(timestampNs, x, y, z) + } + if (gyroSampleCount <= 3L || gyroSampleCount % 500L == 0L) { + PLog.i( + TAG, + "MGC processGyro #$gyroSampleCount: ts=$timestampNs, " + + "xyz=($x,$y,$z), accepted=$accepted", + ) + } + } + } + + @Synchronized + fun processLensOffset( + xShiftPixels: Float, + yShiftPixels: Float, + timestampNs: Long, + cameraType: Int, + ) { + val current = handle + if (current != 0L) { + lensOffsetCount += 1L + val accepted = MgcEisNativeBridge.processLensOffset( + current, + xShiftPixels, + yShiftPixels, + timestampNs, + cameraType, + ) + if (lensOffsetCount <= 3L || lensOffsetCount % 100L == 0L) { + PLog.i( + TAG, + "MGC processLensOffset #$lensOffsetCount: ts=$timestampNs, " + + "xy=($xShiftPixels,$yShiftPixels), camera=$cameraType, " + + "accepted=$accepted", + ) + } + } + } + + @Synchronized + fun processFrame(input: FrameInput): FrameResult? { + val current = handle + if (current == 0L) return null + val activeWidth = input.activeArray.width().coerceAtLeast(1) + val activeHeight = input.activeArray.height().coerceAtLeast(1) + val crop = input.cropRegion + if (crop.width() <= 0 || crop.height() <= 0 || + input.focalLengthMm <= 0f || input.physicalSensorWidthMm <= 0f + ) { + return FrameResult.Dropped(input.sensorTimestampNs) + } + + // htd.m902...: timestamp of the centre of the first row in the scaler crop. + val firstRowCenterTimestampNs = input.sensorTimestampNs + input.exposureTimeNs / 2L + + input.rollingShutterSkewNs * crop.top.toLong() / activeHeight.toLong() + val croppedRollingShutterSkewNs = + input.rollingShutterSkewNs * crop.height().toLong() / activeHeight.toLong() + val inverseFocalLength = crop.width().toFloat() / activeWidth.toFloat() * + (input.physicalSensorWidthMm / input.focalLengthMm) + + // htd's one-second dead-source escape can submit a startup backlog before the first + // calibrated gyro event arrives. Those images do not have a reconstructable pose and + // must be reported as dropped instead of entering the seven-frame motion filter as a + // fabricated identity pose. + if (firstGyroTimestampNs == 0L || firstGyroTimestampNs > firstRowCenterTimestampNs) { + return FrameResult.Dropped(input.sensorTimestampNs) + } + + frameCallCount += 1L + val shouldLog = frameCallCount <= 3L || frameCallCount % 30L == 0L + if (shouldLog) { + PLog.i( + TAG, + "MGC processFrame entry #$frameCallCount: sensorTs=${input.sensorTimestampNs}, " + + "firstRowTs=$firstRowCenterTimestampNs, exposure=${input.exposureTimeNs}, " + + "rolling=$croppedRollingShutterSkewNs, active=${activeWidth}x$activeHeight, " + + "crop=$crop, focal=${input.focalLengthMm}, " + + "inverseFocal=$inverseFocalLength, gyro=$gyroSampleCount, ois=$lensOffsetCount", + ) + } + val matrices = FloatArray(STRIP_COUNT * 9) + val state = FloatArray(2) + val resultTimestampNs = MgcEisNativeBridge.processFrame( + current, + input.sensorTimestampNs, + firstRowCenterTimestampNs, + input.exposureTimeNs, + croppedRollingShutterSkewNs, + inverseFocalLength, + activeWidth, + activeHeight, + crop.width(), + crop.height(), + matrices, + state, + ) + diagnosticTrace.recordFrame( + input = input, + firstRowCenterTimestampNs = firstRowCenterTimestampNs, + croppedRollingShutterSkewNs = croppedRollingShutterSkewNs, + inverseFocalLength = inverseFocalLength, + activeWidth = activeWidth, + activeHeight = activeHeight, + resultTimestampNs = resultTimestampNs, + matrices = matrices, + ) + if (shouldLog) { + PLog.i( + TAG, + "MGC processFrame exit #$frameCallCount: outputSourceTs=$resultTimestampNs", + ) + } + return when { + resultTimestampNs == -1L -> null + resultTimestampNs < -1L -> FrameResult.Dropped(-resultTimestampNs) + else -> FrameResult.Stabilized( + sensorTimestampNs = resultTimestampNs, + rowHomographies = matrices, + appliedStrength = state[0], + tripodMode = state[1] != 0f, + ) + } + } +} diff --git a/app/src/main/java/com/hinnka/mycamera/stabilization/RealtimeStabilizationCoordinator.kt b/app/src/main/java/com/hinnka/mycamera/stabilization/RealtimeStabilizationCoordinator.kt index 0baa423f..42ae0231 100644 --- a/app/src/main/java/com/hinnka/mycamera/stabilization/RealtimeStabilizationCoordinator.kt +++ b/app/src/main/java/com/hinnka/mycamera/stabilization/RealtimeStabilizationCoordinator.kt @@ -8,49 +8,82 @@ import android.hardware.SensorEventListener import android.hardware.SensorManager import android.hardware.camera2.CameraCharacteristics import android.hardware.camera2.CaptureResult +import android.hardware.camera2.TotalCaptureResult +import android.media.Image import android.os.Handler import android.os.HandlerThread import android.util.SizeF import com.hinnka.mycamera.utils.PLog import java.util.ArrayDeque -import kotlin.math.acos -import kotlin.math.cos -import kotlin.math.exp -import kotlin.math.max -import kotlin.math.min -import kotlin.math.sin -import kotlin.math.sqrt +import java.util.LinkedHashMap +import java.util.concurrent.atomic.AtomicBoolean -const val STABILIZATION_ROW_COUNT = 16 +const val STABILIZATION_ROW_COUNT = MgcEisNativeEngine.STRIP_COUNT +const val STABILIZATION_LOOKAHEAD_FRAME_COUNT = MgcEisNativeEngine.LOOKAHEAD_FRAME_COUNT +// MGC profile 7 passes 1.0 to setStabilizationStrength. The value is consumed by the packed +// method-4 look-ahead pose blend; the outer full-grid feasibility correction is independent. +const val DEFAULT_VIDEO_STABILIZATION_STRENGTH = 1f +const val DEFAULT_VIDEO_STABILIZATION_LOOKAHEAD = 7 +const val MIN_VIDEO_STABILIZATION_LOOKAHEAD = 3 +const val MAX_VIDEO_STABILIZATION_LOOKAHEAD = 10 + +fun normalizeStabilizationStrength(strength: Float): Float = + if (strength.isFinite()) strength.coerceIn(0f, 1f) else DEFAULT_VIDEO_STABILIZATION_STRENGTH + +fun normalizeStabilizationLookahead(lookahead: Int): Int = + lookahead.coerceIn(MIN_VIDEO_STABILIZATION_LOOKAHEAD, MAX_VIDEO_STABILIZATION_LOOKAHEAD) enum class StabilizationUseCase( - internal val smoothingTimeSeconds: Double, - internal val cropMarginFraction: Float, + internal val defaultStrength: Float, ) { - VIDEO( - smoothingTimeSeconds = 0.28, - cropMarginFraction = 0.10f, - ), - PHOTO_PREVIEW( - smoothingTimeSeconds = 0.14, - cropMarginFraction = 0.07f, - ), + VIDEO(DEFAULT_VIDEO_STABILIZATION_STRENGTH), + PHOTO_PREVIEW(DEFAULT_VIDEO_STABILIZATION_STRENGTH), } data class AlgorithmicStabilizationTransform( - /** 16 column-major output-to-input homographies, ready for glUniformMatrix3fv. */ + /** SENSOR_TIMESTAMP of the buffered image for which MGC emitted this transform. */ + val timestampNs: Long, + /** MGC's 12 row-major forward vertex homographies, without inversion or interpolation. */ val rowHomographies: FloatArray, - /** Crop applied before the homographies, in normalized SurfaceTexture coordinates. */ + /** SurfaceTexture crop associated with the buffered image, applied before the row mesh. */ val cropRect: FloatArray, val hasPoseCoverage: Boolean, + /** Applied source-engine correction after the crop feasibility constraint. */ val appliedStrength: Float, val tripodMode: Boolean, ) +data class StabilizationFrame( + val timestampNs: Long, + /** Null means MGC explicitly dropped stabilization for this source frame. */ + val transform: AlgorithmicStabilizationTransform?, + /** Exact Camera2 image whose SENSOR_TIMESTAMP equals [timestampNs]. */ + val image: StabilizationImage, +) + +/** + * Reference-counted view of one Camera2 YUV image shared by preview and recording consumers. + * The underlying [Image] stays open until every consumer has finished its synchronous GL upload. + */ +class StabilizationImage internal constructor( + val timestampNs: Long, + val width: Int, + val height: Int, + internal val image: Image, + private val onClose: () -> Unit, +) : AutoCloseable { + private val closed = AtomicBoolean(false) + + override fun close() { + if (closed.compareAndSet(false, true)) onClose() + } +} + private data class CameraCalibration( val activeArray: Rect, - val physicalSizeMm: SizeF?, + val physicalSizeMm: SizeF, val lensFacing: Int, + val sensorOrientationDegrees: Int, val timestampSource: Int, ) @@ -58,70 +91,103 @@ private data class FrameMetadata( val timestampNs: Long, val exposureTimeNs: Long, val rollingShutterSkewNs: Long, - val cropRegion: Rect?, - val zoomRatio: Float, + val cropRegion: Rect, val focalLengthMm: Float, ) -private data class PoseSample( +private data class GyroSample( val timestampNs: Long, - val orientation: Quaternion, - val angularSpeedRadPerSecond: Double, + val x: Float, + val y: Float, + val z: Float, ) -private data class ResolvedFrameMotion( - val centerOrientation: Quaternion, - val rowOrientations: List, - val metadata: FrameMetadata?, - val calibration: CameraCalibration, - val tripodMode: Boolean, +private data class SequencedNativeResult( + val sequence: Long, + val result: MgcEisNativeEngine.FrameResult, +) + +private data class BufferedStabilizationImage( + val image: Image, + val width: Int, + val height: Int, + val pendingSessionIds: MutableSet, + var acquiredLeaseCount: Int = 0, ) /** - * Shared sensor and Camera2 metadata source for the screen-preview and recording renderers. + * Source reconstruction of MGC's htd frame feeder around Photon's native EIS implementation. * - * Gyroscope and SENSOR_TIMESTAMP are both expressed against elapsedRealtimeNanos on Android. - * A renderer owns a lightweight [Session]; the high-rate sensor listener is reference counted so - * the gyro is only active while at least one algorithmic stabilization path is actually rendering. + * Camera metadata, calibrated gyro samples and optional OIS samples are held until they cross the + * next timestamped image boundary. Reconstructed profile 7 then supplies a seven-frame + * look-ahead. Preview and recording sessions share the feeder, source image and + * result stream. */ class RealtimeStabilizationCoordinator(context: Context) { companion object { private const val TAG = "RealtimeStabilization" - private const val MAX_POSE_AGE_NS = 3_000_000_000L - private const val MAX_METADATA_AGE_NS = 3_000_000_000L - private const val MAX_GYRO_STEP_NS = 50_000_000L - private const val METADATA_MATCH_TOLERANCE_NS = 12_000_000L - private const val TRIPOD_SPEED_THRESHOLD_RAD_S = 0.012 - private const val TRIPOD_HOLD_NS = 800_000_000L + private const val SOURCE_DEAD_TIMEOUT_NS = 1_000_000_000L + private const val MAX_RESULT_COUNT = 90 + private const val MAX_METADATA_COUNT = 90 + private const val MAX_PENDING_GYRO_COUNT = 4096 + private const val MAX_BUFFERED_STABILIZATION_IMAGES = + STABILIZATION_LOOKAHEAD_FRAME_COUNT + 8 + const val STABILIZATION_IMAGE_READER_MAX_IMAGES = + MAX_BUFFERED_STABILIZATION_IMAGES + 2 } private val sensorManager = context.applicationContext .getSystemService(Context.SENSOR_SERVICE) as SensorManager - private val gyroSensor = sensorManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE_UNCALIBRATED) - ?: sensorManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE) + // MGC's EIS path requests Android sensor type 4: the calibrated gyroscope. + private val gyroSensor = sensorManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE) + private val nativeEngine = MgcEisNativeEngine(context.applicationContext.cacheDir) private val lock = Any() - private val poses = ArrayDeque() - private val frameMetadata = ArrayDeque() + private val pendingGyroSamples = ArrayDeque() + private val frameMetadata = LinkedHashMap() + private val frameBoundaries = ArrayList() + private val nativeResults = ArrayDeque() + private val bufferedImages = LinkedHashMap() + private val activeSessions = LinkedHashMap Unit)?>() @Volatile private var calibration: CameraCalibration? = null - private var sensorThread: HandlerThread? = null + @Volatile + private var gyroSourceReady = false + private var activeSessionCount = 0 - private var integratedOrientation = Quaternion.IDENTITY - private var previousRate = Vec3.ZERO - private var previousGyroTimestampNs = 0L - private var stillSinceTimestampNs = 0L - private var tripodMode = false + private var nextSessionId = 1L + private var sensorThread: HandlerThread? = null + private var nativeFrameWidth = 0 + private var nativeFrameHeight = 0 + private var nativeStrength = 0f + private var nativeLookaheadFrames = DEFAULT_VIDEO_STABILIZATION_LOOKAHEAD + private var gyroFeedBoundaryNs = 0L + private var lastProcessedGyroTimestampNs = 0L + private var lastOisTimestampNs = 0L + private var latestMetadataTimestampNs = 0L + private var lastFrameBoundaryNs = 0L + private var resultSequence = 0L + private var boundaryCount = 0L + private var nativeFrameAttemptCount = 0L + private var captureResultCount = 0L + private var rawGyroCallbackCount = 0L + private var oisSourceActive = false + private var lastLoggedBoundaryCount = -1L + private var lastLoggedGateBoundaryCount = -1L val isGyroscopeAvailable: Boolean get() = gyroSensor != null + /** True after this acquisition has received its first monotonic calibrated gyro sample. */ + val isPoseSourceReady: Boolean + get() = gyroSourceReady + val isCurrentCameraSupported: Boolean get() { val current = calibration - return isGyroscopeAvailable && - current?.lensFacing == CameraCharacteristics.LENS_FACING_BACK && + return isGyroscopeAvailable && current != null && + current.lensFacing == CameraCharacteristics.LENS_FACING_BACK && current.timestampSource == CameraCharacteristics.SENSOR_INFO_TIMESTAMP_SOURCE_REALTIME } @@ -133,25 +199,48 @@ class RealtimeStabilizationCoordinator(context: Context) { val lensFacing = characteristics.get(CameraCharacteristics.LENS_FACING) ?: timingCharacteristics.get(CameraCharacteristics.LENS_FACING) val timestampSource = timingCharacteristics.get( - CameraCharacteristics.SENSOR_INFO_TIMESTAMP_SOURCE + CameraCharacteristics.SENSOR_INFO_TIMESTAMP_SOURCE, ) ?: CameraCharacteristics.SENSOR_INFO_TIMESTAMP_SOURCE_UNKNOWN - return isGyroscopeAvailable && - characteristics.get(CameraCharacteristics.SENSOR_INFO_ACTIVE_ARRAY_SIZE) != null && + val activeArray = characteristics.get(CameraCharacteristics.SENSOR_INFO_ACTIVE_ARRAY_SIZE) + val physicalSize = characteristics.get(CameraCharacteristics.SENSOR_INFO_PHYSICAL_SIZE) + return isGyroscopeAvailable && activeArray != null && physicalSize != null && lensFacing == CameraCharacteristics.LENS_FACING_BACK && timestampSource == CameraCharacteristics.SENSOR_INFO_TIMESTAMP_SOURCE_REALTIME } private val sensorListener = object : SensorEventListener { override fun onSensorChanged(event: SensorEvent) { + rawGyroCallbackCount += 1L + if (rawGyroCallbackCount <= 3L || rawGyroCallbackCount % 500L == 0L) { + PLog.i( + TAG, + "MGC raw gyro callback #$rawGyroCallbackCount: " + + "sensorType=${event.sensor.type}, values=${event.values.size}, " + + "ts=${event.timestamp}", + ) + } if (event.values.size < 3) return - val uncalibrated = event.sensor.type == Sensor.TYPE_GYROSCOPE_UNCALIBRATED && - event.values.size >= 6 - val rate = Vec3( - x = (event.values[0] - if (uncalibrated) event.values[3] else 0f).toDouble(), - y = (event.values[1] - if (uncalibrated) event.values[4] else 0f).toDouble(), - z = (event.values[2] - if (uncalibrated) event.values[5] else 0f).toDouble(), + val mapped = remapMgcGyro( + x = event.values[0], + y = event.values[1], + z = event.values[2], + calibration = calibration, ) - appendGyro(event.timestamp, rate) + synchronized(lock) { + if (activeSessionCount <= 0) return + val previousTimestampNs = pendingGyroSamples.lastOrNull()?.timestampNs + ?: lastProcessedGyroTimestampNs + if (event.timestamp <= previousTimestampNs) return + pendingGyroSamples.addLast( + GyroSample(event.timestamp, mapped.first, mapped.second, mapped.third), + ) + gyroSourceReady = true + while (pendingGyroSamples.size > MAX_PENDING_GYRO_COUNT) { + pendingGyroSamples.removeFirst() + } + feedGyroThroughBoundaryLocked() + drainFramesLocked(lastFrameBoundaryNs) + } } override fun onAccuracyChanged(sensor: Sensor?, accuracy: Int) = Unit @@ -162,223 +251,500 @@ class RealtimeStabilizationCoordinator(context: Context) { timingCharacteristics: CameraCharacteristics = characteristics, ) { val activeArray = characteristics.get(CameraCharacteristics.SENSOR_INFO_ACTIVE_ARRAY_SIZE) - if (activeArray == null) { + val physicalSize = characteristics.get(CameraCharacteristics.SENSOR_INFO_PHYSICAL_SIZE) + if (activeArray == null || physicalSize == null) { calibration = null return } calibration = CameraCalibration( activeArray = Rect(activeArray), - physicalSizeMm = characteristics.get(CameraCharacteristics.SENSOR_INFO_PHYSICAL_SIZE), + physicalSizeMm = physicalSize, lensFacing = characteristics.get(CameraCharacteristics.LENS_FACING) ?: timingCharacteristics.get(CameraCharacteristics.LENS_FACING) ?: CameraCharacteristics.LENS_FACING_BACK, + sensorOrientationDegrees = characteristics.get(CameraCharacteristics.SENSOR_ORIENTATION) + ?: timingCharacteristics.get(CameraCharacteristics.SENSOR_ORIENTATION) + ?: 0, timestampSource = timingCharacteristics.get( - CameraCharacteristics.SENSOR_INFO_TIMESTAMP_SOURCE + CameraCharacteristics.SENSOR_INFO_TIMESTAMP_SOURCE, ) ?: CameraCharacteristics.SENSOR_INFO_TIMESTAMP_SOURCE_UNKNOWN, ) + PLog.i( + TAG, + "MGC camera calibration: active=$activeArray, physical=$physicalSize, " + + "orientation=${calibration?.sensorOrientationDegrees}, " + + "facing=${calibration?.lensFacing}, timestampSource=${calibration?.timestampSource}", + ) } - fun submitCaptureResult(result: CaptureResult) { - val timestampNs = result.get(CaptureResult.SENSOR_TIMESTAMP) ?: return + fun submitCaptureResult( + result: CaptureResult, + request: android.hardware.camera2.CaptureRequest? = null, + outputPhysicalCameraId: String? = null, + ) { + val physicalResult = (result as? TotalCaptureResult)?.let { totalResult -> + val physicalId = outputPhysicalCameraId + ?: totalResult.get(CaptureResult.LOGICAL_MULTI_CAMERA_ACTIVE_PHYSICAL_ID) + physicalId?.let(totalResult.physicalCameraResults::get) + } + fun value(key: CaptureResult.Key): T? = + physicalResult?.get(key) ?: result.get(key) + + val currentCalibration = calibration ?: return + val timestampNs = value(CaptureResult.SENSOR_TIMESTAMP) ?: return val metadata = FrameMetadata( timestampNs = timestampNs, - exposureTimeNs = result.get(CaptureResult.SENSOR_EXPOSURE_TIME)?.coerceAtLeast(0L) ?: 0L, - rollingShutterSkewNs = result.get(CaptureResult.SENSOR_ROLLING_SHUTTER_SKEW) + exposureTimeNs = value(CaptureResult.SENSOR_EXPOSURE_TIME)?.coerceAtLeast(0L) ?: 0L, + rollingShutterSkewNs = value(CaptureResult.SENSOR_ROLLING_SHUTTER_SKEW) ?.coerceAtLeast(0L) ?: 0L, - cropRegion = result.get(CaptureResult.SCALER_CROP_REGION)?.let(::Rect), - zoomRatio = result.get(CaptureResult.CONTROL_ZOOM_RATIO)?.coerceAtLeast(1f) ?: 1f, - focalLengthMm = result.get(CaptureResult.LENS_FOCAL_LENGTH)?.coerceAtLeast(0f) ?: 0f, + cropRegion = value(CaptureResult.SCALER_CROP_REGION)?.let(::Rect) + ?: Rect(currentCalibration.activeArray), + focalLengthMm = value(CaptureResult.LENS_FOCAL_LENGTH)?.coerceAtLeast(0f) ?: 0f, ) + val oisSamples = value(CaptureResult.STATISTICS_OIS_SAMPLES).orEmpty() synchronized(lock) { - if (frameMetadata.isNotEmpty() && timestampNs <= frameMetadata.last().timestampNs) { - frameMetadata.removeAll { it.timestampNs == timestampNs } + captureResultCount += 1L + if (activeSessionCount > 0 && + (captureResultCount <= 3L || captureResultCount % 30L == 0L) + ) { + PLog.i( + TAG, + "MGC CaptureResult #$captureResultCount: ts=$timestampNs, " + + "requestedVideoStabilization=" + + request?.get(android.hardware.camera2.CaptureRequest.CONTROL_VIDEO_STABILIZATION_MODE) + + ", requestedOpticalStabilization=" + + request?.get(android.hardware.camera2.CaptureRequest.LENS_OPTICAL_STABILIZATION_MODE) + + ", actualVideoStabilization=" + + value(CaptureResult.CONTROL_VIDEO_STABILIZATION_MODE) + + ", actualOpticalStabilization=" + + value(CaptureResult.LENS_OPTICAL_STABILIZATION_MODE) + + ", oisSamples=${oisSamples.size}", + ) } - frameMetadata.addLast(metadata) - val oldestAllowed = timestampNs - MAX_METADATA_AGE_NS - while (frameMetadata.firstOrNull()?.timestampNs?.let { it < oldestAllowed } == true) { - frameMetadata.removeFirst() + frameMetadata[timestampNs] = metadata + latestMetadataTimestampNs = maxOf(latestMetadataTimestampNs, timestampNs) + trimOldest(frameMetadata, MAX_METADATA_COUNT) + + oisSamples.forEach { sample -> + if (!sample.xshift.isFinite() || !sample.yshift.isFinite() || + sample.timestamp < lastOisTimestampNs + ) { + return@forEach + } + nativeEngine.processLensOffset( + xShiftPixels = sample.xshift, + yShiftPixels = sample.yshift, + timestampNs = sample.timestamp, + cameraType = 0, + ) + lastOisTimestampNs = sample.timestamp + oisSourceActive = true } + drainFramesLocked(lastFrameBoundaryNs) } } - fun createSession(useCase: StabilizationUseCase): Session = Session(this, useCase) + fun createSession( + useCase: StabilizationUseCase, + strength: Float = useCase.defaultStrength, + frameWidth: Int = 1920, + frameHeight: Int = 1080, + lookaheadFrames: Int = DEFAULT_VIDEO_STABILIZATION_LOOKAHEAD, + onFrameAvailable: (() -> Unit)? = null, + ): Session = Session( + coordinator = this, + sessionId = synchronized(lock) { nextSessionId++ }, + strength = normalizeStabilizationStrength(strength), + frameWidth = frameWidth, + frameHeight = frameHeight, + lookaheadFrames = normalizeStabilizationLookahead(lookaheadFrames), + onFrameAvailable = onFrameAvailable, + ) - private fun acquireSensor(): Boolean { + /** + * Accepts every ImageReader image in FIFO order. This is the only EIS frame-boundary source: + * SurfaceTexture callbacks are presentation signals and must never advance the native feeder. + */ + fun submitStabilizationImage(image: Image) { + val timestampNs = image.timestamp synchronized(lock) { - activeSessionCount += 1 - if (activeSessionCount > 1) return true - val sensor = gyroSensor ?: run { - activeSessionCount = 0 - return false + if (activeSessionCount <= 0 || timestampNs <= 0L || + image.width != nativeFrameWidth || image.height != nativeFrameHeight + ) { + image.close() + return } - poses.clear() - integratedOrientation = Quaternion.IDENTITY - previousRate = Vec3.ZERO - previousGyroTimestampNs = 0L - stillSinceTimestampNs = 0L - tripodMode = false - val thread = HandlerThread("Photon-Stabilization-Gyro").apply { start() } + bufferedImages.remove(timestampNs)?.image?.close() + bufferedImages[timestampNs] = BufferedStabilizationImage( + image = image, + width = image.width, + height = image.height, + pendingSessionIds = activeSessions.keys.toMutableSet(), + ) + trimBufferedImagesLocked() + onFrameBoundaryLocked(timestampNs) + } + } + + private fun acquire( + sessionId: Long, + onFrameAvailable: (() -> Unit)?, + frameWidth: Int, + frameHeight: Int, + strength: Float, + lookaheadFrames: Int, + ): Long? = synchronized(lock) { + if (!isCurrentCameraSupported) return null + val normalizedLookahead = normalizeStabilizationLookahead(lookaheadFrames) + val sameConfig = activeSessions.isNotEmpty() && + nativeFrameWidth == frameWidth && + nativeFrameHeight == frameHeight && + nativeLookaheadFrames == normalizedLookahead && + kotlin.math.abs(nativeStrength - strength) <= 0.0001f + + if (sameConfig) { + activeSessions[sessionId] = onFrameAvailable + activeSessionCount = activeSessions.size + return resultSequence + } + + if (activeSessions.isNotEmpty()) { + PLog.i( + TAG, + "MGC EIS reconfiguring from ${nativeFrameWidth}x${nativeFrameHeight}@$nativeStrength,lookahead=$nativeLookaheadFrames " + + "to ${frameWidth}x${frameHeight}@$strength,lookahead=$normalizedLookahead", + ) + nativeEngine.stop() + resetFeederLocked() + nativeFrameWidth = 0 + nativeFrameHeight = 0 + nativeStrength = 0f + nativeLookaheadFrames = DEFAULT_VIDEO_STABILIZATION_LOOKAHEAD + activeSessions.clear() + activeSessionCount = 0 + } + + val currentCalibration = calibration ?: return null + val sensor = gyroSensor ?: return null + if (!nativeEngine.start( + width = frameWidth, + height = frameHeight, + frontFacing = currentCalibration.lensFacing == + CameraCharacteristics.LENS_FACING_FRONT, + strength = strength, + lookaheadFrames = normalizedLookahead, + ) + ) { + return null + } + + resetFeederLocked() + nativeFrameWidth = frameWidth + nativeFrameHeight = frameHeight + nativeStrength = strength + nativeLookaheadFrames = normalizedLookahead + if (sensorThread == null) { + val thread = HandlerThread("Photon-MGC-EIS-Gyro").apply { start() } val registered = sensorManager.registerListener( sensorListener, sensor, SensorManager.SENSOR_DELAY_FASTEST, + 0, Handler(thread.looper), ) if (!registered) { thread.quitSafely() - activeSessionCount = 0 - PLog.w(TAG, "Unable to register gyroscope listener") - return false + nativeEngine.stop() + nativeFrameWidth = 0 + nativeFrameHeight = 0 + nativeStrength = 0f + nativeLookaheadFrames = DEFAULT_VIDEO_STABILIZATION_LOOKAHEAD + PLog.e(TAG, "Unable to register MGC calibrated gyroscope stream") + return null } sensorThread = thread - PLog.i(TAG, "Gyroscope stream started: ${sensor.name}") - return true } + activeSessions[sessionId] = onFrameAvailable + activeSessionCount = activeSessions.size + PLog.i(TAG, "MGC htd feeder started with gyro=${sensor.name}") + resultSequence } - private fun releaseSensor() { + private fun release(sessionId: Long) { synchronized(lock) { - if (activeSessionCount <= 0) return - activeSessionCount -= 1 + activeSessions.remove(sessionId) + bufferedImages.values.forEach { it.pendingSessionIds.remove(sessionId) } + closeFullyConsumedImagesLocked() + activeSessionCount = activeSessions.size if (activeSessionCount > 0) return sensorManager.unregisterListener(sensorListener) sensorThread?.quitSafely() sensorThread = null - poses.clear() - previousGyroTimestampNs = 0L - PLog.i(TAG, "Gyroscope stream stopped") + nativeEngine.stop() + nativeFrameWidth = 0 + nativeFrameHeight = 0 + nativeStrength = 0f + nativeLookaheadFrames = DEFAULT_VIDEO_STABILIZATION_LOOKAHEAD + resetFeederLocked() + PLog.i(TAG, "MGC htd feeder stopped") } } - private fun appendGyro(timestampNs: Long, rate: Vec3) { + private fun resetFeederLocked() { + pendingGyroSamples.clear() + frameMetadata.clear() + frameBoundaries.clear() + nativeResults.clear() + bufferedImages.values.forEach { it.image.close() } + bufferedImages.clear() + activeSessions.clear() + gyroFeedBoundaryNs = 0L + lastProcessedGyroTimestampNs = 0L + lastOisTimestampNs = 0L + latestMetadataTimestampNs = 0L + lastFrameBoundaryNs = 0L + resultSequence = 0L + boundaryCount = 0L + nativeFrameAttemptCount = 0L + captureResultCount = 0L + rawGyroCallbackCount = 0L + gyroSourceReady = false + oisSourceActive = false + lastLoggedBoundaryCount = -1L + lastLoggedGateBoundaryCount = -1L + } + + private fun onFrameBoundaryLocked(timestampNs: Long) { + if (activeSessionCount <= 0 || timestampNs <= 0L || + timestampNs <= lastFrameBoundaryNs + ) { + return + } + lastFrameBoundaryNs = timestampNs + boundaryCount += 1L + gyroFeedBoundaryNs = timestampNs + val initialSourceTimestampNs = timestampNs - 1L + if (lastProcessedGyroTimestampNs == 0L) { + lastProcessedGyroTimestampNs = initialSourceTimestampNs + } + feedGyroThroughBoundaryLocked() + frameBoundaries.add(timestampNs) + drainFramesLocked(timestampNs) + } + + private fun feedGyroThroughBoundaryLocked() { + while (pendingGyroSamples.isNotEmpty()) { + val sample = pendingGyroSamples.removeFirst() + nativeEngine.processGyro(sample.x, sample.y, sample.z, sample.timestampNs) + lastProcessedGyroTimestampNs = sample.timestampNs + } + } + + /** Literal control flow of htd.e(long), including its one-second dead-source escape. */ + private fun drainFramesLocked(currentBoundaryNs: Long) { + if (currentBoundaryNs <= 0L || frameBoundaries.size <= 1) return + val gyroDead = currentBoundaryNs >= lastProcessedGyroTimestampNs + SOURCE_DEAD_TIMEOUT_NS + val oisDead = !oisSourceActive || + currentBoundaryNs >= lastOisTimestampNs + SOURCE_DEAD_TIMEOUT_NS + val metadataDead = currentBoundaryNs >= latestMetadataTimestampNs + SOURCE_DEAD_TIMEOUT_NS + if ((boundaryCount <= 3L || boundaryCount % 15L == 0L) && + lastLoggedBoundaryCount != boundaryCount + ) { + lastLoggedBoundaryCount = boundaryCount + PLog.i( + TAG, + "MGC feeder state: boundary#$boundaryCount=$currentBoundaryNs, " + + "queuedBoundaries=${frameBoundaries.size}, metadata=${frameMetadata.size}, " + + "pendingGyro=${pendingGyroSamples.size}, " + + "gyroLagMs=${timestampLagMs(currentBoundaryNs, lastProcessedGyroTimestampNs)}" + + "(dead=$gyroDead), " + + "oisLagMs=${timestampLagMs(currentBoundaryNs, lastOisTimestampNs)}" + + "(dead=$oisDead), " + + "metadataLagMs=${timestampLagMs(currentBoundaryNs, latestMetadataTimestampNs)}" + + "(dead=$metadataDead), attempts=$nativeFrameAttemptCount, " + + "results=$resultSequence", + ) + } + while (frameBoundaries.size > 1) { + val nextBoundaryNs = frameBoundaries[1] + if (!gyroDead && lastProcessedGyroTimestampNs < nextBoundaryNs) { + logGateLocked("gyro", nextBoundaryNs) + break + } + if (!oisDead && lastOisTimestampNs < nextBoundaryNs) { + logGateLocked("ois", nextBoundaryNs) + break + } + if (!metadataDead && latestMetadataTimestampNs < nextBoundaryNs) { + logGateLocked("metadata", nextBoundaryNs) + break + } + + val frameTimestampNs = frameBoundaries.removeAt(0) + val metadata = frameMetadata.remove(frameTimestampNs) + if (metadata == null) { + val nearestMetadataTimestampNs = frameMetadata.keys.minByOrNull { + absoluteTimestampDifference(it, frameTimestampNs) + } + PLog.w( + TAG, + "MGC has no exact metadata for boundary=$frameTimestampNs; " + + "nearest=$nearestMetadataTimestampNs, " + + "deltaNs=${nearestMetadataTimestampNs?.minus(frameTimestampNs)}", + ) + appendNativeResultLocked( + MgcEisNativeEngine.FrameResult.Dropped(frameTimestampNs), + ) + continue + } + val currentCalibration = calibration ?: continue + nativeFrameAttemptCount += 1L + if (nativeFrameAttemptCount <= 3L || nativeFrameAttemptCount % 30L == 0L) { + PLog.i( + TAG, + "Calling MGC native processFrame #$nativeFrameAttemptCount for " + + "sensorTs=${metadata.timestampNs}", + ) + } + val result = nativeEngine.processFrame( + MgcEisNativeEngine.FrameInput( + sensorTimestampNs = metadata.timestampNs, + exposureTimeNs = metadata.exposureTimeNs, + rollingShutterSkewNs = metadata.rollingShutterSkewNs, + cropRegion = metadata.cropRegion, + activeArray = currentCalibration.activeArray, + physicalSensorWidthMm = currentCalibration.physicalSizeMm.width, + focalLengthMm = metadata.focalLengthMm, + ), + ) + if (nativeFrameAttemptCount <= 3L || nativeFrameAttemptCount % 30L == 0L) { + PLog.i( + TAG, + "MGC native processFrame #$nativeFrameAttemptCount returned " + + (result?.javaClass?.simpleName ?: "pending"), + ) + } + if (result != null) appendNativeResultLocked(result) + } + } + + private fun logGateLocked(source: String, nextBoundaryNs: Long) { + if ((boundaryCount <= 3L || boundaryCount % 15L == 0L) && + lastLoggedGateBoundaryCount != boundaryCount + ) { + lastLoggedGateBoundaryCount = boundaryCount + PLog.i(TAG, "MGC feeder waiting for $source to cross nextBoundary=$nextBoundaryNs") + } + } + + private fun appendNativeResultLocked(result: MgcEisNativeEngine.FrameResult) { + resultSequence += 1L + nativeResults.addLast(SequencedNativeResult(resultSequence, result)) + while (nativeResults.size > MAX_RESULT_COUNT) nativeResults.removeFirst() + activeSessions.values.forEach { callback -> + try { + callback?.invoke() + } catch (error: RuntimeException) { + PLog.w(TAG, "MGC frame-ready callback failed: ${error.message}") + } + } + } + + private fun nextNativeResult(afterSequence: Long): SequencedNativeResult? = + synchronized(lock) { nativeResults.firstOrNull { it.sequence > afterSequence } } + + private fun pendingNativeResultCount(afterSequence: Long): Int = synchronized(lock) { + nativeResults.count { it.sequence > afterSequence } + } + + private fun currentResultSequence(): Long = synchronized(lock) { resultSequence } + + private fun acquireImageForSession( + sessionId: Long, + timestampNs: Long, + ): StabilizationImage? = synchronized(lock) { + val buffered = bufferedImages[timestampNs] ?: return@synchronized null + if (!buffered.pendingSessionIds.remove(sessionId)) return@synchronized null + buffered.acquiredLeaseCount += 1 + StabilizationImage( + timestampNs = timestampNs, + // A camera-session teardown may revoke an ImageReader image while + // a delayed native result is still queued. Its dimensions were + // captured while the image was valid; the renderer then handles a + // revoked plane as a dropped frame rather than crashing the GL thread. + width = buffered.width, + height = buffered.height, + image = buffered.image, + onClose = { releaseImageLease(timestampNs) }, + ) + } + + private fun releaseImageLease(timestampNs: Long) { synchronized(lock) { - if (activeSessionCount <= 0) return - if (previousGyroTimestampNs == 0L) { - previousGyroTimestampNs = timestampNs - previousRate = rate - poses.addLast(PoseSample(timestampNs, integratedOrientation, rate.length())) - updateTripodState(timestampNs, rate.length()) - return - } - val stepNs = timestampNs - previousGyroTimestampNs - if (stepNs <= 0L) return - if (stepNs > MAX_GYRO_STEP_NS) { - integratedOrientation = Quaternion.IDENTITY - poses.clear() - } else { - val dt = stepNs.toDouble() * 1.0e-9 - val midpointRate = (previousRate + rate) * 0.5 - integratedOrientation = ( - integratedOrientation * Quaternion.fromRotationVector(midpointRate * dt) - ).normalized() - } - previousGyroTimestampNs = timestampNs - previousRate = rate - val angularSpeed = rate.length() - poses.addLast(PoseSample(timestampNs, integratedOrientation, angularSpeed)) - updateTripodState(timestampNs, angularSpeed) - - val oldestAllowed = timestampNs - MAX_POSE_AGE_NS - while (poses.firstOrNull()?.timestampNs?.let { it < oldestAllowed } == true) { - poses.removeFirst() - } + val buffered = bufferedImages[timestampNs] ?: return + buffered.acquiredLeaseCount = (buffered.acquiredLeaseCount - 1).coerceAtLeast(0) + closeFullyConsumedImagesLocked() } } - private fun updateTripodState(timestampNs: Long, angularSpeed: Double) { - if (angularSpeed <= TRIPOD_SPEED_THRESHOLD_RAD_S) { - if (stillSinceTimestampNs == 0L) stillSinceTimestampNs = timestampNs - tripodMode = timestampNs - stillSinceTimestampNs >= TRIPOD_HOLD_NS - } else { - stillSinceTimestampNs = 0L - tripodMode = false - } - } - - private fun resolveFrameMotion(timestampNs: Long): ResolvedFrameMotion? { - val currentCalibration = calibration ?: return null - synchronized(lock) { - if (poses.size < 2) return null - val metadata = nearestMetadataLocked(timestampNs) - val exposureNs = metadata?.exposureTimeNs ?: 0L - val rollingSkewNs = metadata?.rollingShutterSkewNs ?: 0L - val activeHeight = currentCalibration.activeArray.height().coerceAtLeast(1) - val crop = metadata?.cropRegion ?: currentCalibration.activeArray - val cropStartFraction = (crop.top - currentCalibration.activeArray.top) - .toDouble() / activeHeight.toDouble() - val cropHeightFraction = crop.height().toDouble() / activeHeight.toDouble() - val firstRowCenterNs = timestampNs + exposureNs / 2L + - (rollingSkewNs * cropStartFraction).toLong() - val rowSpanNs = (rollingSkewNs * cropHeightFraction).toLong() - val centerTimestampNs = firstRowCenterNs + rowSpanNs / 2L - val firstPoseTimestamp = poses.first().timestampNs - val lastPoseTimestamp = poses.last().timestampNs - if (centerTimestampNs < firstPoseTimestamp - METADATA_MATCH_TOLERANCE_NS || - centerTimestampNs > lastPoseTimestamp + METADATA_MATCH_TOLERANCE_NS - ) { - return null - } - - val center = orientationAtLocked(centerTimestampNs) ?: return null - val rows = List(STABILIZATION_ROW_COUNT) { index -> - val fraction = index.toDouble() / (STABILIZATION_ROW_COUNT - 1).toDouble() - orientationAtLocked(firstRowCenterNs + (rowSpanNs * fraction).toLong()) ?: center - } - return ResolvedFrameMotion( - centerOrientation = center, - rowOrientations = rows, - metadata = metadata, - calibration = currentCalibration, - tripodMode = tripodMode, + private fun trimBufferedImagesLocked() { + while (bufferedImages.size > MAX_BUFFERED_STABILIZATION_IMAGES) { + val oldestEntry = bufferedImages.entries.firstOrNull { + it.value.acquiredLeaseCount == 0 + } ?: return + val oldestTimestamp = oldestEntry.key + val oldest = bufferedImages.remove(oldestTimestamp) ?: continue + oldest.image.close() + PLog.w( + TAG, + "MGC YUV queue overflow; dropping source image $oldestTimestamp " + + "before native result, queued=${bufferedImages.size}", ) } } - private fun nearestMetadataLocked(timestampNs: Long): FrameMetadata? { - var best: FrameMetadata? = null - var bestDistance = Long.MAX_VALUE - frameMetadata.forEach { candidate -> - val distance = absoluteDifference(candidate.timestampNs, timestampNs) - if (distance < bestDistance) { - best = candidate - bestDistance = distance + private fun closeFullyConsumedImagesLocked() { + val iterator = bufferedImages.entries.iterator() + while (iterator.hasNext()) { + val entry = iterator.next() + val buffered = entry.value + if (buffered.pendingSessionIds.isEmpty() && buffered.acquiredLeaseCount == 0) { + iterator.remove() + buffered.image.close() } } - return best?.takeIf { bestDistance <= METADATA_MATCH_TOLERANCE_NS } - } - - private fun orientationAtLocked(timestampNs: Long): Quaternion? { - if (poses.isEmpty()) return null - if (timestampNs <= poses.first().timestampNs) return poses.first().orientation - if (timestampNs >= poses.last().timestampNs) return poses.last().orientation - var before = poses.first() - poses.forEach { after -> - if (after.timestampNs >= timestampNs) { - val span = after.timestampNs - before.timestampNs - if (span <= 0L) return before.orientation - val fraction = (timestampNs - before.timestampNs).toDouble() / span.toDouble() - return Quaternion.slerp(before.orientation, after.orientation, fraction) - } - before = after - } - return poses.last().orientation } class Session internal constructor( private val coordinator: RealtimeStabilizationCoordinator, - private val useCase: StabilizationUseCase, + private val sessionId: Long, + private val strength: Float, + private val frameWidth: Int, + private val frameHeight: Int, + private val lookaheadFrames: Int, + private val onFrameAvailable: (() -> Unit)?, ) { private var active = false - private var smoothedOrientation: Quaternion? = null - private var lastFrameTimestampNs = 0L + private var lastConsumedSequence = 0L + + val isPoseSourceReady: Boolean + get() = active && coordinator.isPoseSourceReady @Synchronized fun start(): Boolean { if (active) return true - if (!coordinator.isCurrentCameraSupported) return false - active = coordinator.acquireSensor() - smoothedOrientation = null - lastFrameTimestampNs = 0L + val startSequence = coordinator.acquire( + sessionId = sessionId, + onFrameAvailable = onFrameAvailable, + frameWidth = frameWidth, + frameHeight = frameHeight, + strength = strength, + lookaheadFrames = lookaheadFrames, + ) + active = startSequence != null + // Registration and the result cursor are captured under the same coordinator lock: + // no image can include this session and then have its result skipped by a start race. + lastConsumedSequence = startSequence ?: 0L return active } @@ -386,393 +752,127 @@ class RealtimeStabilizationCoordinator(context: Context) { fun stop() { if (!active) return active = false - smoothedOrientation = null - lastFrameTimestampNs = 0L - coordinator.releaseSensor() + lastConsumedSequence = 0L + coordinator.release(sessionId) } @Synchronized - fun transformForFrame( - timestampNs: Long, - baseCropRect: FloatArray, - textureAxesSwapped: Boolean, - displayRotationDegrees: Int = 0, - ): AlgorithmicStabilizationTransform? { - if (!active || !coordinator.isCurrentCameraSupported || - timestampNs <= 0L || baseCropRect.size < 4 - ) { - return null - } - val stabilizedCrop = insetCrop(baseCropRect, useCase.cropMarginFraction) - val motion = coordinator.resolveFrameMotion(timestampNs) - ?: return identityTransform(stabilizedCrop, hasCoverage = false) - - val currentSmooth = smoothedOrientation - val frameDeltaNs = timestampNs - lastFrameTimestampNs - val nextSmooth = if (currentSmooth == null || frameDeltaNs <= 0L || - frameDeltaNs > 500_000_000L - ) { - motion.centerOrientation - } else { - val timeConstant = if (motion.tripodMode) { - max(useCase.smoothingTimeSeconds, 0.72) - } else { - useCase.smoothingTimeSeconds + fun dequeueFrame(): StabilizationFrame? { + if (!active) return null + while (true) { + val next = coordinator.nextNativeResult(lastConsumedSequence) ?: return null + lastConsumedSequence = next.sequence + val timestampNs = when (val result = next.result) { + is MgcEisNativeEngine.FrameResult.Stabilized -> result.sensorTimestampNs + is MgcEisNativeEngine.FrameResult.Dropped -> result.sensorTimestampNs } - val alpha = 1.0 - exp(-frameDeltaNs.toDouble() * 1.0e-9 / timeConstant) - Quaternion.slerp(currentSmooth, motion.centerOrientation, alpha.coerceIn(0.0, 1.0)) - } - smoothedOrientation = nextSmooth - lastFrameTimestampNs = timestampNs - - val focal = resolveNormalizedFocalLength( - calibration = motion.calibration, - metadata = motion.metadata, - axesSwapped = textureAxesSwapped, - ) - val rowCorrections = motion.rowOrientations.map { rowOrientation -> - val outputToInput = rowOrientation.inverse() * nextSmooth - mapDeviceRotationToDisplay( - Quaternion.log(outputToInput), - displayRotationDegrees, - ) - } - val safeStrength = constrainStrength( - rotations = rowCorrections, - focalX = focal.first, - focalY = focal.second, - stabilizedCrop = stabilizedCrop, - availableCrop = baseCropRect, - ) - val matrices = FloatArray(STABILIZATION_ROW_COUNT * 9) - rowCorrections.forEachIndexed { index, rotationVector -> - val homography = homographyForRotation( - rotationVector = rotationVector * safeStrength.toDouble(), - focalX = focal.first, - focalY = focal.second, - ) - homography.writeColumnMajor(matrices, index * 9) - } - return AlgorithmicStabilizationTransform( - rowHomographies = matrices, - cropRect = stabilizedCrop, - hasPoseCoverage = true, - appliedStrength = safeStrength, - tripodMode = motion.tripodMode, - ) - } - - private fun constrainStrength( - rotations: List, - focalX: Double, - focalY: Double, - stabilizedCrop: FloatArray, - availableCrop: FloatArray, - ): Float { - fun safe(strength: Double): Boolean { - rotations.forEach { rotation -> - val h = homographyForRotation(rotation * strength, focalX, focalY) - if (!cornersStayInside(h, stabilizedCrop, availableCrop)) return false + val image = coordinator.acquireImageForSession(sessionId, timestampNs) + if (image == null) { + if (next.sequence <= 3L || next.sequence % 30L == 0L) { + PLog.i( + TAG, + "MGC session skipped unbuffered result sequence=${next.sequence}, " + + "timestamp=$timestampNs", + ) + } + continue } - return true - } - - if (safe(1.0)) return 1f - var low = 0.0 - var high = 1.0 - repeat(10) { - val middle = (low + high) * 0.5 - if (safe(middle)) low = middle else high = middle - } - return low.toFloat() - } - - private fun identityTransform( - crop: FloatArray, - hasCoverage: Boolean, - ): AlgorithmicStabilizationTransform { - val matrices = FloatArray(STABILIZATION_ROW_COUNT * 9) - repeat(STABILIZATION_ROW_COUNT) { index -> - Mat3.IDENTITY.writeColumnMajor(matrices, index * 9) - } - return AlgorithmicStabilizationTransform( - rowHomographies = matrices, - cropRect = crop, - hasPoseCoverage = hasCoverage, - appliedStrength = 0f, - tripodMode = false, - ) - } - } -} - -private fun resolveNormalizedFocalLength( - calibration: CameraCalibration, - metadata: FrameMetadata?, - axesSwapped: Boolean, -): Pair { - val physical = calibration.physicalSizeMm - val focalMm = metadata?.focalLengthMm?.toDouble()?.takeIf { it > 0.0 } - if (physical == null || focalMm == null || physical.width <= 0f || physical.height <= 0f) { - return 1.20 to 1.20 - } - - val active = calibration.activeArray - val crop = metadata.cropRegion ?: active - val zoom = metadata.zoomRatio.toDouble().coerceAtLeast(1.0) - val effectiveWidth = min(crop.width().toDouble(), active.width().toDouble() / zoom).coerceAtLeast(1.0) - val effectiveHeight = min(crop.height().toDouble(), active.height().toDouble() / zoom).coerceAtLeast(1.0) - val horizontal = focalMm / physical.width.toDouble() * active.width().toDouble() / effectiveWidth - val vertical = focalMm / physical.height.toDouble() * active.height().toDouble() / effectiveHeight - return if (axesSwapped) vertical to horizontal else horizontal to vertical -} - -private fun mapDeviceRotationToDisplay(rotation: Vec3, displayRotationDegrees: Int): Vec3 { - val normalizedRotation = ((displayRotationDegrees % 360) + 360) % 360 - val radians = Math.toRadians(normalizedRotation.toDouble()) - val c = cos(radians) - val s = sin(radians) - val screenRight = Vec3(c, -s, 0.0) - val screenDown = Vec3(-s, -c, 0.0) - val sceneForward = Vec3(0.0, 0.0, -1.0) - return Vec3( - rotation.dot(screenRight), - rotation.dot(screenDown), - rotation.dot(sceneForward), - ) -} - -private fun homographyForRotation( - rotationVector: Vec3, - focalX: Double, - focalY: Double, -): Mat3 { - val safeFocalX = focalX.coerceIn(0.25, 20.0) - val safeFocalY = focalY.coerceIn(0.25, 20.0) - val intrinsics = Mat3( - doubleArrayOf( - safeFocalX, 0.0, 0.5, - 0.0, safeFocalY, 0.5, - 0.0, 0.0, 1.0, - ) - ) - val rotation = Quaternion.fromRotationVector(rotationVector).toMatrix3() - return intrinsics * rotation * intrinsics.inverse() -} - -private fun cornersStayInside( - homography: Mat3, - sourceCrop: FloatArray, - bounds: FloatArray, -): Boolean { - val corners = arrayOf( - Vec2(sourceCrop[0].toDouble(), sourceCrop[1].toDouble()), - Vec2(sourceCrop[2].toDouble(), sourceCrop[1].toDouble()), - Vec2(sourceCrop[0].toDouble(), sourceCrop[3].toDouble()), - Vec2(sourceCrop[2].toDouble(), sourceCrop[3].toDouble()), - ) - return corners.all { corner -> - val point = homography.transform(corner) ?: return@all false - point.x >= bounds[0] && point.x <= bounds[2] && - point.y >= bounds[1] && point.y <= bounds[3] - } -} - -private fun insetCrop(crop: FloatArray, marginFraction: Float): FloatArray { - val margin = marginFraction.coerceIn(0f, 0.24f) - val widthInset = (crop[2] - crop[0]) * margin - val heightInset = (crop[3] - crop[1]) * margin - return floatArrayOf( - crop[0] + widthInset, - crop[1] + heightInset, - crop[2] - widthInset, - crop[3] - heightInset, - ) -} - -private data class Vec2(val x: Double, val y: Double) - -private data class Vec3(val x: Double, val y: Double, val z: Double) { - operator fun plus(other: Vec3) = Vec3(x + other.x, y + other.y, z + other.z) - operator fun times(scale: Double) = Vec3(x * scale, y * scale, z * scale) - fun dot(other: Vec3): Double = x * other.x + y * other.y + z * other.z - fun length(): Double = sqrt(dot(this)) - - companion object { - val ZERO = Vec3(0.0, 0.0, 0.0) - } -} - -private data class Quaternion( - val w: Double, - val x: Double, - val y: Double, - val z: Double, -) { - operator fun times(other: Quaternion): Quaternion = Quaternion( - w = w * other.w - x * other.x - y * other.y - z * other.z, - x = w * other.x + x * other.w + y * other.z - z * other.y, - y = w * other.y - x * other.z + y * other.w + z * other.x, - z = w * other.z + x * other.y - y * other.x + z * other.w, - ) - - fun normalized(): Quaternion { - val magnitude = sqrt(w * w + x * x + y * y + z * z) - return if (magnitude <= 1.0e-12) IDENTITY else Quaternion( - w / magnitude, - x / magnitude, - y / magnitude, - z / magnitude, - ) - } - - fun inverse(): Quaternion = Quaternion(w, -x, -y, -z).normalized() - - fun toMatrix3(): Mat3 { - val q = normalized() - val xx = q.x * q.x - val yy = q.y * q.y - val zz = q.z * q.z - val xy = q.x * q.y - val xz = q.x * q.z - val yz = q.y * q.z - val wx = q.w * q.x - val wy = q.w * q.y - val wz = q.w * q.z - return Mat3( - doubleArrayOf( - 1.0 - 2.0 * (yy + zz), 2.0 * (xy - wz), 2.0 * (xz + wy), - 2.0 * (xy + wz), 1.0 - 2.0 * (xx + zz), 2.0 * (yz - wx), - 2.0 * (xz - wy), 2.0 * (yz + wx), 1.0 - 2.0 * (xx + yy), - ) - ) - } - - companion object { - val IDENTITY = Quaternion(1.0, 0.0, 0.0, 0.0) - - fun fromRotationVector(vector: Vec3): Quaternion { - val angle = vector.length() - if (angle <= 1.0e-12) return IDENTITY - val half = angle * 0.5 - val scale = sin(half) / angle - return Quaternion(cos(half), vector.x * scale, vector.y * scale, vector.z * scale) - .normalized() - } - - fun log(value: Quaternion): Vec3 { - val q = value.normalized().let { if (it.w < 0.0) Quaternion(-it.w, -it.x, -it.y, -it.z) else it } - val vectorLength = sqrt(q.x * q.x + q.y * q.y + q.z * q.z) - if (vectorLength <= 1.0e-12) return Vec3.ZERO - val angle = 2.0 * kotlin.math.atan2(vectorLength, q.w.coerceIn(-1.0, 1.0)) - val scale = angle / vectorLength - return Vec3(q.x * scale, q.y * scale, q.z * scale) - } - - fun slerp(from: Quaternion, to: Quaternion, amount: Double): Quaternion { - val a = from.normalized() - var b = to.normalized() - var dot = a.w * b.w + a.x * b.x + a.y * b.y + a.z * b.z - if (dot < 0.0) { - b = Quaternion(-b.w, -b.x, -b.y, -b.z) - dot = -dot - } - val t = amount.coerceIn(0.0, 1.0) - if (dot > 0.9995) { - return Quaternion( - a.w + (b.w - a.w) * t, - a.x + (b.x - a.x) * t, - a.y + (b.y - a.y) * t, - a.z + (b.z - a.z) * t, - ).normalized() - } - val theta = acos(dot.coerceIn(-1.0, 1.0)) - val denominator = sin(theta) - val fromWeight = sin((1.0 - t) * theta) / denominator - val toWeight = sin(t * theta) / denominator - return Quaternion( - a.w * fromWeight + b.w * toWeight, - a.x * fromWeight + b.x * toWeight, - a.y * fromWeight + b.y * toWeight, - a.z * fromWeight + b.z * toWeight, - ).normalized() - } - } -} - -private class Mat3(private val values: DoubleArray) { - init { - require(values.size == 9) - } - - operator fun times(other: Mat3): Mat3 { - val out = DoubleArray(9) - for (row in 0..2) { - for (column in 0..2) { - out[row * 3 + column] = (0..2).sumOf { index -> - values[row * 3 + index] * other.values[index * 3 + column] + if (next.sequence <= 3L || next.sequence % 30L == 0L) { + PLog.i( + TAG, + "MGC session matched result sequence=${next.sequence}, " + + "latest=${coordinator.currentResultSequence()}, " + + "timestamp=$timestampNs", + ) + } + return when (val result = next.result) { + is MgcEisNativeEngine.FrameResult.Dropped -> + StabilizationFrame(timestampNs, null, image) + is MgcEisNativeEngine.FrameResult.Stabilized -> StabilizationFrame( + timestampNs = timestampNs, + transform = AlgorithmicStabilizationTransform( + timestampNs = timestampNs, + rowHomographies = result.rowHomographies, + cropRect = floatArrayOf(0f, 0f, 1f, 1f), + hasPoseCoverage = true, + appliedStrength = result.appliedStrength, + tripodMode = result.tripodMode, + ), + image = image, + ) } } } - return Mat3(out) - } - fun inverse(): Mat3 { - val a = values[0] - val b = values[1] - val c = values[2] - val d = values[3] - val e = values[4] - val f = values[5] - val g = values[6] - val h = values[7] - val i = values[8] - val determinant = a * (e * i - f * h) - b * (d * i - f * g) + c * (d * h - e * g) - if (kotlin.math.abs(determinant) <= 1.0e-12) return IDENTITY - val reciprocal = 1.0 / determinant - return Mat3( - doubleArrayOf( - (e * i - f * h) * reciprocal, - (c * h - b * i) * reciprocal, - (b * f - c * e) * reciprocal, - (f * g - d * i) * reciprocal, - (a * i - c * g) * reciprocal, - (c * d - a * f) * reciprocal, - (d * h - e * g) * reciprocal, - (b * g - a * h) * reciprocal, - (a * e - b * d) * reciprocal, - ) - ) - } - - fun transform(point: Vec2): Vec2? { - val denominator = values[6] * point.x + values[7] * point.y + values[8] - if (kotlin.math.abs(denominator) <= 1.0e-9) return null - return Vec2( - x = (values[0] * point.x + values[1] * point.y + values[2]) / denominator, - y = (values[3] * point.x + values[4] * point.y + values[5]) / denominator, - ) - } - - fun writeColumnMajor(destination: FloatArray, offset: Int) { - for (row in 0..2) { - for (column in 0..2) { - destination[offset + column * 3 + row] = values[row * 3 + column].toFloat() - } + /** + * Number of native results not yet consumed by this session. + * + * GLSurfaceView collapses repeated requestRender() calls into one draw. The preview + * renderer uses this authoritative cursor distance after each draw to request the next + * draw until every timestamped result has been presented exactly once. + */ + @Synchronized + fun pendingResultCount(): Int = if (active) { + coordinator.pendingNativeResultCount(lastConsumedSequence) + } else { + 0 } } +} - companion object { - val IDENTITY = Mat3( - doubleArrayOf( - 1.0, 0.0, 0.0, - 0.0, 1.0, 0.0, - 0.0, 0.0, 1.0, - ) - ) +private fun remapMgcGyro( + x: Float, + y: Float, + z: Float, + calibration: CameraCalibration?, +): Triple { + calibration ?: return Triple(x, y, z) + val orientation = Math.floorMod(calibration.sensorOrientationDegrees, 360) + val frontFacing = calibration.lensFacing == CameraCharacteristics.LENS_FACING_FRONT + return when { + (frontFacing && orientation == 90) || (!frontFacing && orientation == 270) -> + Triple(-x, -y, z) + frontFacing && orientation == 0 -> Triple(y, -x, z) + else -> Triple(x, y, z) } } -private fun absoluteDifference(a: Long, b: Long): Long { - return if (a >= b) a - b else b - a +internal fun remapMgcGyroForTest( + x: Double, + y: Double, + z: Double, + sensorOrientationDegrees: Int, + frontFacing: Boolean, +): Triple { + val calibration = CameraCalibration( + activeArray = Rect(0, 0, 1, 1), + physicalSizeMm = SizeF(1f, 1f), + lensFacing = if (frontFacing) { + CameraCharacteristics.LENS_FACING_FRONT + } else { + CameraCharacteristics.LENS_FACING_BACK + }, + sensorOrientationDegrees = sensorOrientationDegrees, + timestampSource = CameraCharacteristics.SENSOR_INFO_TIMESTAMP_SOURCE_REALTIME, + ) + return remapMgcGyro(x.toFloat(), y.toFloat(), z.toFloat(), calibration).let { + Triple(it.first.toDouble(), it.second.toDouble(), it.third.toDouble()) + } +} + +private fun timestampLagMs(currentTimestampNs: Long, sourceTimestampNs: Long): String = + if (sourceTimestampNs <= 0L) { + "unset" + } else { + ((currentTimestampNs - sourceTimestampNs) / 1_000_000.0).toString() + } + +private fun absoluteTimestampDifference(first: Long, second: Long): Long = + if (first >= second) first - second else second - first + +private fun trimOldest(map: LinkedHashMap, maximumSize: Int) { + while (map.size > maximumSize) { + val oldest = map.keys.firstOrNull() ?: return + map.remove(oldest) + } } diff --git a/app/src/main/java/com/hinnka/mycamera/ui/camera/CameraGLSurfaceView.kt b/app/src/main/java/com/hinnka/mycamera/ui/camera/CameraGLSurfaceView.kt index 74759851..3cb9db69 100644 --- a/app/src/main/java/com/hinnka/mycamera/ui/camera/CameraGLSurfaceView.kt +++ b/app/src/main/java/com/hinnka/mycamera/ui/camera/CameraGLSurfaceView.kt @@ -17,7 +17,11 @@ import com.hinnka.mycamera.lut.PreviewCaptureSource import com.hinnka.mycamera.model.ColorRecipeParams import com.hinnka.mycamera.model.ColorPaletteMapper import com.hinnka.mycamera.screencapture.PhantomPipCrop +import com.hinnka.mycamera.stabilization.DEFAULT_VIDEO_STABILIZATION_LOOKAHEAD import com.hinnka.mycamera.stabilization.RealtimeStabilizationCoordinator +import com.hinnka.mycamera.stabilization.StabilizationUseCase +import com.hinnka.mycamera.stabilization.normalizeStabilizationLookahead +import com.hinnka.mycamera.stabilization.normalizeStabilizationStrength import com.hinnka.mycamera.utils.PLog import com.hinnka.mycamera.video.VideoLogProfile @@ -38,7 +42,8 @@ class CameraGLSurfaceView @JvmOverloads constructor( private val renderer: LutRenderer = LutRenderer(context.applicationContext) private var currentStabilizationCoordinator: RealtimeStabilizationCoordinator? = null - private var currentPhotoPreviewStabilizationEnabled = false + private var currentPreviewStabilizationUseCase: StabilizationUseCase? = null + private var currentPreviewStabilizationStrength = 0f var onHistogramUpdated: ((IntArray) -> Unit)? = null var onMeteringUpdated: ((Double, Double) -> Unit)? = null @@ -166,11 +171,26 @@ class CameraGLSurfaceView @JvmOverloads constructor( } } - fun setPhotoPreviewStabilizationEnabled(enabled: Boolean) { - if (currentPhotoPreviewStabilizationEnabled == enabled) return - currentPhotoPreviewStabilizationEnabled = enabled + private var currentPreviewStabilizationLookahead = DEFAULT_VIDEO_STABILIZATION_LOOKAHEAD + + fun setPreviewStabilization( + useCase: StabilizationUseCase?, + strength: Float, + lookaheadFrames: Int = DEFAULT_VIDEO_STABILIZATION_LOOKAHEAD, + ) { + val normalizedStrength = normalizeStabilizationStrength(strength) + val normalizedLookahead = normalizeStabilizationLookahead(lookaheadFrames) + if (currentPreviewStabilizationUseCase == useCase && + kotlin.math.abs(currentPreviewStabilizationStrength - normalizedStrength) <= 0.0001f && + currentPreviewStabilizationLookahead == normalizedLookahead + ) { + return + } + currentPreviewStabilizationUseCase = useCase + currentPreviewStabilizationStrength = normalizedStrength + currentPreviewStabilizationLookahead = normalizedLookahead queueEvent { - renderer.setPhotoPreviewStabilizationEnabled(enabled) + renderer.setPreviewStabilization(useCase, normalizedStrength, normalizedLookahead) requestRender() } } diff --git a/app/src/main/java/com/hinnka/mycamera/ui/camera/CameraPreviewGL.kt b/app/src/main/java/com/hinnka/mycamera/ui/camera/CameraPreviewGL.kt index 0693991f..3e0e4297 100644 --- a/app/src/main/java/com/hinnka/mycamera/ui/camera/CameraPreviewGL.kt +++ b/app/src/main/java/com/hinnka/mycamera/ui/camera/CameraPreviewGL.kt @@ -24,7 +24,9 @@ import com.hinnka.mycamera.camera.MeteringMode import com.hinnka.mycamera.lut.LutConfig import com.hinnka.mycamera.model.ColorRecipeParams import com.hinnka.mycamera.preview.EyeFocusPreviewFrame +import com.hinnka.mycamera.stabilization.DEFAULT_VIDEO_STABILIZATION_LOOKAHEAD import com.hinnka.mycamera.stabilization.RealtimeStabilizationCoordinator +import com.hinnka.mycamera.stabilization.StabilizationUseCase import com.hinnka.mycamera.ui.components.FocusIndicator import com.hinnka.mycamera.utils.OrientationObserver import com.hinnka.mycamera.video.CaptureMode @@ -72,6 +74,9 @@ fun CameraPreviewGL( focusPeakingEnabled: Boolean = true, stabilizationCoordinator: RealtimeStabilizationCoordinator? = null, photoPreviewStabilizationEnabled: Boolean = false, + videoPreviewStabilizationEnabled: Boolean = false, + videoPreviewStabilizationStrength: Float = 0f, + videoPreviewStabilizationLookahead: Int = DEFAULT_VIDEO_STABILIZATION_LOOKAHEAD, modifier: Modifier = Modifier ) { val rotationDegrees = OrientationObserver.rotationDegrees @@ -222,8 +227,25 @@ fun CameraPreviewGL( glSurfaceView.setCalibrationOffset(calibrationOffset) glSurfaceView.setCaptureAspectRatio(aspectRatio) glSurfaceView.setStabilizationCoordinator(stabilizationCoordinator) - glSurfaceView.setPhotoPreviewStabilizationEnabled( - photoPreviewStabilizationEnabled && captureMode == CaptureMode.PHOTO + val previewStabilizationUseCase = when { + captureMode == CaptureMode.VIDEO && + videoPreviewStabilizationEnabled -> StabilizationUseCase.VIDEO + captureMode == CaptureMode.PHOTO && + photoPreviewStabilizationEnabled -> StabilizationUseCase.PHOTO_PREVIEW + else -> null + } + glSurfaceView.setPreviewStabilization( + useCase = previewStabilizationUseCase, + strength = if (previewStabilizationUseCase == StabilizationUseCase.VIDEO) { + videoPreviewStabilizationStrength + } else { + StabilizationUseCase.PHOTO_PREVIEW.defaultStrength + }, + lookaheadFrames = if (previewStabilizationUseCase == StabilizationUseCase.VIDEO) { + videoPreviewStabilizationLookahead + } else { + DEFAULT_VIDEO_STABILIZATION_LOOKAHEAD + }, ) // 当 SurfaceTexture 准备好且尺寸已就绪时,通知外部打开相机。 diff --git a/app/src/main/java/com/hinnka/mycamera/ui/camera/CameraScreen.kt b/app/src/main/java/com/hinnka/mycamera/ui/camera/CameraScreen.kt index e90fb74e..acc974e4 100644 --- a/app/src/main/java/com/hinnka/mycamera/ui/camera/CameraScreen.kt +++ b/app/src/main/java/com/hinnka/mycamera/ui/camera/CameraScreen.kt @@ -82,6 +82,7 @@ import com.hinnka.mycamera.video.VideoAspectRatio import com.hinnka.mycamera.video.VideoFpsPreset import com.hinnka.mycamera.video.VideoLogProfile import com.hinnka.mycamera.video.VideoResolutionPreset +import com.hinnka.mycamera.video.VideoStabilizationMode import kotlinx.coroutines.Job import kotlinx.coroutines.delay import kotlinx.coroutines.launch @@ -1194,6 +1195,13 @@ fun CameraScreen( stabilizationCoordinator = viewModel.realtimeStabilizationCoordinator, photoPreviewStabilizationEnabled = state.photoPreviewStabilizationEnabled, + videoPreviewStabilizationEnabled = + state.videoConfig.stabilizationMode == + VideoStabilizationMode.ENHANCED, + videoPreviewStabilizationStrength = + state.videoConfig.enhancedStabilizationStrength, + videoPreviewStabilizationLookahead = + state.videoConfig.enhancedStabilizationLookahead, modifier = Modifier.fillMaxSize() ) } diff --git a/app/src/main/java/com/hinnka/mycamera/ui/settings/SettingsScreen.kt b/app/src/main/java/com/hinnka/mycamera/ui/settings/SettingsScreen.kt index 23157402..4bce9bc5 100644 --- a/app/src/main/java/com/hinnka/mycamera/ui/settings/SettingsScreen.kt +++ b/app/src/main/java/com/hinnka/mycamera/ui/settings/SettingsScreen.kt @@ -139,6 +139,12 @@ import com.hinnka.mycamera.raw.RawNoiseProfileManager import com.hinnka.mycamera.raw.RawWhiteLevelCorrection import com.hinnka.mycamera.raw.HncsProfileManager import com.hinnka.mycamera.raw.SpectralFilmSelection +import com.hinnka.mycamera.stabilization.DEFAULT_VIDEO_STABILIZATION_LOOKAHEAD +import com.hinnka.mycamera.stabilization.DEFAULT_VIDEO_STABILIZATION_STRENGTH +import com.hinnka.mycamera.stabilization.MIN_VIDEO_STABILIZATION_LOOKAHEAD +import com.hinnka.mycamera.stabilization.MAX_VIDEO_STABILIZATION_LOOKAHEAD +import com.hinnka.mycamera.stabilization.normalizeStabilizationLookahead +import com.hinnka.mycamera.stabilization.normalizeStabilizationStrength import com.hinnka.mycamera.ui.camera.LutEditBottomSheet import com.hinnka.mycamera.ui.camera.LutEditorTarget import com.hinnka.mycamera.ui.camera.autoRotate @@ -446,6 +452,12 @@ fun SettingsScreen( var rawMaxChromaNoiseReductionUi by remember { mutableStateOf(rawMaxChromaNoiseReduction) } var windowScreenBrightnessUi by remember { mutableStateOf(windowScreenBrightness ?: 1f) } var windowScreenBrightnessEnabled by remember { mutableStateOf(windowScreenBrightness != null) } + var videoEnhancedStabilizationStrengthUi by remember { + mutableStateOf(userPreferences.videoEnhancedStabilizationStrength) + } + var videoEnhancedStabilizationLookaheadUi by remember { + mutableStateOf(userPreferences.videoEnhancedStabilizationLookahead) + } var showAspectRatioDialog by remember { mutableStateOf(false) } var showAddIszLensDialog by remember { mutableStateOf(false) } var showCustomVendorKeysDialog by remember { mutableStateOf(false) } @@ -538,6 +550,16 @@ fun SettingsScreen( } } + LaunchedEffect(userPreferences.videoEnhancedStabilizationStrength) { + videoEnhancedStabilizationStrengthUi = + userPreferences.videoEnhancedStabilizationStrength + } + + LaunchedEffect(userPreferences.videoEnhancedStabilizationLookahead) { + videoEnhancedStabilizationLookaheadUi = + userPreferences.videoEnhancedStabilizationLookahead + } + fun commitRawSliderValues() { isRawSliderAdjusting = false viewModel.setRawExposureCompensation(rawExposureCompensationUi) @@ -1595,6 +1617,87 @@ fun SettingsScreen( modifier = Modifier.padding(vertical = 8.dp) ) + val stabilizationStrengthValueFormat = stringResource( + R.string.settings_video_stabilization_strength_value + ) + SliderSettingItem( + title = stringResource( + R.string.settings_video_stabilization_strength + ), + description = stringResource( + R.string.settings_video_stabilization_strength_description + ), + value = videoEnhancedStabilizationStrengthUi, + valueRange = 0f..1f, + resetValue = DEFAULT_VIDEO_STABILIZATION_STRENGTH, + onResetValue = { strength -> + videoEnhancedStabilizationStrengthUi = strength + viewModel.setVideoEnhancedStabilizationStrength(strength) + }, + onValueChange = { strength -> + videoEnhancedStabilizationStrengthUi = + normalizeStabilizationStrength(strength) + }, + onValueChangeFinished = { + viewModel.setVideoEnhancedStabilizationStrength( + videoEnhancedStabilizationStrengthUi + ) + }, + valueTextFormatter = { strength -> + String.format( + stabilizationStrengthValueFormat, + (strength * 100f).roundToInt() + ) + }, + enabled = viewModel.isAlgorithmicStabilizationSupported, + ) + + HorizontalDivider( + color = Color.White.copy(alpha = 0.1f), + modifier = Modifier.padding(vertical = 8.dp) + ) + + val stabilizationLookaheadValueFormat = stringResource( + R.string.settings_video_stabilization_lookahead_value + ) + SliderSettingItem( + title = stringResource( + R.string.settings_video_stabilization_lookahead + ), + description = stringResource( + R.string.settings_video_stabilization_lookahead_description + ), + value = videoEnhancedStabilizationLookaheadUi.toFloat(), + valueRange = MIN_VIDEO_STABILIZATION_LOOKAHEAD.toFloat()..MAX_VIDEO_STABILIZATION_LOOKAHEAD.toFloat(), + resetValue = DEFAULT_VIDEO_STABILIZATION_LOOKAHEAD.toFloat(), + onResetValue = { lookahead -> + val intLookahead = lookahead.roundToInt() + videoEnhancedStabilizationLookaheadUi = intLookahead + viewModel.setVideoEnhancedStabilizationLookahead(intLookahead) + }, + onValueChange = { lookahead -> + videoEnhancedStabilizationLookaheadUi = + normalizeStabilizationLookahead(lookahead.roundToInt()) + }, + onValueChangeFinished = { + viewModel.setVideoEnhancedStabilizationLookahead( + videoEnhancedStabilizationLookaheadUi + ) + }, + valueTextFormatter = { lookahead -> + String.format( + stabilizationLookaheadValueFormat, + lookahead.roundToInt() + ) + }, + enabled = viewModel.isAlgorithmicStabilizationSupported, + ) + + HorizontalDivider( + color = Color.White.copy(alpha = 0.1f), + modifier = Modifier.padding(vertical = 8.dp) + ) + SwitchSettingItem( title = stringResource(R.string.settings_separate_video_lut), description = stringResource(R.string.settings_separate_video_lut_description), diff --git a/app/src/main/java/com/hinnka/mycamera/video/VideoCapabilitiesResolver.kt b/app/src/main/java/com/hinnka/mycamera/video/VideoCapabilitiesResolver.kt index e2acfe0b..00be072f 100644 --- a/app/src/main/java/com/hinnka/mycamera/video/VideoCapabilitiesResolver.kt +++ b/app/src/main/java/com/hinnka/mycamera/video/VideoCapabilitiesResolver.kt @@ -101,12 +101,7 @@ object VideoCapabilitiesResolver { } val enhancedCameraInputSize = cameraInputSizesByResolution[VideoResolutionPreset.FHD_1080P] val enhancedStabilizationAvailable = algorithmicStabilizationSupported && - enhancedCameraInputSize != null && - resolveAvailableFps( - characteristics = characteristics, - cameraInputSize = enhancedCameraInputSize, - previewSize = previewSize - ).contains(VideoFpsPreset.FPS_30) + enhancedCameraInputSize != null if (enhancedStabilizationAvailable) { availableStabilizationModes.add(VideoStabilizationMode.ENHANCED) } diff --git a/app/src/main/java/com/hinnka/mycamera/video/VideoRecorder.kt b/app/src/main/java/com/hinnka/mycamera/video/VideoRecorder.kt index 8f3ba75a..7d5f595c 100644 --- a/app/src/main/java/com/hinnka/mycamera/video/VideoRecorder.kt +++ b/app/src/main/java/com/hinnka/mycamera/video/VideoRecorder.kt @@ -20,7 +20,11 @@ import android.view.Surface import androidx.core.app.ActivityCompat import com.hinnka.mycamera.lut.RealtimeVideoRenderer import com.hinnka.mycamera.lut.VideoColorEffectLayer +import com.hinnka.mycamera.stabilization.DEFAULT_VIDEO_STABILIZATION_LOOKAHEAD +import com.hinnka.mycamera.stabilization.DEFAULT_VIDEO_STABILIZATION_STRENGTH import com.hinnka.mycamera.stabilization.RealtimeStabilizationCoordinator +import com.hinnka.mycamera.stabilization.normalizeStabilizationLookahead +import com.hinnka.mycamera.stabilization.normalizeStabilizationStrength import com.hinnka.mycamera.utils.PLog import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers @@ -122,6 +126,8 @@ class VideoRecorder( private var requestedCameraInputSize = Size(1920, 1080) private var requestedColorLayers: List = emptyList() private var requestedEnhancedStabilization = false + private var requestedEnhancedStabilizationStrength = DEFAULT_VIDEO_STABILIZATION_STRENGTH + private var requestedEnhancedStabilizationLookahead = DEFAULT_VIDEO_STABILIZATION_LOOKAHEAD private var cameraInputStarted = false private var hlgCameraInput = false private var requestedCameraTimestampSource = CameraCharacteristics.SENSOR_INFO_TIMESTAMP_SOURCE_UNKNOWN @@ -153,7 +159,7 @@ class VideoRecorder( private var activeAudioConfig = monoAudioConfig() private var lastMuxedVideoPresentationTimeUs = Long.MIN_VALUE private var lastMuxedAudioPresentationTimeUs = Long.MIN_VALUE - private var pendingRealtimeFrame = false + private var pendingRealtimeFrameCount = 0 private var renderLoopRunning = false private var statsWindowStartMs: Long = 0L private var statsIncomingFrames: Int = 0 @@ -188,6 +194,8 @@ class VideoRecorder( orientationHintDegrees: Int = 0, flipEncodedFrame: Boolean = false, enhancedStabilization: Boolean = false, + enhancedStabilizationStrength: Float = DEFAULT_VIDEO_STABILIZATION_STRENGTH, + enhancedStabilizationLookahead: Int = DEFAULT_VIDEO_STABILIZATION_LOOKAHEAD, recordingPath: VideoRecordingPath = VideoRecordingPath.DCIM_PHOTON, recordingTreeUri: String? = null, onError: ((String) -> Unit)? = null, @@ -210,6 +218,10 @@ class VideoRecorder( requestedCameraTimestampSource = cameraTimestampSource requestedFlipEncodedFrame = flipEncodedFrame requestedEnhancedStabilization = enhancedStabilization + requestedEnhancedStabilizationStrength = + normalizeStabilizationStrength(enhancedStabilizationStrength) + requestedEnhancedStabilizationLookahead = + normalizeStabilizationLookahead(enhancedStabilizationLookahead) requestedRecordingPath = recordingPath requestedRecordingTreeUri = recordingTreeUri?.takeIf { it.isNotBlank() } outputDateTakenMs = System.currentTimeMillis() @@ -247,7 +259,8 @@ class VideoRecorder( "output=${requestedOutputSize.width}x${requestedOutputSize.height} @ " + "${requestedFps}fps, orientationHint=$requestedOrientationHintDegrees, " + "enhancedStabilization=$requestedEnhancedStabilization, " + - "input=dedicated-surface-texture, " + + "stabilizationStrength=$requestedEnhancedStabilizationStrength, " + + "input=${if (requestedEnhancedStabilization) "timestamped-yuv" else "dedicated-surface-texture"}, " + "cameraTimestampSource=$requestedCameraTimestampSource, " + "path=${requestedRecordingPath.name}, uri=${requestedRecordingTreeUri?.take(48)}" ) @@ -257,6 +270,7 @@ class VideoRecorder( fun onCameraInputStarted(): Boolean { if (!isRecording || stopRequested || cameraInputStarted) return false cameraInputStarted = true + renderer?.resumeStabilization() if (audioEnabled) { startAudioLoop() } @@ -274,6 +288,7 @@ class VideoRecorder( audioRecordJob?.join() withContext(renderDispatcher) { drainRealtimeFrames(allowWhenStopping = true) + renderer?.pauseStabilization() signalVideoEndOfInputStream() } queueAudioEndOfStream() @@ -352,6 +367,8 @@ class VideoRecorder( encoderColorConfig = encoderColorConfig, stabilizationCoordinator = stabilizationCoordinator, enhancedStabilizationEnabled = requestedEnhancedStabilization, + enhancedStabilizationStrength = requestedEnhancedStabilizationStrength, + enhancedStabilizationLookahead = requestedEnhancedStabilizationLookahead, ) renderer = realtimeRenderer realtimeRenderer.initialize( @@ -368,10 +385,16 @@ class VideoRecorder( if (!isRecording || stopRequested || isPaused) return statsIncomingFrames += 1 synchronized(realtimeFrameLock) { - if (pendingRealtimeFrame) { + if (pendingRealtimeFrameCount > 0) { statsReplacedPendingFrames += 1 } - pendingRealtimeFrame = true + pendingRealtimeFrameCount = if (requestedEnhancedStabilization) { + pendingRealtimeFrameCount + 1 + } else { + // SurfaceTexture itself is latest-only; multiple callbacks before the GL + // consumer runs therefore represent one materializable OES frame. + 1 + } if (!renderLoopRunning) { renderLoopRunning = true scope.launch(renderDispatcher) { @@ -847,11 +870,11 @@ class VideoRecorder( private fun drainRealtimeFrames(allowWhenStopping: Boolean) { while (true) { val hasFrame = synchronized(realtimeFrameLock) { - if (!pendingRealtimeFrame) { + if (pendingRealtimeFrameCount <= 0) { renderLoopRunning = false return } - pendingRealtimeFrame = false + pendingRealtimeFrameCount -= 1 true } @@ -1371,7 +1394,7 @@ class VideoRecorder( activePauseStartTimeUs = UNSET_TIMESTAMP } synchronized(realtimeFrameLock) { - pendingRealtimeFrame = false + pendingRealtimeFrameCount = 0 renderLoopRunning = false } } diff --git a/app/src/main/java/com/hinnka/mycamera/video/VideoTypes.kt b/app/src/main/java/com/hinnka/mycamera/video/VideoTypes.kt index 80797b25..31305096 100644 --- a/app/src/main/java/com/hinnka/mycamera/video/VideoTypes.kt +++ b/app/src/main/java/com/hinnka/mycamera/video/VideoTypes.kt @@ -5,6 +5,8 @@ import android.os.Environment import android.util.Size import com.hinnka.mycamera.raw.ColorSpace import com.hinnka.mycamera.color.TransferCurve +import com.hinnka.mycamera.stabilization.DEFAULT_VIDEO_STABILIZATION_STRENGTH +import com.hinnka.mycamera.stabilization.DEFAULT_VIDEO_STABILIZATION_LOOKAHEAD import kotlin.math.max import kotlin.math.min import kotlin.math.roundToInt @@ -124,6 +126,8 @@ data class VideoConfig( val recordingPath: VideoRecordingPath = VideoRecordingPath.DCIM_PHOTON, val recordingTreeUri: String? = null, val stabilizationMode: VideoStabilizationMode = VideoStabilizationMode.OIS, + val enhancedStabilizationStrength: Float = DEFAULT_VIDEO_STABILIZATION_STRENGTH, + val enhancedStabilizationLookahead: Int = DEFAULT_VIDEO_STABILIZATION_LOOKAHEAD, val torchEnabled: Boolean = false, val lensLockEnabled: Boolean = false, val whiteBalanceLockEnabled: Boolean = false diff --git a/app/src/main/java/com/hinnka/mycamera/viewmodel/CameraViewModel.kt b/app/src/main/java/com/hinnka/mycamera/viewmodel/CameraViewModel.kt index 9cb23403..16a8f08e 100644 --- a/app/src/main/java/com/hinnka/mycamera/viewmodel/CameraViewModel.kt +++ b/app/src/main/java/com/hinnka/mycamera/viewmodel/CameraViewModel.kt @@ -2181,6 +2181,12 @@ class CameraViewModel(application: Application) : AndroidViewModel(application) cameraController.setVideoAudioInputId(it.videoAudioInputId) cameraController.setVideoRecordingPath(it.videoRecordingPath, it.videoRecordingTreeUri) cameraController.setVideoStabilizationMode(it.videoStabilizationMode) + cameraController.setVideoEnhancedStabilizationStrength( + it.videoEnhancedStabilizationStrength + ) + cameraController.setVideoEnhancedStabilizationLookahead( + it.videoEnhancedStabilizationLookahead + ) cameraController.setPhotoPreviewStabilizationEnabled( it.photoPreviewStabilizationEnabled ) @@ -2325,6 +2331,12 @@ class CameraViewModel(application: Application) : AndroidViewModel(application) cameraController.setVideoAudioInputId(prefs.videoAudioInputId) cameraController.setVideoRecordingPath(prefs.videoRecordingPath, prefs.videoRecordingTreeUri) cameraController.setVideoStabilizationMode(prefs.videoStabilizationMode) + cameraController.setVideoEnhancedStabilizationStrength( + prefs.videoEnhancedStabilizationStrength + ) + cameraController.setVideoEnhancedStabilizationLookahead( + prefs.videoEnhancedStabilizationLookahead + ) cameraController.setVideoTorchEnabled(prefs.videoTorchEnabled) cameraController.setVideoLensLockEnabled(prefs.videoLensLockEnabled) cameraController.setVideoWhiteBalanceLockEnabled(prefs.videoWhiteBalanceLockEnabled) @@ -3679,11 +3691,7 @@ class CameraViewModel(application: Application) : AndroidViewModel(application) reopenCamera() } viewModelScope.launch { - userPreferencesRepository.saveVideoStabilizationConfig( - mode = resolvedConfig.stabilizationMode, - resolution = resolvedConfig.resolution, - fps = resolvedConfig.fps, - ) + userPreferencesRepository.saveVideoStabilizationMode(resolvedConfig.stabilizationMode) } } @@ -3694,6 +3702,20 @@ class CameraViewModel(application: Application) : AndroidViewModel(application) } } + fun setVideoEnhancedStabilizationStrength(strength: Float) { + cameraController.setVideoEnhancedStabilizationStrength(strength) + viewModelScope.launch { + userPreferencesRepository.saveVideoEnhancedStabilizationStrength(strength) + } + } + + fun setVideoEnhancedStabilizationLookahead(lookahead: Int) { + cameraController.setVideoEnhancedStabilizationLookahead(lookahead) + viewModelScope.launch { + userPreferencesRepository.saveVideoEnhancedStabilizationLookahead(lookahead) + } + } + fun setVideoLogProfile(logProfile: VideoLogProfile) { cameraController.setVideoLogProfile(logProfile) reopenCamera() diff --git a/app/src/main/res/values-b+zh+Hant/strings.xml b/app/src/main/res/values-b+zh+Hant/strings.xml index 09a758d9..353fe878 100644 --- a/app/src/main/res/values-b+zh+Hant/strings.xml +++ b/app/src/main/res/values-b+zh+Hant/strings.xml @@ -193,11 +193,17 @@ 鎖定鏡頭 影片錄製過程中變焦不切換鏡頭。 預設影片防震模式 - 選擇進入影片模式時使用的防震方式。EIS+ 在後置相機使用陀螺儀與滾動快門校正,並會將錄影規格切換為 1080p/30 fps。 + 選擇進入影片模式時使用的防震方式。EIS+ 在後置相機使用陀螺儀與滾動快門校正。 關閉 電子防震 (EIS) 光學防震 (OIS) 增強防震 (EIS+) + EIS+ 防震強度 + 數值越高,套用的姿態修正越完整;數值越低,畫面越貼近手機移動。下次開始錄影時生效。 + %1$d%% + EIS+ 前瞻影格數 + 影格數越少,畫面延遲越低、跟手性越強;影格數越多,畫面防震越平滑穩定。預設為 7 幀。 + %1$d 幀 鎖定白平衡 影片錄製過程中鎖定白平衡。 畫質與性能 diff --git a/app/src/main/res/values-zh-rCN/strings.xml b/app/src/main/res/values-zh-rCN/strings.xml index 551b0007..a264c9d4 100644 --- a/app/src/main/res/values-zh-rCN/strings.xml +++ b/app/src/main/res/values-zh-rCN/strings.xml @@ -193,11 +193,17 @@ 锁定镜头 视频录制过程中变焦不切换镜头。 默认视频防抖模式 - 选择进入视频模式时使用的防抖方式。EIS+ 在后摄使用陀螺仪和滚动快门校正,并会将录像规格切换为 1080p/30 fps。 + 选择进入视频模式时使用的防抖方式。EIS+ 在后摄使用陀螺仪和滚动快门校正。 关闭 电子防抖 (EIS) 光学防抖 (OIS) 增强防抖 (EIS+) + EIS+ 防抖强度 + 数值越高,应用的姿态修正越完整;数值越低,画面越贴近手机移动。下次开始录像时生效。 + %1$d%% + EIS+ 前瞻帧数 + 帧数越少,画面延时越低、跟手性越强;帧数越多,画面防抖越平滑稳定。默认为 7 帧。 + %1$d 帧 锁定白平衡 视频录制过程中锁定白平衡。 画质与性能 diff --git a/app/src/main/res/values-zh-rHK/strings.xml b/app/src/main/res/values-zh-rHK/strings.xml index 7e413be9..7cae1074 100644 --- a/app/src/main/res/values-zh-rHK/strings.xml +++ b/app/src/main/res/values-zh-rHK/strings.xml @@ -193,11 +193,17 @@ 鎖定鏡頭 影片錄製過程中變焦不切換鏡頭。 預設影片防震模式 - 選擇進入影片模式時使用的防震方式。EIS+ 在後置相機使用陀螺儀與滾動快門校正,並會將錄影規格切換為 1080p/30 fps。 + 選擇進入影片模式時使用的防震方式。EIS+ 在後置相機使用陀螺儀與滾動快門校正。 關閉 電子防震 (EIS) 光學防震 (OIS) 增強防震 (EIS+) + EIS+ 防震強度 + 數值越高,套用的姿態修正越完整;數值越低,畫面越貼近手機移動。下次開始錄影時生效。 + %1$d%% + EIS+ 前瞻影格數 + 影格數越少,畫面延遲越低、跟手性越強;影格數越多,畫面防震越平滑穩定。預設為 7 幀。 + %1$d 幀 鎖定白平衡 影片錄製過程中鎖定白平衡。 畫質與性能 diff --git a/app/src/main/res/values-zh-rTW/strings.xml b/app/src/main/res/values-zh-rTW/strings.xml index 52c3f01d..cc0ff3e1 100644 --- a/app/src/main/res/values-zh-rTW/strings.xml +++ b/app/src/main/res/values-zh-rTW/strings.xml @@ -193,11 +193,17 @@ 鎖定鏡頭 影片錄製過程中變焦不切換鏡頭。 預設影片防震模式 - 選擇進入影片模式時使用的防震方式。EIS+ 在後置相機使用陀螺儀與滾動快門校正,並會將錄影規格切換為 1080p/30 fps。 + 選擇進入影片模式時使用的防震方式。EIS+ 在後置相機使用陀螺儀與滾動快門校正。 關閉 電子防震 (EIS) 光學防震 (OIS) 增強防震 (EIS+) + EIS+ 防震強度 + 數值越高,套用的姿態修正越完整;數值越低,畫面越貼近手機移動。下次開始錄影時生效。 + %1$d%% + EIS+ 前瞻影格數 + 影格數越少,畫面延遲越低、跟手性越強;影格數越多,畫面防震越平滑穩定。預設為 7 幀。 + %1$d 幀 鎖定白平衡 影片錄製過程中鎖定白平衡。 畫質與性能 diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 94b36fd2..15efe14e 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -197,11 +197,17 @@ Lock Lens Prevent zooming from switching cameras while video is recording. Default Video Stabilization - Choose the stabilization mode used when video mode starts. EIS+ uses gyro-driven rolling-shutter correction on rear cameras and switches recording to 1080p/30 fps. + Choose the stabilization mode used when video mode starts. EIS+ uses gyro-driven rolling-shutter correction on rear cameras. Off Electronic (EIS) Optical (OIS) Enhanced (EIS+) + EIS+ Strength + Higher values apply more of the recovered pose correction; lower values follow camera movement more closely. Changes take effect when the next recording starts. + %1$d%% + EIS+ Lookahead Frames + Lower frames reduce latency for better responsiveness; higher frames provide smoother stabilization. Default is 7 frames. + %1$d frames Lock White Balance Keep automatic white balance fixed while video is recording. Quality & Performance diff --git a/app/src/test/java/com/hinnka/mycamera/stabilization/RealtimeStabilizationMathTest.kt b/app/src/test/java/com/hinnka/mycamera/stabilization/RealtimeStabilizationMathTest.kt new file mode 100644 index 00000000..274db828 --- /dev/null +++ b/app/src/test/java/com/hinnka/mycamera/stabilization/RealtimeStabilizationMathTest.kt @@ -0,0 +1,61 @@ +package com.hinnka.mycamera.stabilization + +import com.hinnka.mycamera.lut.MgcEisMesh +import org.junit.Assert.assertEquals +import org.junit.Test + +class RealtimeStabilizationMathTest { + @Test + fun identityNativeMatricesReproduceMgcTwentySixVertexStrip() { + val matrices = FloatArray(STABILIZATION_ROW_COUNT * 9) + repeat(STABILIZATION_ROW_COUNT) { row -> + matrices[row * 9] = 1f + matrices[row * 9 + 4] = 1f + matrices[row * 9 + 8] = 1f + } + + val positions = MgcEisMesh.warpedPositions(matrices) + + assertEquals((STABILIZATION_ROW_COUNT + 1) * 2 * 4, positions.size) + assertEquals(-1f, positions[0], 0f) + assertEquals(1f, positions[1], 0f) + assertEquals(1f, positions[3], 0f) + assertEquals(1f, positions[positions.size - 4], 0f) + assertEquals(-1f, positions[positions.size - 3], 0f) + assertEquals(1f, positions[positions.size - 1], 0f) + assertEquals(STABILIZATION_ROW_COUNT * 6, MgcEisMesh.indices.size) + } + + @Test + fun rearNinetyDegreeSensorUsesMgcRawGyroOrder() { + assertTripleEquals( + Triple(1.0, 2.0, 3.0), + remapMgcGyroForTest(1.0, 2.0, 3.0, 90, frontFacing = false), + ) + } + + @Test + fun rearTwoSeventyDegreeSensorNegatesMgcXYOnly() { + assertTripleEquals( + Triple(-1.0, -2.0, 3.0), + remapMgcGyroForTest(1.0, 2.0, 3.0, 270, frontFacing = false), + ) + } + + @Test + fun frontZeroDegreeSensorUsesMgcAxisSwap() { + assertTripleEquals( + Triple(2.0, -1.0, 3.0), + remapMgcGyroForTest(1.0, 2.0, 3.0, 0, frontFacing = true), + ) + } + + private fun assertTripleEquals( + expected: Triple, + actual: Triple, + ) { + assertEquals(expected.first, actual.first, 1.0e-9) + assertEquals(expected.second, actual.second, 1.0e-9) + assertEquals(expected.third, actual.third, 1.0e-9) + } +} diff --git a/docs/research/mgc-video-stabilization-reconstruction.md b/docs/research/mgc-video-stabilization-reconstruction.md index 9d8a6c43..a966a79a 100644 --- a/docs/research/mgc-video-stabilization-reconstruction.md +++ b/docs/research/mgc-video-stabilization-reconstruction.md @@ -1,15 +1,15 @@ # MGC 视频防抖功能整理与核心算法重建 -目标版本:`MGC_9.6.080_V24_MGC.apk`(arm64-v8a) +主目标版本:完整 V25 `libgcastartup.so` / `.i64`(arm64-v8a);V24 仅用于跨版本函数指纹和 Java 调度对照。 结论:MGC 不只有 Camera2 的 HAL 防抖开关,还包含一条应用侧 Native AEIS 链路。该链路同步消费陀螺仪、OIS 镜组偏移和逐帧 Camera2 元数据,输出多条带 3×3 变换矩阵,再在独立的视频渲染轨中完成重采样。 -本文把信息分成三类: +本文把逆向证据分成三类: - **确认**:能由反编译 Java、JNI 导出、ARM64 反汇编或二进制字符串直接证明。 -- **高置信重建**:接口、数据流和算法组件已经确认,但原始 C++ 被 strip,只能按相机几何重建实现。 -- **未知**:设备标定、滤波系数、裁切优化器参数,以及 UI 模式到 Native 配置档的完整映射。 +- **源码重建**:接口、数据流、profile 7 与 type 18 共用的顶层状态机和算法组件已经确认,按 V25 逐指令控制流写成可编译 C++。 +- **未知**:原厂机型专属标定 protobuf 的完整数值,以及 profile 专用标志的全部消费者和视觉分支。 -配套代码:[`mgc_eis_reconstruction.hpp`](../../research/mgc_eis_reconstruction/mgc_eis_reconstruction.hpp) 和 [`mgc_eis_reconstruction.cpp`](../../research/mgc_eis_reconstruction/mgc_eis_reconstruction.cpp)。它们是可编译的 clean-room 结构重建,不是逐指令翻译或声称还原出的 Google 原始源码。 +生产代码位于 `research/mgc_eis_reconstruction/` 下的 `mgc_type18_engine.*`、`mgc_type18_gyro.*`、`mgc_type18_lookahead.*`、`mgc_type18_projection.*` 和公共数学类型,通过 [`mgc_eis_reconstruction_jni.cpp`](../../app/src/main/cpp/mgc_eis_reconstruction_jni.cpp) 编入 Photon 自己的 `libmy-native-lib.so`。文件名保留最初逆向时的 type 18 名称,但生产 JNI 固定创建已证实的 `blueline` profile 7(12 条带、7 帧前瞻)。App 不打包、不加载原始 `libgcastartup.so`,也不使用 EIS AOT 胶囊。 ## 1. 功能分层 @@ -225,7 +225,7 @@ function stopEis(): ### 3.2 Gyro 输入 -`htd` 每次请求 `(lastGyroTimestamp + 1, frameBoundary]` 内的样本,并按前后摄与 sensor orientation 变换 XY;Z 保留为第三轴。Native 对前摄还会再执行自身坐标系修正。 +`htd` 每次请求 `(lastGyroTimestamp + 1, frameBoundary]` 内的样本,并按前后摄与 sensor orientation 变换 XY;Z 保留为第三轴。`EisNative.processGyro` 随后还会无条件交换 Java X/Y;前摄模式在交换前额外反转 Java Y/Z。 ```pseudo function feedGyroUntil(frameBoundary): @@ -255,6 +255,17 @@ else: (x, y) = (rawX, rawY) ``` +已确认的 Native 入口映射(V25 `0x22809BC..0x22809DC`): + +```pseudo +if frontCameraCoordinateMode: + engineGyro = (-javaY, javaX, -javaZ) +else: + engineGyro = (javaY, javaX, javaZ) +``` + +这里的第二次换轴不能并入或省略 Java 映射。后摄 90° 传感器虽然在 `htd` 中保持 raw XY,进入 `gyro.cc` 的顺序仍然是 `(rawY, rawX, rawZ)`。 + ### 3.3 OIS 输入 ```pseudo @@ -404,7 +415,7 @@ function onEncoderInputFrame(frame): ## 4. Native 入口还原 -目标库:`lib/arm64-v8a/libgcastartup.so`,ELF 已 strip。JNI 符号仍保留: +V24 对照库:`lib/arm64-v8a/libgcastartup.so`,ELF 已 strip。JNI 符号仍保留;V25 地址在 6.1 节单列,不能与本表混用: | JNI | 地址 | 大小 | 反汇编结论 | |---|---:|---:|---| @@ -413,7 +424,7 @@ function onEncoderInputFrame(frame): | `processGyro` | `0x2280998` | 144 | 坐标修正后写入 gyro helper 与主引擎 | | `getTransformBetweenFrames` | `0x2280a28` | 1304 | 组装两帧元数据并输出相对分条变换 | | `processLensOffset` | `0x2281200` | 48 | 把 XY、timestamp、camera index 转交主引擎 | -| `setStabilizationStrength` | `0x2281230` | 12 | 写入当前 filter/profile | +| `setStabilizationStrength` | `0x2281230` | 12 | 转入当前 filter/profile 的强度 setter;V25 的完整字段链见 5.3 | | `getNumOfFramesToLookAhead` | `0x228123c` | 16 | 读取主 filter `+0x110` | | `isTripodMode` | `0x228124c` | 12 | 读取 gyro helper 首字节 | | `setActiveArraySize` | `0x2281258` | 16 | 保存浮点 width/height 并更新引擎 | @@ -470,131 +481,273 @@ ShotParams indicates that device is on a tripod. Gyro speed = ... - **当前可见 MGC 视频 AEIS 调用主要走 Gyro/OIS/元数据/标定路径。** - 库内的 KLT/RegionFlow 可能供另一个配置或调用方使用;仅凭二进制包含这些组件,不能断言它们是当前链路的逐帧必经步骤。 -## 5. 核心算法高置信重建 +## 5. 核心算法源码重建 -原始滤波器和裁切优化器的精确系数无法从 stripped library 唯一恢复。配套 C++ 因此按已确认 ABI 和相机几何重建完整可运行的传感器路径。 +已安装 MGC 的 `device_key=blueline` 经 `prb` 的 UTF-16LE SHA-256 设备哈希映射到 `iyk.c`,其 Native product ID 为 **7**。`motion_filtering_params` 的 `case 7` 确认选择 method 4、12 条带、7 帧 look-ahead;其常规 `mhz.n(false)` 标定字符串为空。它与 type 18 共用 Gyro 主/副姿态流、rolling-shutter 行时间、projection protrusion core、非 Ceres look-ahead 调度、顶层逐帧对象编排以及 JNI→Java/GLES 矩阵适配;type 18 仅保留为同一代码路径的对照 profile。设备标定 protobuf、ROI tracking 和没有实际调用证据的视觉分支不会以猜测值加入生产实现。 + +profile 7 的首个输出在提交第 8 张帧元数据时产生,故其输入图像、Native 输出和 GPU 队列均以 **7 帧**为唯一前瞻长度。不得把 type 18 的 10 帧延迟、10 帧缓存容量或 type 18 专用参数标志混入该路径。 ### 5.1 Gyro 坐标、偏置与姿态积分 -Java 先做设备/镜头方向变换。Native 维护时间有序样本,低速时估计 bias,并以中点角速度积分: +Java 先做设备/镜头方向变换。MGC 请求的是 Android type-4 校准陀螺仪,因此源码不重复估计 bias。`gyro.cc` 的 `0x33BDA1C` 用当前样本角速度与上一时间戳的差构造轴角四元数,再左乘上一姿态: ```text -ω'k = ωk - bias -ωmid = (ω'k-1 + ω'k) / 2 -Δq = Exp(ωmid × Δt) -qk = normalize(qk-1 × Δq) +Δq = AxisAngle(normalize(ωk), |ωk| × (tk - tk-1)) +qk = normalize(Δq × qk-1) ``` 姿态查询落在两个样本之间时用 quaternion SLERP。超过 1 秒的 Gyro 间隙视为不连续,不能直接积分成巨大旋转。 -### 5.2 Tripod 检测 +校准 Gyro 在进入上述积分器前仍经过外层静止门控。V25 `createHandle` 在 `0x22BFD38..0x22BFD78` 构造 `0x22C1A54` 对象;`processGyro` 先把 Java 坐标排成 `(JavaY, JavaX, JavaZ)`,再调用 `0x22C1A9C`。该对象维护 100 个三轴样本的 float 均值和方差;最大轴速率超过 `0.02` 时该样本先乘 `5.0`,静止判定要求每轴 `variance < 0.001` 且 `abs(mean) < 0.004`。第 100 个样本起,一旦判定静止,JNI 在把同一样本送入主/副姿态队列前将 xyz 全部置零;窗口退出静止时立即恢复原样本。常量原始位值来自 `0x6BCB90` 与 `0x6B69C8`,不是 Photon 自设阈值。 -Native 明确暴露 `isTripodMode()`,二进制文本也显示根据 Gyro speed 判定 tripod。重建逻辑是: - -```pseudo -if norm(gyro - bias) <= stillThreshold continuously for holdDuration: - tripodMode = true -else: - tripodMode = false -``` - -Locked profile 在 tripod 状态下冻结虚拟相机姿态;运动恢复后再以较长时间常数跟随。 - -### 5.3 Look-ahead 姿态平滑 - -Native 明确包含 nonlinear look-ahead filter,并能报告 `getNumOfFramesToLookAhead()`。重建实现把未来帧姿态映射到目标帧 quaternion tangent space 后做高斯加权,再用 profile 对应的时间常数更新虚拟相机: +type 18 还使用一条独立的 delayed decomposed pose stream,不能把它实现成 primary pose 的普通低通副本。`0x22820F0` 从 method-4 参数取出 10 帧,并设置: ```text -δi = Log(qtarget^-1 × qi) -δsmooth = Σ wi δi / Σ wi -qlookahead = qtarget × Exp(δsmooth) - -α = 1 - exp(-Δt / τprofile) -qvirtual = SLERP(qvirtual_previous, qlookahead, α) +decomposed_delay = 33,333,333ns × 10 = 333,333,330ns ``` -这比直接平均 quaternion 分量稳定,也避免符号翻转。原库实际使用的 nonlinear cost、look-ahead window 和 IIR 系数属于未知设备 tuning。 +`0x33BE2D4` 每次在当前主姿态入队前,把**上一条**主环记录加入约 1 秒运行均值;当 `previous_timestamp - oldest_timestamp >= 1,000,000,001ns` 时,每次调用只移除一条最旧记录。均值归一化为 dominant axis。`0x33BDA1C` 等历史样本成熟后,把历史角速度投影到该轴再左乘积分: + +```text +axis = normalize(running_mean(previous gyro records)) +ωdecomposed = axis × dot(axis, ωhistorical) +Δqdecomposed = AxisAngle(normalize(ωdecomposed), + |ωdecomposed| × Δthistorical) +qdecomposed = normalize(Δqdecomposed × qdecomposed_previous) +``` + +延迟模式在第二条 Gyro 样本以 identity pose 建立 secondary ring 和 cursor;该 cursor 第一次成熟时会产生同时间戳、零步长的记录,然后才逐条推进历史时间戳。`0x33BE698`/`0x33BE798`/`0x33BEA28` 分别验证主/副环覆盖范围、按查询时间计算 float SLERP 比例并返回两条姿态。该链已经在 `mgc_type18_gyro.*` 中按原顺序实现并用“恒速 pan 保持完整增量、正交 jitter 被轴投影剔除”测试覆盖。 + +### 5.2 Tripod 状态边界 + +Native ABI 的 `isTripodMode()` 直接读取上述外层静止检测对象首字节;它不是 nonlinear motion filter 另行计算的状态。Photon 复刻同一个 100 样本窗口,并且像原版一样先用该状态对 Gyro 归零,再把状态暴露为 tripod mode;二者不能拆开实现。 + +### 5.3 Type 18 nonlinear look-ahead + +`motion_filtering_params.cc` 的 `case 0x12` 已逐字段恢复:method 为 4,look-ahead 半窗为 10,Gaussian sigma 为 6.0,历史容量为 50;`params+526` 保持默认值 0,因此 type 18 的实际逐帧路径**不进入 Ceres optimization**。`0x22BDFBC` 的有效调度固定为: + +```text +22BD63C 构建当前帧和未来 10 帧的 rolling-shutter geometry +22BD844 生成三条加权 gyro pose candidate +22BDA3C two-row grid 快速 protrusion 扫描 +22BDEE0 低 protrusion 下的 motion/pose 混合 +22BE240 full-grid 复核、动态未来窗口和时域释放 +``` + +首个有效 Gyro frame 先走 `gyro_nonlinear_filter.cc` 的 `engine+2080` 初始化分支,把当前 primary pose 同时写入持久虚拟姿态 `+1168` 和当前输出姿态 `+1200`,而不是从全局 identity 开始追赶。进入 look-ahead 链之前,`0x2296470` 再生成每帧 baseline virtual-pose increment。它不是通用姿态低通。type 18 使用 secondary pose stream 判断自适应 domain 边界,同时用 primary stream 建立前后对称的运动轴;保留相邻增量的条件为: + +```text +domain_distance += 2000 × acos(abs(dot(normalize(Δqi), normalize(Δqi-1)))) +retain Δqi when domain_distance + frame_index < 32 +``` + +历史侧最多查询 10 帧并前插增量,未来侧最多查询 10 帧并后插增量;完整 primary 增量积采用 `product = Δq × product`。未来增量先投影到剩余增量积的平均旋转轴,再继续做同一 domain 判断。最终对所有保留增量做左乘积,并以 `1 / (nominal_to_measured_period_ratio × retained_count)` 从单位四元数 SLERP。由此可验证:匀速平移手机时每个增量相同,输出仍是完整的一帧旋转增量,不会像之前的 generic pose low-pass 那样把画面移动拖慢。 + +`0x22BD844` 不是 tangent-space Gaussian average。对 `i=-10..+10` 的 gyro pose,MGC 使用以下固定乘法顺序;`Gσ(i)` 是由 `0x22BCD94` 生成、按完整对称核归一化后只保存中心到边缘一半的权重: + +```text +Δqi = qi × inverse(qreference) +wide = SLERP(I, Δqi, G6(|i|)) × wide +tight = SLERP(I, Δqi, G1(|i|)) × tight + +if i >= 0: + future = SLERP(I, Δqi, GreversedFuture(i)) × future + +wide_out = wide × qreference +tight_out = tight × qreference +future_out = future × qreference +``` + +其中 future 权重把 sigma-6 正半核反转,并用 `(1 + G6(0)) / 2` 再归一化。四元数 SLERP 使用二进制中的端点阈值 `1e-6`、near-parallel 阈值 `0.9999989867` 和 invalid-dot 阈值 `1.0000009537`,不能用普通线性姿态平均替代。 + +two-row protrusion 的逐帧标量变换也已恢复: + +```text +penalty(raw) = min(pow(max(raw, 0) / 0.2, 2), 1) +two_row_pressure = mean(penalty(raw_i)) +``` + +`0x22CF250` 的 activity 输入不是角速度插值。它先由 `0x3411340` 在 primary gyro pose ring 中按半开区间收集 48-byte 姿态记录,再以最小时间差挑选下一姿态,并把 `qselected × inverse(qprevious)` 转为轴角旋转向量后求均值、标准差和方向余弦。该函数在活动链中有两个参数不同、用途独立的调用: + +```text +nonlinear top-level: + end = frame_timestamp + 10 × 33,333,333ns(覆盖不足时逐帧回退) + interval = [end - 700,000,000ns, end) + minimum sample delta = 33,333,332ns + motion = logistic(-8.3469 + 10.7854 × |mean|₁ / sum(stddev)) + if directional_alignment >= 0.01: + motion *= directional_alignment + +look-ahead full-grid: + interval = [frame_timestamp, frame_timestamp + 10 × 33,333,333ns) + minimum sample delta = 33,333,333ns + 只返回独立的 directional_alignment +``` + +后一条 directional alignment 才把有效未来索引从 10 向 3 收缩,不能复用 top-level 的 700ms activity,也不能以 11 个插值角速度样本替代姿态差。当相邻 raw score 满足 `next >= 0.06` 且 `next-current >= 0.04` 时,才对对应未来姿态执行昂贵的 full-grid 复核。空间压力为: + +```text +pressure = min(max(current_full_grid, + cos(motion_blend × π/2) × two_row_pressure), 1) +``` + +压力上升立即生效;下降时用从 0.95 开始、每帧减 0.05 的系数与上一帧混合。`0x22BDEE0` 还在 protrusion 小于 0.001 且 motion blend 上升时使用 `0.925×previous + 0.075×current`。这些精确分支已放入 `mgc_type18_lookahead.*`,并由 `mgc_type18_engine.cpp` 与 full-grid/rolling-shutter 几何共同驱动生产路径。 + +`0x22CDB08` 的 full-grid/two-row 共用几何核心也已恢复。它不按条带中心或整帧四角直接评分。对每个启用的相邻 scanline boundary: + +1. 以 `Htop = Vtop × inverse(Preal_top)` 投影输入条带的两个上角; +2. 以 `Hbottom = Vbottom × inverse(Preal_bottom)` 投影两个下角; +3. 从输入四角到这四个投影点拟合一套 3×3 单应矩阵; +4. 求逆后把对应输出条带的四角反投影回输入域; +5. 按 frame width/height 归一化,与 allowed rect 做 signed protrusion;区间分数取四点最大值; +6. 全局只记录最大区间,并且仅当最大值为正时输出一个只含该区间的 mask。 + +`0x22CEB9C` 实际返回的不是“full-grid score”,而是从请求虚拟姿态向兜底姿态 SLERP 的裁切修正比例:请求姿态已经可行时返回 `0`;否则先用全部区间验证兜底姿态,再只针对初始最差区间二分,直到 `high-low <= 0.01`;若兜底仍越界或最终可行比例 `>0.99`,返回哨兵 `1.1`。`0x22BE240` 把当前帧该修正比例作为空间压力下限,并在检测到 future raw score 的 `0.06/0.04` 跳变时以同一函数替换相应 future pressure。该几何核心与二分返回语义已放入 `mgc_type18_projection.*` 并由确定性测试覆盖。 + +V25 的构造参数和 frame-state 打包链必须一起解释,不能只读取参数源中的相邻浮点数。`createHandle(..., cropFactor=0.5)` 后,`0x22D55C4..0x22D5608` 构造出 `0.025 / 0.05 / 0.05` 三个活动 margin;`0x22DE1F8` 再把它们分别写入 frame state 的 allowed、input 和 output 矩形。当前 `oeq.m()` 固定传 `zoom=1.0` 且提供非空的 12 行输出数组,因此 fallback type-18 的常用分支为: + +```text +two-row score: + input = inset(frame, 0.05) + output = inset(frame, 0.05) + allowed = inset(frame, 0.025) + +full-grid correction: + input = full frame + output = inset(frame, 0.05) + allowed = full frame +``` + +只有 frame scale 大于 `1.0` 且满足相应动态裁切条件时,frame state `+324` 的有效 output rect 才会被更新;普通 fallback 调用不进入该更新。二分阶段 `maximum_allowed_protrusion=0.0`。逐行虚拟投影开关 `params+415=0`,所以真实投影按 12 个 rolling-shutter 时间分别构造,虚拟投影则在所有行共享最终姿态。 + +`0x229DCC8` 的裁切状态也已拆开恢复。当前最大 margin 为: + +```text +base = 0.5 × (1 - (1 - 2 × configured_crop_ratio) / max(frame_scale, 1)) +if filtering_method == 4: base /= method4_scale +current_margin = min(maximum_margin, base) +``` + +`engine+3168` 是返回给 frame state `+320` 的 filtering margin;`engine+3172` 是经过 secondary-margin mix 后的 optimization margin,两者不能共用一个状态。mode 1 只平滑 margin 的上升,mode 5 两个状态都立即使用 current margin。优化状态的历史权重通常为 `engine+640`;只有 filtering method 4 且 `engine+74 != 0` 时归零。 + +V25 的 strength 链已在完整 `.i64` 中从 JNI 写入一直追到两个代码消费点,并进一步按 filtering method 区分是否活动。`0x22C11D4 -> 0x22C4510 -> 0x22E2144` 选择 handle `+0x18` 下 filter `+0x70` 的对象,并按下式写入外层对象 `+0x21c8`(非线性子对象 `+0x1840` 后的 `+0x988`): + +```text +strength_state = strength_state × alpha + input × (1 - alpha) +``` + +type-18 的 `alpha` 来自参数块 `+640`,构造值为 `0.0`,因此对当前活动配置这是立即写入,不是额外的经验平滑。`0x22D7D24` 的 `0x22D8098` 确实存在下面的 full-grid strength 公式: + +```text +effective_correction = 1 - (1 - c) × strength +``` + +但该函数入口先检查 filtering method 字段为 `1`,不是 fallback type-18 的 method `4` 活动分支。method 4 在 `0x22DB9F4` 中把 outer full-grid correction 直接用于请求姿态到实测姿态的 SLERP。type-18 的实际 strength 消费点在组装 look-ahead frame state 时:`+0x84 = min(filter+0x98c, strength)`;`+0x98c` 初值为 `1.0`,在合法 `strength <= 1` 的路径中等于 strength,`0x22FE9BC` 再把它与最终 look-ahead pressure 合成。因此 fallback type-18 的用户强度只控制 look-ahead tight-pose 最终回退;外层 full-grid 是不可绕过的可行性约束,不再乘一次 strength,也不存在 Photon 自造的 zoom/crop 强度链。 ### 5.4 Rolling-shutter 分条 -对于 `N = numStrips`,第 `s` 条的曝光中心近似为: +`0x22CE380` 对 `N` 个输出行矩阵覆盖 rolling-shutter 的两个端点。第 `s` 行的查询时间为: ```text -u = (s + 0.5) / N -Ts = Tcenter - Tcrop_skew / 2 + u × Tcrop_skew +Ts = Tframe + s × Tcrop_skew / (N - 1), s = 0..N-1 +Tcenter = Tframe + Tcrop_skew / 2 ``` -在 `Ts` 查询真实相机姿态 `qactual(Ts)`;虚拟相机姿态在整帧保持平滑目标 `qvirtual`。这样每个条带得到不同修正,直接对应 JNI 的 `N × 9` 输出。 +因此原版不是 `(s+0.5)/N` 的条带中心采样。非逐行的 bounding-box 分支只取两个显式 source row,并先以 float 计算 `row × skew`、截断成 int64 后再除以整数 frame height。在 `Ts` 查询真实相机姿态 `qactual(Ts)`;当请求时间仅略晚于最新 Gyro 且正间隔小于容差时,`0x33BF394` 才把它钳回最新样本时间。每行先构造 `Preal = Kintrinsics × Ractual(Ts)`,OIS 存在时先修正该行 `Kintrinsics`。 ### 5.5 Gyro 单应矩阵 -配套代码约定矩阵执行 output-to-input 采样。对纯旋转: +Native 返回矩阵的方向可由 `iha.b()` 明确确定:矩阵直接乘在条带顶点位置上, +因此它是 input-frame 到 stabilized-output 的正向顶点变换。fallback type 18 的活动 `oeq` 调用没有 injected projection,逐行像素域矩阵为: ```text -Rcorrection = Ractual(Ts) × inverse(Rvirtual) -Hs = Kin × Rcorrection × inverse(Kout) +Preal(Ts) = K × Ractual(Ts) +Pvirtual = K × Rvirtual +Hpixel(Ts) = Pvirtual × inverse(Preal(Ts)) ``` -其中 `Kout` 以输出中心为主点,`Kin` 以 crop-window 中心为主点。strength 不直接线性混矩阵,而是在姿态空间内插: +`K` 的 `fx=fy=outputWidth/inverseFocalLength`,主点为 `(0.5×width, 0.5×height)`。`0x5667084` 随后执行精确坐标适配: ```text -qvirtual_applied = SLERP(qactual, qvirtual, strength) +Hclip = pixelToClip × Hpixel × clipToPixel +normalize Hclip by Hclip[2,2] ``` -所以 strength 0 对应无旋转修正,strength 1 对应完整稳定目标。 +坐标适配之后还有一个不可省略的输出安全画幅步骤。构造器验证 `cropping_ratio == inner_margin == 0.05`,在 `filter+0x428` 保存: + +```text +cropZoom = 1 / (1 - 2 × 0.05) = 1 / 0.9 +``` + +`0x22DD5AC -> 0x5666FA0` 对每条最终返回给 Java 的 `Hclip` 执行 `h20,h21,h22 /= cropZoom`。这是绕 clip-space 原点的齐次投影放大;`iha` 用变换后的 `w` 做透视除法,因而输入图像边缘落到 viewport 外侧,5% 安全区成为实际输出画幅。它不是只供 protrusion 评分的 margin,也不是修改纹理 crop rect。漏掉该步骤会在网格补偿移动时直接露出 framebuffer 黑边。 + +`0x33BF57C` 把 Java 已映射的 xyzw 四元数直接转换为标准 3×3 旋转矩阵;Native 路径中不存在额外的 `diag(1,1,-1)` 共轭。Photon 与 `iha` 一样在 CPU 上把 `Hclip` 直接作用于 26 个 mesh 顶点,不在 fragment shader 中求逆。用户 strength 按 5.3 恢复的 method-4 look-ahead 回退点生效,不改变上述矩阵方向与坐标链。 ### 5.6 OIS lens offset -`processLensOffset(x, y, timestamp, cameraIndex)` 的存在和时间同步是确认事实。offset 到像素位移的比例依赖设备标定,重建代码显式保留: +`processLensOffset(x, y, timestamp, cameraIndex)` 的存在和时间同步是确认事实。V25 的 `apply_lens_offset_to_intrinsics` 只有在 camera metadata 指示存在 camera model 时才查询标定并修改 K;`oeq` 对未知设备创建的 type-18 空配置没有该模型。因此 Photon 仍按原 ABI 接收和排序 OIS 样本,但 fallback 活动路径不把原始 `xshift/yshift` 猜成像素平移。独立的 Camera2 `OIS` 模式仍由 HAL 控制。 -```text -ois_pixels_per_unit_x -ois_pixels_per_unit_y -``` +### 5.7 裁切约束与动态姿态修正 -经时间插值后,OIS 平移与 Gyro homography 合成。不能把某台 Pixel 的比例硬编码成所有 MGC 设备通用值。 +防抖修正会暴露黑边。MGC 先用 5.3 所述 scanline quadrilateral 反投影与姿态 SLERP 二分限制可行姿态,再用 5.5 的固定齐次 crop zoom 把保留的安全区落实为最终输出画幅;两步缺一不可。type-18 只在 look-ahead tight-pose 阶段把原始 pressure `x` 变成 `1-(1-x)×strength`,不再追加第三次姿态插值或经验 `safeStrength`。 -### 5.7 裁切约束与动态有效 strength +### 5.8 视觉运动分支边界 -防抖修正会暴露黑边。重建实现用输出四角和四边中点测试每条 warp 是否仍落入 crop-window;若越界,对 strength 做二分搜索: - -```pseudo -safeStrength = requestedStrength -for each rollingShutterStrip: - safeStrength = min( - safeStrength, - maximum strength whose warped boundary stays inside crop) -``` - -这与 MGC “更强防抖需要更大裁切余量”、Locked 使用更紧 framing 的行为闭合,但原始 Native crop optimizer 可能使用更复杂的时域约束。 - -### 5.8 可选视觉运动融合 - -重建接口保留 `VisualMotion`。只有调用者提供视觉估计时,才按 robust confidence 把它与 Gyro prior 合成。当前 MGC Java 路径传 null image,因此默认不会进入这一支。 - -若要进一步实现库内可见的视觉链,合理结构为: - -```pseudo -pyramid = buildImagePyramid(frame) -tracks = fastKlt(previousPyramid, pyramid, gyroPredictedFlow) -regionFlow = rejectForwardBackwardAndPhotometricOutliers(tracks) -model = robustFit(similarity / homography / mixtureHomography, regionFlow) -confidence = analyzeInliersAndMotionSaliency(model, regionFlow) -visualMotion = temporalIrlsSmooth(model) -fusedMotion = fuse(gyroPrior, visualMotion, confidence) -``` - -这个组件顺序有二进制文件名与日志支撑;阈值、金字塔层数、RANSAC/IRLS 参数及 model selector 没有足够证据,故未伪造为“原始代码”。 +库中包含 KLT/RegionFlow/IRLS 组件,但当前 `oeq.m()` 对 `processFrame()` 明确传 `imageBytes = null`。生产源码因此不加入没有调用证据的视觉运动估计,避免把另一配置档的组件猜进 type 18 传感器路径。 ## 6. 未能唯一恢复的部分 -1. `iyk` 每个设备 ID 对应的完整 protobuf tuning 内容。 +1. `iyk` 每个 Pixel 设备 ID 对应的完整 protobuf tuning 内容。 2. `.obf` 标定文件的解析后参数和值域。 -3. Native nonlinear/look-ahead/IIR filter 的精确系数与 cost function。 -4. `numStrips` 和 look-ahead 帧数的各设备实际值;它们是运行时从 Native profile 读取,不是 Java 常量。 +3. type 18 不启用 Ceres optimizer、ROI tracking 和图像运动估计;这些非活动分支未移植。 +4. 其他设备 profile 的 `numStrips`、look-ahead 与 tuning;fallback type 18 已确认是 12 strips、10 frames。 5. Standard、Active、Locked 各自最终选择哪一个 Native filter/profile 对象。UI 和 framing 已确认,但 createHandle ABI 没有直接携带 `gwo` 枚举。 6. KLT/RegionFlow 在其他视频管线中的精确启用条件。 -7. Native 输出矩阵在原 renderer 内部使用的归一化坐标约定。重建代码明确采用 output-pixel 到 crop-pixel 的约定,便于验证,不声称与原库内存表示逐位一致。 +7. Native 输出矩阵由 `iha.b()` 作为正向顶点变换使用;重建渲染器已采用相同的 13 行/26 顶点正向 mesh 约定。 + +### 6.1 IDA 分片索引 + +为避免继续按字符串零散追踪,现已建立专用副本 `MGC/reverse/eis_index/ida/libgcastartup_eis_indexed.i64`。索引首先以源码文件字符串交叉引用定位断言函数,再用 ELF `.eh_frame` 的精确 FDE 边界补齐同编译单元的静默函数,并加入局部直接调用邻居。原始 `libgcastartup.i64` 不修改。 + +当前源码分片包含 404 个函数:JNI/engine 69、gyro core 18、gyro nonlinear 81、gyro look-ahead/optimization 83、motion filtering 50、rolling-shutter/geometry 76、crop/ROI 7、lens offset 4、visual motion 16。另建立 `modules/type18_active` 语义分片,将 type 18 实际调用链的 74 个入口、数学原语和 geometry helper 重新命名;其中 73 个已导出 Hex-Rays 伪代码,JNI `processFrame` 因函数过大保留逐指令汇编。V25 对应分片为 `modules/v25_type18_active`;strength 的 JNI、setter、状态字段和两个消费点另收敛到 `modules/v25_type18_strength`。IDA 脚本先完成全量命名,再设置 AArch64 原型、清理 Hex-Rays cache 并导出;每次导出前重建 assembly/pseudocode 目录,避免调用点或重命名文件残留旧的 `sub_xxx` 结果。确认的关键入口如下: + +| 地址 | 已确认语义 | +|---:|---| +| `0x22820F0` | engine state 构造;12 strips,并为 method 4 设置 `33,333,333ns × half_window` 的副姿态延迟 | +| `0x22A1D18` | motion filtering 按 method 分发;3/4 进入 nonlinear gyro | +| `0x2295014` | nonlinear gyro filter 构造与参数/历史缓冲初始化 | +| `0x2296470` | method-4 adaptive-domain baseline virtual-pose increment | +| `0x2299AB8` | nonlinear gyro 逐帧主路径 | +| `0x229D234` | 构造 `H = Pvirtual × inverse(Preal)` | +| `0x229DCC8` | filtering/optimization 两套裁切 margin 状态更新 | +| `0x22BC790` | nonlinear look-ahead filter 构造 | +| `0x22BDFBC` | look-ahead 逐帧入口;type 18 固定进入非 Ceres 自适应 protrusion 路径 | +| `0x22BD844` | 三条 gyro pose candidate 的顺序 SLERP/左乘累积 | +| `0x22BDA3C` | two-row-grid protrusion penalty、均值与 wide pose blend | +| `0x22BDEE0` | 低 protrusion motion-rise 状态与中间姿态的两次 SLERP | +| `0x22BE240` | full-grid 未来窗口、空间/时域压力和最终 tight pose blend | +| `0x22CE380` | 首行到末行的 real-camera RS 时间采样与 `Preal=K×R` | +| `0x22CE778` | 按 camera model 把 OIS lens offset 写入每行 intrinsics | +| `0x22CDB08` | 对每个 scanline 区间拟合四点单应、反投影输出边界并返回最坏 protrusion | +| `0x22CEB9C` | 返回请求姿态向兜底姿态的 crop correction fraction;`0`/二分比例/`1.1` 哨兵 | +| `0x33BDA1C` | 当前样本右端点、`Δq × previous` 主姿态积分,以及延迟副姿态成熟调度 | +| `0x33BE2D4` | 从上一条主环记录更新 1 秒运行 Gyro 均值 | +| `0x33BE698` | 验证查询时间是否同时被主姿态环和可选副姿态环覆盖 | +| `0x33BE798` | 计算查询时间比例并对主/副姿态环做 SLERP | +| `0x33BF394` | 只对略超出最新 Gyro 的查询时间做有限钳位 | +| `0x33BF600` | 四元数 half-angle:`acos(abs(dot(normalize(a), normalize(b))))` | +| `0x33BF804` | xyzw 四元数乘法 | +| `0x33BF8C0` | 归一化 shortest-path SLERP | +| `0x22C11D4` | V25 `setStabilizationStrength` JNI 入口 | +| `0x22E2144` | V25 type-18 strength 状态 setter;该配置 `alpha=0` | +| `0x22D8098` | V25 filtering-method-1 的 full-grid strength 消费点;fallback type-18 method 4 不进入 | +| `0x22FE9BC` | V25 look-ahead frame strength 消费点 | +| `0x3411340` | V25 gyro pose 半开区间收集器;lower-bound helper 为 `0x2313CBC` | +| `0x230F094` | V25 两处共用的 horizon/activity 统计原语 | + +`0x22BD23C` 和 `0x22C5BBC` 属于 `params+526 != 0` 才启用的 Ceres 支路;type 18 的参数工厂没有设置该位,不能把它们纳入 type 18 的运行时还原。 + +用户提供的完整 V25 母库位于 `../PhotonCamera/.codex-tmp/ida/mgc_v25/libgcastartup_v25_arm64.i64`,对应二进制 SHA-256 `76966e7c150dfcb2795ea5b2119827a7e90b13d8c03035dbc4de583d9d12eaa6`;V24 目标二进制为 `2103c54ebba1627733b79e3646105595ed1ccefa2b1629f63fb7e1785a48d6a0`,两者地址不能直接互换。完整母库以 clonefile 复制为 `MGC/reverse/eis_index/ida/libgcastartup_v25_full_indexed.i64`,原文件不修改;`modules/v25_type18_active` 已收敛为 74 个活动语义入口并全部成功反编译,strength 和 horizon 两条易混淆状态链分别拆入 `modules/v25_type18_strength` 与 `modules/v25_type18_horizon`。除唯一/放宽指纹映射外,关键入口由源码字符串、严格锚点之间的连续函数布局、调用顺序和函数角色共同审计确认,包括 Gyro 积分、full-grid 调度、RS projection、OIS intrinsics、crop-correction fraction 和 future-horizon signal。`ida_discover_full_eis.py` 从完整库找出 12 个 EisNative JNI 导出、64 个源码字符串 seed 和 512 个两层调用闭包;Gyro 主链的运行均值、查询验证、范围 SLERP、查询函数、range lower-bound 与半开区间收集均已在 V25 完整库中直接导出。 ## 7. 主要证据索引 @@ -611,30 +764,61 @@ fusedMotion = fuse(gyroPrior, visualMotion, confidence) - 设备 ID、camera index、标定路径:`mhz.java`、`iyk.java`、`lsb.java` - 稳定视频渲染轨:`jxm.java`、`iid.java`、`hsz.java` - tracked AEIS vendor keys:`koh.java`、`ksr.java`、`fzj.java` -- Native 二进制:`MGC/MGC_9.6.080_V24_MGC/lib/arm64-v8a/libgcastartup.so` +- V25 Native 二进制:`../PhotonCamera/.codex-tmp/mgc_v25/apk/lib/arm64-v8a/libgcastartup.so` +- V25 完整 IDA 母库:`../PhotonCamera/.codex-tmp/ida/mgc_v25/libgcastartup_v25_arm64.i64` ## 8. 重建代码验证 -代码不依赖 Android 或第三方数学库,可单独做 C++17 静态编译检查: +核心代码不依赖 Android 或第三方数学库,可单独编译并运行确定性测试: ```bash -xcrun clang++ -std=c++17 -Wall -Wextra -Werror -fsyntax-only \ - research/mgc_eis_reconstruction/mgc_eis_reconstruction.cpp +clang++ -std=c++17 -Wall -Wextra -Werror \ + research/mgc_eis_reconstruction/mgc_eis_reconstruction.cpp \ + research/mgc_eis_reconstruction/mgc_type18_lookahead.cpp \ + research/mgc_eis_reconstruction/mgc_type18_lookahead_test.cpp \ + -o /tmp/mgc_type18_lookahead_test +/tmp/mgc_type18_lookahead_test + +clang++ -std=c++17 -Wall -Wextra -Werror \ + research/mgc_eis_reconstruction/mgc_eis_reconstruction.cpp \ + research/mgc_eis_reconstruction/mgc_type18_lookahead.cpp \ + research/mgc_eis_reconstruction/mgc_type18_projection.cpp \ + research/mgc_eis_reconstruction/mgc_type18_projection_test.cpp \ + -o /tmp/mgc_type18_projection_test +/tmp/mgc_type18_projection_test + +clang++ -std=c++17 -Wall -Wextra -Werror \ + research/mgc_eis_reconstruction/mgc_eis_reconstruction.cpp \ + research/mgc_eis_reconstruction/mgc_type18_gyro.cpp \ + research/mgc_eis_reconstruction/mgc_type18_gyro_test.cpp \ + -o /tmp/mgc_type18_gyro_test +/tmp/mgc_type18_gyro_test + +clang++ -std=c++17 -Wall -Wextra -Werror \ + research/mgc_eis_reconstruction/mgc_eis_reconstruction.cpp \ + research/mgc_eis_reconstruction/mgc_type18_gyro.cpp \ + research/mgc_eis_reconstruction/mgc_type18_lookahead.cpp \ + research/mgc_eis_reconstruction/mgc_type18_projection.cpp \ + research/mgc_eis_reconstruction/mgc_type18_engine.cpp \ + research/mgc_eis_reconstruction/mgc_eis_reconstruction_test.cpp \ + -o /tmp/mgc_eis_reconstruction_test +/tmp/mgc_eis_reconstruction_test ``` -`EngineConfig` 的默认数值只是让重建实现可运行的工程占位值。除 ABI 明确约束(例如 strength 必须在 `[0, 1]`)外,不应把默认值当作 MGC 原 tuning。接入真实相机前必须用目标设备的焦距、crop 余量、OIS 比例、strip 数和 look-ahead 长度替换。 +测试覆盖 Gyro 右端点积分和延迟副姿态、100 样本静止门控、horizon pose range 的 lower-bound/最小采样时间差、method-4 baseline/candidate/crop 状态、两个 strength 回退公式、rolling-shutter 端点时间、投影矩阵乘法顺序、最终齐次 crop zoom、scanline 四点单应、最差区间 mask 以及 `0`/二分比例/`1.1` crop correction 返回语义。Android 端由 `buildCMakeDebug`、`compileDefaultDebugKotlin` 验证编译与链接;新构建仍需在设备上完成 JNI、Camera2 时间同步和 GL 延迟帧队列的实时预览/录像验证。 ## 9. Photon App 接入 -Photon 已将传感器驱动路径接入正式 GLES 预览和录像链路,生产实现位于 -`app/src/main/java/com/hinnka/mycamera/stabilization/RealtimeStabilizationCoordinator.kt`。 -研究目录中的 C++ 保持为独立 clean-room 参考,不参与 APK 构建。 +Photon 正式路径只编译 clean-room 重建源码,构建产物中不存在 `libgcastartup.so`。`MgcEisNativeEngine.kt`、`RealtimeStabilizationCoordinator.kt`、JNI 和 GL mesh 已接到本节恢复的 profile 7 非线性链;JNI 固定 12 条带和 7 帧前瞻,不能由 UI 或调用方改成 type 18。旧的 tangent-space 平滑、经验 `safeStrength` 裁切、假 OIS 主点平移和 synthetic framing matrix 已从编译路径删除。 启用条件分成两个互不依赖的开关: -- **视频增强防抖**:视频防抖模式选择 `EIS+`、普通视频录制、后置相机、1080p、30 fps、存在 Gyro,且 Camera2 时间戳源为 `REALTIME`。`EIS+` 与顶栏的 `OFF/EIS/OIS` 共用同一模式状态,设置页用于选择默认模式;选择 `EIS+` 会同步切换到 1080p/30 fps。该模式关闭 HAL EIS/OIS,避免对已经稳定过的图像再次按 Gyro 修正。 +- **视频增强防抖**:视频防抖模式选择 `EIS+`、普通视频录制、后置相机、1080p、30 fps、存在 Gyro,且 Camera2 时间戳源为 `REALTIME`。`EIS+` 与顶栏的 `OFF/EIS/OIS` 共用同一模式状态,设置页用于选择默认模式;选择 `EIS+` 会同步切换到 1080p/30 fps。反编译 `fwp` case 18 和 `ffw` 均表明算法 EIS 运行时关闭 HAL OIS,Photon 按此执行;独立 `OIS` 模式仍由 HAL 开启。 +- **强度与裁切**:默认值按 `oeq.l()` 恢复为 `1.0`。profile 7 同样走 method-4 look-ahead 与 outer full-grid 可行性约束;用户强度只进入该已恢复的滤波状态,不改 Camera2 zoom、焦距矩阵,也不另造 `safeStrength`。 - **照片预览防抖**:开关开启、照片模式、后置相机、存在 Gyro,且 Camera2 时间戳源为 `REALTIME`。它只进入 `LutRenderer` 的首个 OES pass,不参与静态照片请求或照片编码。 -两个路径共享 Camera2 元数据和 Gyro 姿态缓冲,各自维护因果平滑状态。当前生产实现使用 16 个滚动快门行节点、四角安全约束和动态 strength;录像保留 10% 单边裁切余量,照片预览保留 7%。片元 shader 在相邻行节点间插值单应矩阵,然后再应用 `SurfaceTexture` 变换和现有色彩链。 +两个路径共享 `htd` 调度器:按 SurfaceTexture 时间戳建立帧边界队列,只有 Gyro、OIS 和 Camera metadata 越过下一帧边界后才把旧帧交给 Native;数据源超过一秒不更新时走原逻辑的 dead-source escape。当前生产目标只实现已验证的 `blueline` profile 7、空 camera config、空 extended config,并固定返回 12 strips 和 7-frame look-ahead;其他 device profile 不能静默回退到本路径。 -生产路径刻意没有硬编码未知的 MGC 设备 tuning,也没有在缺少标定时伪造 OIS lens-offset 比例。照片预览继续保留既有 Camera2 OIS 行为;视频增强路径关闭 OIS,以保证 Gyro 与输入图像运动模型一致。 +每个 GL 路径的 GPU 帧队列容量由 7 帧 Native look-ahead 加上调度余量得出,而不是沿用 type 18 的 10 帧容量。生产者到帧时立即 `updateTexImage()`,不会为等矩阵占住 OES。陀螺仪首包到达前只推进 htd 边界而不缓存无姿态图像;Native 返回 EIS 时间戳后,渲染器只取相同时间戳的源图像,过期结果会被丢弃,避免在“当前 OES”与“历史稳定帧”之间切换。Camera2 录像会话起停造成相邻输入时间戳超过 250ms 时才建立新的图像 epoch;删除了此前每 500ms 按队列总跨度周期清空的 Photon 自加逻辑。 + +坐标与 `iha` 保持一致:12 个 row-major 3×3 矩阵不转置、不求逆、不上传片元 shader。CPU 构建 13 行、每行左右两个点,共 26 个齐次顶点;第 0 行使用矩阵 0,第 `i>0` 行使用矩阵 `i-1`,生成 72 个索引后由顶点 shader 绘制。Gyro 轴映射、首行中心时间、裁切后 rolling-shutter skew、inverse focal length、active array、crop window 和 OIS camera type 都按 `htd`/`oeq` 调用约定传入重建引擎。 diff --git a/research/mgc_eis_reconstruction/mgc_eis_reconstruction.cpp b/research/mgc_eis_reconstruction/mgc_eis_reconstruction.cpp index b6b41994..fcd6844e 100644 --- a/research/mgc_eis_reconstruction/mgc_eis_reconstruction.cpp +++ b/research/mgc_eis_reconstruction/mgc_eis_reconstruction.cpp @@ -4,14 +4,11 @@ #include #include #include -#include namespace mgc_eis_reconstruction { namespace { constexpr double kEpsilon = 1.0e-12; -constexpr std::int64_t kVisualMatchWindowNs = 50'000'000; -constexpr std::size_t kMaximumOutputCacheSize = 120; double clamp(double value, double minimum, double maximum) { return std::max(minimum, std::min(value, maximum)); @@ -25,33 +22,6 @@ Quaternion negated(const Quaternion &value) { return {-value.w, -value.x, -value.y, -value.z}; } -Mat3 blendHomography(const Mat3 &from, const Mat3 &to, double amount) { - Mat3 result; - const double t = clamp(amount, 0.0, 1.0); - for (std::size_t i = 0; i < result.v.size(); ++i) { - result.v[i] = from.v[i] + (to.v[i] - from.v[i]) * t; - } - if (std::abs(result.v[8]) > kEpsilon) { - const double scale = 1.0 / result.v[8]; - for (double &value : result.v) { - value *= scale; - } - } - return result; -} - -double profileTimeConstant(const EngineConfig &config) { - switch (config.profile) { - case StabilizationProfile::kStandard: - return config.standard_smoothing_time_seconds; - case StabilizationProfile::kActive: - return config.active_smoothing_time_seconds; - case StabilizationProfile::kLocked: - return config.locked_smoothing_time_seconds; - } - return config.standard_smoothing_time_seconds; -} - } // namespace Vec3 Vec3::operator+(const Vec3 &rhs) const { @@ -96,7 +66,6 @@ Quaternion Quaternion::identity() { return {}; } Quaternion Quaternion::fromRotationVector(const Vec3 &radians) { const double angle = norm(radians); if (angle < 1.0e-8) { - // sin(angle / 2) / angle, expanded around zero. const double scale = 0.5 - angle * angle / 48.0; return Quaternion{1.0 - angle * angle / 8.0, radians.x * scale, radians.y * scale, radians.z * scale} @@ -278,7 +247,8 @@ Mat3 Mat3::inverse() const { } Vec2 Mat3::transformPoint(const Vec2 &point) const { - const double denominator = at(2, 0) * point.x + at(2, 1) * point.y + at(2, 2); + const double denominator = + at(2, 0) * point.x + at(2, 1) * point.y + at(2, 2); if (std::abs(denominator) < kEpsilon) { return {std::numeric_limits::infinity(), std::numeric_limits::infinity()}; @@ -289,539 +259,10 @@ Vec2 Mat3::transformPoint(const Vec2 &point) const { }; } -Engine::Engine(EngineConfig config) : config_(std::move(config)) { - if (config_.active_array_width <= 0) { - config_.active_array_width = config_.output_width; - } - if (config_.active_array_height <= 0) { - config_.active_array_height = config_.output_height; - } - if (config_.crop_width <= 0) { - config_.crop_width = config_.active_array_width; - } - if (config_.crop_height <= 0) { - config_.crop_height = config_.active_array_height; - } - if (!validateConfig()) { - throw std::invalid_argument("Invalid EIS engine configuration"); - } -} - -bool Engine::validateConfig() const { - return config_.output_width > 0 && config_.output_height > 0 && - config_.active_array_width > 0 && config_.active_array_height > 0 && - config_.crop_width > 0 && config_.crop_height > 0 && - config_.num_strips > 0 && config_.lookahead_frames >= 0 && - config_.default_focal_length_px > 0.0 && - config_.stabilization_strength >= 0.0 && - config_.stabilization_strength <= 1.0 && - config_.gyro_bias_time_constant_seconds > 0.0 && - profileTimeConstant(config_) > 0.0; -} - -void Engine::setActiveArraySize(int width, int height) { - if (width <= 0 || height <= 0) { - throw std::invalid_argument("Active array dimensions must be positive"); - } - config_.active_array_width = width; - config_.active_array_height = height; -} - -void Engine::setCropWindowSize(int width, int height) { - if (width <= 0 || height <= 0) { - throw std::invalid_argument("Crop dimensions must be positive"); - } - config_.crop_width = width; - config_.crop_height = height; -} - -void Engine::setStabilizationStrength(double strength) { - if (strength < 0.0 || strength > 1.0) { - throw std::invalid_argument( - "Stabilization strength must be between zero and one"); - } - config_.stabilization_strength = strength; -} - -int Engine::numStrips() const { return config_.num_strips; } - -int Engine::numFramesToLookAhead() const { return config_.lookahead_frames; } - -bool Engine::isTripodMode() const { return tripod_mode_; } - -bool Engine::pushGyro(const GyroSample &sample) { - if (last_gyro_ && sample.timestamp_ns <= last_gyro_->timestamp_ns) { - return false; - } - if (!last_gyro_) { - last_gyro_ = sample; - poses_.push_back({sample.timestamp_ns, integrated_orientation_, - sample.radians_per_second}); - updateTripodState(sample); - return true; - } - - const double dt = - static_cast(sample.timestamp_ns - last_gyro_->timestamp_ns) * - kNsToSeconds; - if (!(dt > 0.0) || dt > 1.0) { - // A one-second gap is treated as a discontinuity instead of being - // integrated into a catastrophic pose jump. - last_gyro_ = sample; - poses_.push_back({sample.timestamp_ns, integrated_orientation_, - sample.radians_per_second - gyro_bias_}); - still_since_ns_.reset(); - tripod_mode_ = false; - return false; - } - - const double raw_speed = norm(sample.radians_per_second); - if (raw_speed < config_.tripod_gyro_threshold_rad_s * 4.0) { - const double bias_alpha = - 1.0 - std::exp(-dt / config_.gyro_bias_time_constant_seconds); - gyro_bias_ += (sample.radians_per_second - gyro_bias_) * bias_alpha; - } - - const Vec3 previous_rate = last_gyro_->radians_per_second - gyro_bias_; - const Vec3 current_rate = sample.radians_per_second - gyro_bias_; - const Vec3 midpoint_rate = (previous_rate + current_rate) * 0.5; - integrated_orientation_ = (integrated_orientation_ * - Quaternion::fromRotationVector(midpoint_rate * dt)) - .normalized(); - poses_.push_back( - {sample.timestamp_ns, integrated_orientation_, current_rate}); - last_gyro_ = sample; - updateTripodState(sample); - return true; -} - -void Engine::updateTripodState(const GyroSample &sample) { - const double speed = norm(sample.radians_per_second - gyro_bias_); - if (speed <= config_.tripod_gyro_threshold_rad_s) { - if (!still_since_ns_) { - still_since_ns_ = sample.timestamp_ns; - } - const double still_seconds = - static_cast(sample.timestamp_ns - *still_since_ns_) * - kNsToSeconds; - tripod_mode_ = still_seconds >= config_.tripod_hold_seconds; - } else { - still_since_ns_.reset(); - tripod_mode_ = false; - } -} - -bool Engine::pushLensOffset(const LensOffsetSample &sample) { - if (!lens_offsets_.empty() && - sample.timestamp_ns <= lens_offsets_.back().timestamp_ns) { - return false; - } - lens_offsets_.push_back(sample); - return true; -} - -void Engine::pushVisualMotion(const VisualMotion &motion) { - if (motion.confidence <= 0.0) { - return; - } - if (!visual_motions_.empty() && - motion.timestamp_ns <= visual_motions_.back().timestamp_ns) { - throw std::invalid_argument("Visual motion timestamps must be monotonic"); - } - VisualMotion clamped_motion = motion; - clamped_motion.confidence = clamp(motion.confidence, 0.0, 1.0); - visual_motions_.push_back(clamped_motion); -} - -Quaternion Engine::orientationAt(std::int64_t timestamp_ns) const { - if (poses_.empty()) { - return Quaternion::identity(); - } - if (timestamp_ns <= poses_.front().timestamp_ns) { - return poses_.front().orientation; - } - if (timestamp_ns >= poses_.back().timestamp_ns) { - return poses_.back().orientation; - } - const auto upper = - std::lower_bound(poses_.begin(), poses_.end(), timestamp_ns, - [](const PoseSample &pose, std::int64_t timestamp) { - return pose.timestamp_ns < timestamp; - }); - const auto lower = std::prev(upper); - const double span = - static_cast(upper->timestamp_ns - lower->timestamp_ns); - const double amount = - static_cast(timestamp_ns - lower->timestamp_ns) / span; - return slerp(lower->orientation, upper->orientation, amount); -} - -Vec3 Engine::angularVelocityAt(std::int64_t timestamp_ns) const { - if (poses_.empty()) { - return {}; - } - const auto nearest = - std::lower_bound(poses_.begin(), poses_.end(), timestamp_ns, - [](const PoseSample &pose, std::int64_t timestamp) { - return pose.timestamp_ns < timestamp; - }); - if (nearest == poses_.begin()) { - return nearest->filtered_gyro; - } - if (nearest == poses_.end()) { - return poses_.back().filtered_gyro; - } - const auto previous = std::prev(nearest); - return timestamp_ns - previous->timestamp_ns < - nearest->timestamp_ns - timestamp_ns - ? previous->filtered_gyro - : nearest->filtered_gyro; -} - -Vec2 Engine::lensOffsetAt(std::int64_t timestamp_ns, int camera_index) const { - const LensOffsetSample *before = nullptr; - const LensOffsetSample *after = nullptr; - for (const LensOffsetSample &sample : lens_offsets_) { - if (sample.camera_index != camera_index) { - continue; - } - if (sample.timestamp_ns <= timestamp_ns) { - before = &sample; - } - if (sample.timestamp_ns >= timestamp_ns) { - after = &sample; - break; - } - } - if (!before && !after) { - return {}; - } - if (!before) { - return after->offset; - } - if (!after || before->timestamp_ns == after->timestamp_ns) { - return before->offset; - } - const double amount = - static_cast(timestamp_ns - before->timestamp_ns) / - static_cast(after->timestamp_ns - before->timestamp_ns); - return { - before->offset.x + (after->offset.x - before->offset.x) * amount, - before->offset.y + (after->offset.y - before->offset.y) * amount, - }; -} - -Quaternion Engine::smoothedOrientation(std::size_t pending_index, - const PendingFrame &frame) const { - const Quaternion reference = frame.center_orientation; - Vec3 weighted_tangent{}; - double total_weight = 0.0; - const double sigma = std::max(config_.lookahead_sigma_frames, 0.5); - - for (std::size_t i = pending_index; i < pending_frames_.size(); ++i) { - const double distance = static_cast(i - pending_index); - if (distance > static_cast(config_.lookahead_frames + 1)) { - break; - } - const double weight = - std::exp(-0.5 * distance * distance / (sigma * sigma)); - Quaternion relative = - reference.inverse() * pending_frames_[i].center_orientation; - if (relative.w < 0.0) { - relative = negated(relative); - } - weighted_tangent += quaternionLog(relative) * weight; - total_weight += weight; - } - if (total_weight < kEpsilon) { - return reference; - } - return (reference * quaternionExp(weighted_tangent / total_weight)) - .normalized(); -} - -std::optional -Engine::processFrame(const FrameMetadata &frame) { - if (!pending_frames_.empty() && - frame.frame_timestamp_ns <= - pending_frames_.back().metadata.frame_timestamp_ns) { - throw std::invalid_argument("Frame timestamps must be monotonic"); - } - - const std::int64_t last_strip_time = - frame.frame_timestamp_ns + frame.rolling_shutter_skew_ns / 2; - if (!poses_.empty() && poses_.back().timestamp_ns < last_strip_time) { - // MGC's Java scheduler normally prevents this call until gyro/OIS and - // metadata have crossed the next frame boundary. - return std::nullopt; - } - - PendingFrame pending; - pending.metadata = frame; - pending.center_orientation = orientationAt(frame.frame_timestamp_ns); - pending.center_lens_offset = - lensOffsetAt(frame.frame_timestamp_ns, frame.camera_index); - pending_frames_.push_back(pending); - - if (pending_frames_.size() <= - static_cast(config_.lookahead_frames)) { - return std::nullopt; - } - - StabilizedFrame result = stabilizePending(0); - pending_frames_.pop_front(); - cacheOutput(result); - const std::int64_t keep_from = - pending_frames_.empty() - ? result.timestamp_ns - 1'000'000'000 - : pending_frames_.front().metadata.frame_timestamp_ns - 1'000'000'000; - pruneSensorHistory(keep_from); - return result; -} - -StabilizedFrame Engine::stabilizePending(std::size_t pending_index) { - const PendingFrame &pending = pending_frames_.at(pending_index); - const FrameMetadata &frame = pending.metadata; - const Quaternion lookahead_target = - smoothedOrientation(pending_index, pending); - - Quaternion virtual_orientation = pending.center_orientation; - if (!virtual_orientation_) { - virtual_orientation_ = pending.center_orientation; - virtual_orientation_timestamp_ns_ = frame.frame_timestamp_ns; - } else { - const double dt = - std::max(0.0, static_cast(frame.frame_timestamp_ns - - *virtual_orientation_timestamp_ns_) * - kNsToSeconds); - const double time_constant = profileTimeConstant(config_); - double alpha = 1.0 - std::exp(-dt / time_constant); - - // Locked mode holds the virtual camera while the gyro classifier says - // the device is stationary. This mirrors the native library's exposed - // tripod state structurally; the exact transition constants are not - // recoverable. - if (config_.profile == StabilizationProfile::kLocked && tripod_mode_) { - alpha = 0.0; - } - virtual_orientation_ = - slerp(*virtual_orientation_, lookahead_target, alpha); - virtual_orientation_timestamp_ns_ = frame.frame_timestamp_ns; - } - virtual_orientation = *virtual_orientation_; - - double safe_strength = config_.stabilization_strength; - for (int strip = 0; strip < config_.num_strips; ++strip) { - const double row_fraction = (static_cast(strip) + 0.5) / - static_cast(config_.num_strips); - const std::int64_t strip_timestamp = - frame.frame_timestamp_ns - frame.rolling_shutter_skew_ns / 2 + - static_cast(row_fraction * frame.rolling_shutter_skew_ns); - safe_strength = std::min( - safe_strength, - constrainStrength( - frame, orientationAt(strip_timestamp), virtual_orientation, - lensOffsetAt(strip_timestamp, frame.camera_index), safe_strength)); - } - - StabilizedFrame output; - output.timestamp_ns = frame.frame_timestamp_ns; - output.tripod_mode = tripod_mode_; - output.applied_strength = safe_strength; - output.strip_output_to_input.reserve( - static_cast(config_.num_strips)); - - for (int strip = 0; strip < config_.num_strips; ++strip) { - const double row_fraction = (static_cast(strip) + 0.5) / - static_cast(config_.num_strips); - const std::int64_t strip_timestamp = - frame.frame_timestamp_ns - frame.rolling_shutter_skew_ns / 2 + - static_cast(row_fraction * frame.rolling_shutter_skew_ns); - output.strip_output_to_input.push_back(makeStripWarp( - frame, orientationAt(strip_timestamp), virtual_orientation, - lensOffsetAt(strip_timestamp, frame.camera_index), safe_strength)); - } - return output; -} - -Mat3 Engine::makeStripWarp(const FrameMetadata &frame, - const Quaternion &actual_orientation, - const Quaternion &virtual_orientation, - const Vec2 &lens_offset, double strength) const { - strength = clamp(strength, 0.0, 1.0); - const Quaternion applied_virtual = - slerp(actual_orientation, virtual_orientation, strength); - // A ray rendered by the virtual camera is sampled in the actual camera: - // ray_actual = R_actual * inverse(R_virtual) * ray_virtual. - const Quaternion correction = - (actual_orientation * applied_virtual.inverse()).normalized(); - - const double focal = frame.focal_length_px > 0.0 - ? frame.focal_length_px - : config_.default_focal_length_px; - const Mat3 output_intrinsics = - Mat3::cameraIntrinsics(focal, focal, (config_.output_width - 1) * 0.5, - (config_.output_height - 1) * 0.5); - const Mat3 input_intrinsics = - Mat3::cameraIntrinsics(focal, focal, (config_.crop_width - 1) * 0.5, - (config_.crop_height - 1) * 0.5); - const Mat3 gyro_warp = input_intrinsics * Mat3::fromQuaternion(correction) * - output_intrinsics.inverse(); - - const double lens_x = - lens_offset.x * config_.ois_pixels_per_unit_x * strength; - const double lens_y = - lens_offset.y * config_.ois_pixels_per_unit_y * strength; - Mat3 result = Mat3::translation(lens_x, lens_y) * gyro_warp; - - // The current MGC Java call passes a null image buffer, so this branch is - // dormant for that observed path. It models the library's optional - // KLT/RegionFlow motion estimate when an external estimate is supplied. - const VisualMotion *closest = nullptr; - std::int64_t closest_distance = kVisualMatchWindowNs + 1; - for (const VisualMotion &visual : visual_motions_) { - const std::int64_t distance = - std::llabs(visual.timestamp_ns - frame.frame_timestamp_ns); - if (distance < closest_distance) { - closest = &visual; - closest_distance = distance; - } - } - if (closest && closest_distance <= kVisualMatchWindowNs) { - // Gyro remains the prior; visual motion contributes only according to - // its robust-estimator confidence. - result = blendHomography(result, closest->output_to_input * result, - closest->confidence * strength); - } - return result; -} - -bool Engine::warpFitsCrop(const Mat3 &transform) const { - const double maximum_x = static_cast(config_.crop_width - 1) - - config_.safety_margin_pixels; - const double maximum_y = static_cast(config_.crop_height - 1) - - config_.safety_margin_pixels; - const double minimum = config_.safety_margin_pixels; - const std::array boundary_points{{ - {0.0, 0.0}, - {static_cast(config_.output_width - 1), 0.0}, - {0.0, static_cast(config_.output_height - 1)}, - {static_cast(config_.output_width - 1), - static_cast(config_.output_height - 1)}, - {(config_.output_width - 1) * 0.5, 0.0}, - {(config_.output_width - 1) * 0.5, - static_cast(config_.output_height - 1)}, - {0.0, (config_.output_height - 1) * 0.5}, - {static_cast(config_.output_width - 1), - (config_.output_height - 1) * 0.5}, - }}; - for (const Vec2 &point : boundary_points) { - const Vec2 warped = transform.transformPoint(point); - if (!std::isfinite(warped.x) || !std::isfinite(warped.y) || - warped.x < minimum || warped.y < minimum || warped.x > maximum_x || - warped.y > maximum_y) { - return false; - } - } - return true; -} - -double Engine::constrainStrength(const FrameMetadata &frame, - const Quaternion &actual_orientation, - const Quaternion &virtual_orientation, - const Vec2 &lens_offset, - double requested_strength) const { - double low = 0.0; - double high = clamp(requested_strength, 0.0, 1.0); - if (warpFitsCrop(makeStripWarp(frame, actual_orientation, virtual_orientation, - lens_offset, high))) { - return high; - } - if (!warpFitsCrop(makeStripWarp(frame, actual_orientation, - virtual_orientation, lens_offset, 0.0))) { - // No stabilizing correction can fix invalid base geometry. Returning - // zero exposes the configuration problem without inventing a fallback - // transform. - return 0.0; - } - for (int iteration = 0; iteration < 24; ++iteration) { - const double middle = (low + high) * 0.5; - if (warpFitsCrop(makeStripWarp(frame, actual_orientation, - virtual_orientation, lens_offset, middle))) { - low = middle; - } else { - high = middle; - } - } - return low; -} - -std::vector Engine::flush() { - std::vector outputs; - while (!pending_frames_.empty()) { - StabilizedFrame output = stabilizePending(0); - pending_frames_.pop_front(); - cacheOutput(output); - outputs.push_back(std::move(output)); - } - return outputs; -} - -bool Engine::getTransformBetweenFrames( - std::int64_t from_timestamp_ns, std::int64_t to_timestamp_ns, - std::vector *strip_transforms) const { - if (!strip_transforms) { - throw std::invalid_argument("strip_transforms must not be null"); - } - const OutputCacheEntry *from = nullptr; - const OutputCacheEntry *to = nullptr; - for (const OutputCacheEntry &entry : output_cache_) { - if (entry.timestamp_ns == from_timestamp_ns) { - from = &entry; - } - if (entry.timestamp_ns == to_timestamp_ns) { - to = &entry; - } - } - if (!from || !to || from->transforms.size() != to->transforms.size()) { - return false; - } - strip_transforms->clear(); - strip_transforms->reserve(from->transforms.size()); - for (std::size_t i = 0; i < from->transforms.size(); ++i) { - strip_transforms->push_back(to->transforms[i].inverse() * - from->transforms[i]); - } - return true; -} - -void Engine::cacheOutput(const StabilizedFrame &frame) { - output_cache_.push_back({frame.timestamp_ns, frame.strip_output_to_input}); - while (output_cache_.size() > kMaximumOutputCacheSize) { - output_cache_.pop_front(); - } -} - -void Engine::pruneSensorHistory(std::int64_t oldest_needed_timestamp_ns) { - while (poses_.size() > 2 && - poses_[1].timestamp_ns < oldest_needed_timestamp_ns) { - poses_.pop_front(); - } - while (lens_offsets_.size() > 2 && - lens_offsets_[1].timestamp_ns < oldest_needed_timestamp_ns) { - lens_offsets_.pop_front(); - } - while (!visual_motions_.empty() && - visual_motions_.front().timestamp_ns < oldest_needed_timestamp_ns) { - visual_motions_.pop_front(); - } -} - std::string confidenceNotice() { - return "Confirmed ABI/dataflow reconstruction plus clean-room mathematics; " - "not bit-exact original MGC source. Device calibration, filter " - "coefficients, crop optimizer and UI-mode/native-profile mapping " - "remain proprietary/unknown."; + return "Clean-room reconstruction of the V25 fallback type-18 gyro, " + "look-ahead, crop-pressure, rolling-shutter projection, and JNI " + "matrix-adapter paths; no MGC shared object is loaded or packaged."; } } // namespace mgc_eis_reconstruction diff --git a/research/mgc_eis_reconstruction/mgc_eis_reconstruction.hpp b/research/mgc_eis_reconstruction/mgc_eis_reconstruction.hpp index d3f23b56..0d9af05d 100644 --- a/research/mgc_eis_reconstruction/mgc_eis_reconstruction.hpp +++ b/research/mgc_eis_reconstruction/mgc_eis_reconstruction.hpp @@ -4,6 +4,7 @@ #include #include #include +#include #include #include @@ -54,8 +55,8 @@ Quaternion slerp(Quaternion from, Quaternion to, double t); Vec3 quaternionLog(Quaternion value); Quaternion quaternionExp(const Vec3 &tangent); -// Row-major 3x3 matrix. The reconstruction uses an output-to-input warp: -// input_pixel ~ H * output_pixel. +// Row-major 3x3 matrix. Production output follows MGC's iha contract: +// output_clip ~ H * input_clip. struct Mat3 { std::array v{}; @@ -71,52 +72,47 @@ struct Mat3 { Vec2 transformPoint(const Vec2 &point) const; }; -enum class StabilizationProfile { - kStandard, - kActive, - kLocked, -}; - struct GyroSample { std::int64_t timestamp_ns = 0; - // Camera-coordinate angular velocity in radians/second. + // Android device-coordinate angular velocity in radians/second, after the + // same sensor-orientation remap performed by MGC's htd Java feeder. Vec3 radians_per_second; }; struct LensOffsetSample { std::int64_t timestamp_ns = 0; - // The native ABI accepts raw float offsets. Converting them to pixels is - // calibration-dependent and is controlled by ois_pixels_per_unit below. + // The native ABI accepts raw float offsets. Their conversion is defined by + // the per-camera model, which is absent from the empty type-18 fallback. Vec2 offset; int camera_index = 0; }; -struct VisualMotion { - std::int64_t timestamp_ns = 0; - Mat3 output_to_input = Mat3::identity(); - double confidence = 0.0; -}; - struct FrameMetadata { + // Assigned by Engine on submission. MGC keeps the same monotonic frame id + // at metadata +72 and records it when projected motion forms a local peak. + std::int64_t sequence_id = 0; + // Camera2 SENSOR_TIMESTAMP of the exact source buffer. This is distinct + // from frame_timestamp_ns, which is the first-row centre timestamp consumed + // by the EIS math. The delayed engine must return this ownership key with + // its output so a seven-frame look-ahead transform can never be applied to + // the current buffer. + std::int64_t source_timestamp_ns = 0; std::int64_t frame_timestamp_ns = 0; std::int64_t exposure_time_ns = 0; std::int64_t rolling_shutter_skew_ns = 0; int camera_index = 0; bool half_resolution_sensor_mode = false; - // MGC derives the effective horizontal field scale as: + // Full horizontal field scale used by MGC's JNI call: // crop_width / active_width * physical_sensor_width / focal_length. - // Supplying focal_length_px directly is more convenient for this - // reconstruction. If it is <= 0, EngineConfig::default_focal_length_px is - // used. - double focal_length_px = 0.0; + double inverse_focal_length = 0.0; }; struct EngineConfig { - // Defaults make the reconstruction runnable; except for the public ABI - // ranges (for example strength in [0, 1]), they are not claimed to be MGC - // tuning constants. Real MGC values come from its device configuration and - // calibration protobufs. + // MGC V25 profile 7 fixes the strip/look-ahead parameters below. The + // reconstruction also retains profile 18 only for differential research. + // Method 4 consumes strength in the packed lookahead frame state; its outer + // full-grid feasibility correction is applied directly. int output_width = 1920; int output_height = 1080; int active_array_width = 0; @@ -124,41 +120,61 @@ struct EngineConfig { int crop_width = 0; int crop_height = 0; - int num_strips = 16; - int lookahead_frames = 0; - StabilizationProfile profile = StabilizationProfile::kStandard; + int num_strips = 12; + int lookahead_frames = 10; double stabilization_strength = 1.0; - - double default_focal_length_px = 1200.0; - double gyro_bias_time_constant_seconds = 8.0; - double standard_smoothing_time_seconds = 0.14; - double active_smoothing_time_seconds = 0.28; - double locked_smoothing_time_seconds = 0.75; - double lookahead_sigma_frames = 2.0; - double tripod_gyro_threshold_rad_s = 0.012; - double tripod_hold_seconds = 0.8; - - // Converts processLensOffset() units into active-array pixels. The real - // value is supplied by per-device calibration and is not recoverable as a - // universal constant from the APK. - double ois_pixels_per_unit_x = 1.0; - double ois_pixels_per_unit_y = 1.0; - - // Prevents the warp from touching the crop boundary. The native library - // has its own device-tuned constraint; this value is a reconstruction. - double safety_margin_pixels = 2.0; }; struct StabilizedFrame { std::int64_t timestamp_ns = 0; - std::vector strip_output_to_input; + // Ownership key copied from the buffered FrameMetadata, not derived from + // timestamp_ns. The latter is on the EIS first-row time axis. + std::int64_t source_timestamp_ns = 0; + std::vector strip_input_to_output; bool tripod_mode = false; double applied_strength = 0.0; + // Internal trace values from the same output frame. They are not part of + // the Java ABI; the JNI wrapper uses them to isolate gyro integration, + // virtual-pose filtering and matrix adaptation on one timestamp axis. + Quaternion diagnostic_measured_pose = Quaternion::identity(); + Quaternion diagnostic_secondary_measured_pose = Quaternion::identity(); + Quaternion diagnostic_virtual_pose = Quaternion::identity(); + Quaternion diagnostic_baseline_increment = Quaternion::identity(); + Quaternion diagnostic_motion_pose = Quaternion::identity(); + Quaternion diagnostic_wide_pose = Quaternion::identity(); + Quaternion diagnostic_tight_pose = Quaternion::identity(); + Quaternion diagnostic_intermediate_pose = Quaternion::identity(); + Vec3 diagnostic_horizon_mean_rotation{}; + Vec3 diagnostic_horizon_rotation_stddev{}; + double diagnostic_horizon_directional_alignment = 0.0; + double diagnostic_horizon_logistic_motion_blend = 0.0; + int diagnostic_future_horizon_index = -1; + double diagnostic_future_horizon_alignment = 0.0; + double diagnostic_future_horizon_pressure = 0.0; + double diagnostic_current_motion_blend = 0.0; + double diagnostic_filtered_motion_blend = 0.0; + Vec2 diagnostic_projected_motion{}; + double diagnostic_projected_candidate_requested = 0.0; + double diagnostic_projected_candidate_capped = 0.0; + double diagnostic_projected_candidate_history_gain = 0.0; + double diagnostic_tight_candidate_blend = 0.0; + std::vector diagnostic_raw_two_row_scores; + double diagnostic_mean_future_pressure = 0.0; + double diagnostic_current_full_grid_pressure = 0.0; + double diagnostic_temporal_pressure = 0.0; + double diagnostic_final_blend = 0.0; + double diagnostic_outer_correction = 0.0; }; class Engine { public: explicit Engine(EngineConfig config); + ~Engine(); + + Engine(const Engine &) = delete; + Engine &operator=(const Engine &) = delete; + Engine(Engine &&) noexcept; + Engine &operator=(Engine &&) noexcept; void setActiveArraySize(int width, int height); void setCropWindowSize(int width, int height); @@ -170,7 +186,6 @@ public: bool pushGyro(const GyroSample &sample); bool pushLensOffset(const LensOffsetSample &sample); - void pushVisualMotion(const VisualMotion &motion); // Matches EisNative's delayed-output behavior: the returned timestamp can // belong to an older frame when look-ahead is enabled. @@ -187,58 +202,8 @@ public: std::vector *strip_transforms) const; private: - struct PoseSample { - std::int64_t timestamp_ns = 0; - Quaternion orientation; - Vec3 filtered_gyro; - }; - - struct PendingFrame { - FrameMetadata metadata; - Quaternion center_orientation; - Vec2 center_lens_offset; - }; - - struct OutputCacheEntry { - std::int64_t timestamp_ns = 0; - std::vector transforms; - }; - - bool validateConfig() const; - Quaternion orientationAt(std::int64_t timestamp_ns) const; - Vec3 angularVelocityAt(std::int64_t timestamp_ns) const; - Vec2 lensOffsetAt(std::int64_t timestamp_ns, int camera_index) const; - Quaternion smoothedOrientation(std::size_t pending_index, - const PendingFrame &frame) const; - void updateTripodState(const GyroSample &sample); - StabilizedFrame stabilizePending(std::size_t pending_index); - Mat3 makeStripWarp(const FrameMetadata &frame, - const Quaternion &actual_orientation, - const Quaternion &virtual_orientation, - const Vec2 &lens_offset, double strength) const; - bool warpFitsCrop(const Mat3 &transform) const; - double constrainStrength(const FrameMetadata &frame, - const Quaternion &actual_orientation, - const Quaternion &virtual_orientation, - const Vec2 &lens_offset, - double requested_strength) const; - void cacheOutput(const StabilizedFrame &frame); - void pruneSensorHistory(std::int64_t oldest_needed_timestamp_ns); - - EngineConfig config_; - std::deque poses_; - std::deque lens_offsets_; - std::deque visual_motions_; - std::deque pending_frames_; - std::deque output_cache_; - - Vec3 gyro_bias_; - std::optional last_gyro_; - Quaternion integrated_orientation_; - std::optional virtual_orientation_; - std::optional virtual_orientation_timestamp_ns_; - std::optional still_since_ns_; - bool tripod_mode_ = false; + class Impl; + std::unique_ptr impl_; }; std::string confidenceNotice(); diff --git a/research/mgc_eis_reconstruction/mgc_type18_engine.cpp b/research/mgc_eis_reconstruction/mgc_type18_engine.cpp new file mode 100644 index 00000000..64532737 --- /dev/null +++ b/research/mgc_eis_reconstruction/mgc_type18_engine.cpp @@ -0,0 +1,1071 @@ +#include "mgc_eis_reconstruction.hpp" + +#include "mgc_type18_gyro.hpp" +#include "mgc_type18_lookahead.hpp" +#include "mgc_type18_projection.hpp" + +#include +#include +#include +#include +#include + +namespace mgc_eis_reconstruction { +namespace { + +constexpr std::size_t kMaximumOutputCacheSize = 120; +constexpr double kMaximumAllowedProtrusion = 0.0; +// createHandle(..., cropFactor=0.5) scales the fallback parameter source to +// 0.05 for the look-ahead input/output crop and 0.025 for its inner allowed +// rectangle. The full native output configuration applies the corresponding +// projection crop scale after construction. +constexpr double kLookaheadCropMargin = 0.05; +constexpr double kAllowedInnerMargin = 0.025; +constexpr double kOutputCropZoom = + 1.0 / (1.0 - 2.0 * kLookaheadCropMargin); +constexpr double kProjectionDenominatorEpsilon = 0.000001; + +type18::Parameters parametersFor(const EngineConfig &config) { + type18::Parameters parameters; + // The motion-filtering factory selects this exact half-window from the MGC + // product profile. V25's type-7 fallback has seven frames; type 18 has + // ten. Keep it alongside the queue delay rather than letting either path + // retain a stale type-18 literal. + parameters.half_window_frames = config.lookahead_frames; + // 0x22FD640 and 0x22FE244 pass params+416 to the rolling-shutter projection + // builder. The ensuing conditional is only the calibrated OIS/lens-offset + // intrinsic adjustment; profile 7 leaves it false. Photon has no calibrated + // profile-7 lens model, so its existing geometry path correctly keeps K + // unchanged, but carry the recovered profile field explicitly rather than + // treating the type-18 setting as a common default. + parameters.apply_lens_offsets_to_intrinsics = config.lookahead_frames != 7; + return parameters; +} + +double clamp01(double value) { + return std::max(0.0, std::min(value, 1.0)); +} + +type18::ProtrusionRect insetRect(double width, double height, + double margin) { + return {width * margin, width * (1.0 - margin), height * margin, + height * (1.0 - margin)}; +} + +} // namespace + +class Engine::Impl { +public: + explicit Impl(EngineConfig config) + : config_(std::move(config)), parameters_(parametersFor(config_)), + delayed_gyro_(static_cast(parameters_.half_window_frames) * + type18::Parameters::kFramePeriodNs), + realtime_gyro_(0), motion_filter_(parameters_), + pressure_filter_(parameters_) { + if (config_.active_array_width <= 0) { + config_.active_array_width = config_.output_width; + } + if (config_.active_array_height <= 0) { + config_.active_array_height = config_.output_height; + } + if (config_.crop_width <= 0) { + config_.crop_width = config_.active_array_width; + } + if (config_.crop_height <= 0) { + config_.crop_height = config_.active_array_height; + } + if (!validConfig()) { + throw std::invalid_argument("Invalid MGC EIS engine configuration"); + } + } + + void setActiveArraySize(int width, int height) { + if (width <= 0 || height <= 0) { + throw std::invalid_argument("Active array dimensions must be positive"); + } + config_.active_array_width = width; + config_.active_array_height = height; + } + + void setCropWindowSize(int width, int height) { + if (width <= 0 || height <= 0) { + throw std::invalid_argument("Crop dimensions must be positive"); + } + config_.crop_width = width; + config_.crop_height = height; + } + + void setStrength(double strength) { + if (!(strength >= 0.0 && strength <= 1.0)) { + throw std::invalid_argument( + "Stabilization strength must be between zero and one"); + } + config_.stabilization_strength = strength; + } + + bool pushGyro(const GyroSample &sample) { + // V25 0x22C0980 runs the shared 100-sample stationary detector before + // 0x22C3F70 fans the same (possibly zeroed) sample into both queues. + const GyroSample gated_sample = gyro_stationary_detector_.gate(sample); + tripod_mode_ = gyro_stationary_detector_.isStationary(); + const bool delayed = delayed_gyro_.push(gated_sample); + const bool realtime = realtime_gyro_.push(gated_sample); + return delayed && realtime; + } + + bool pushLensOffset(const LensOffsetSample &sample) { + if (!lens_offsets_.empty() && + sample.timestamp_ns < lens_offsets_.back().timestamp_ns) { + return false; + } + lens_offsets_.push_back(sample); + while (lens_offsets_.size() > 2048) { + lens_offsets_.pop_front(); + } + // Profile 7 disables the raw-offset-to-intrinsics branch (params+416=0). + // The empty profile configuration also has no calibrated lens model. In + // either case, applying raw shifts would invent a calibration and + // reverse/scale motion incorrectly. + return true; + } + + std::optional processFrame(const FrameMetadata &frame) { + if (!pending_frames_.empty() && + frame.frame_timestamp_ns <= + pending_frames_.back().frame_timestamp_ns) { + throw std::invalid_argument("Frame timestamps must be monotonic"); + } + if (!(frame.inverse_focal_length > 0.0)) { + return dropped(frame.frame_timestamp_ns); + } + + FrameMetadata queued_frame = frame; + queued_frame.sequence_id = next_frame_sequence_++; + pending_frames_.push_back(queued_frame); + if (pending_frames_.size() <= + static_cast(parameters_.half_window_frames)) { + return std::nullopt; + } + + StabilizedFrame output = stabilizeFront(); + // `timestamp_ns` is the EIS first-row-centre time. Keep the independent + // Camera2 source-buffer timestamp with the delayed output rather than + // asking a downstream consumer to reconstruct the mapping. + output.source_timestamp_ns = pending_frames_.front().source_timestamp_ns; + previous_frame_timestamp_ns_ = + pending_frames_.front().frame_timestamp_ns; + pending_frames_.pop_front(); + cacheOutput(output); + return output; + } + + std::vector flush() { + // Method 4 cannot synthesize the missing +1..+10 frame metadata. MGC's + // stop path drains those images as unstabilized/dropped rather than + // reflecting or freezing the last pose. + std::vector result; + result.reserve(pending_frames_.size()); + while (!pending_frames_.empty()) { + StabilizedFrame output = + dropped(pending_frames_.front().frame_timestamp_ns); + output.source_timestamp_ns = pending_frames_.front().source_timestamp_ns; + result.push_back(std::move(output)); + pending_frames_.pop_front(); + } + return result; + } + + bool getTransformBetweenFrames(std::int64_t from_timestamp_ns, + std::int64_t to_timestamp_ns, + std::vector *strip_transforms) const { + if (strip_transforms == nullptr) { + throw std::invalid_argument("strip_transforms must not be null"); + } + const OutputCacheEntry *from = nullptr; + const OutputCacheEntry *to = nullptr; + for (const OutputCacheEntry &entry : output_cache_) { + if (entry.timestamp_ns == from_timestamp_ns) { + from = &entry; + } + if (entry.timestamp_ns == to_timestamp_ns) { + to = &entry; + } + } + if (from == nullptr || to == nullptr || + from->transforms.size() != to->transforms.size()) { + return false; + } + strip_transforms->clear(); + strip_transforms->reserve(from->transforms.size()); + for (std::size_t index = 0; index < from->transforms.size(); ++index) { + strip_transforms->push_back(to->transforms[index].inverse() * + from->transforms[index]); + } + return true; + } + + int numStrips() const { return config_.num_strips; } + int numFramesToLookAhead() const { return parameters_.half_window_frames; } + bool isTripodMode() const { return tripod_mode_; } + +private: + struct FutureGeometry { + std::vector real; + std::vector inverse_real; + }; + + struct OutputCacheEntry { + std::int64_t timestamp_ns = 0; + std::vector transforms; + }; + + bool validConfig() const { + return config_.output_width > 0 && config_.output_height > 0 && + config_.active_array_width > 0 && + config_.active_array_height > 0 && config_.crop_width > 0 && + config_.crop_height > 0 && config_.num_strips == 12 && + config_.lookahead_frames >= 3 && config_.lookahead_frames <= 10 && + config_.lookahead_frames == parameters_.half_window_frames && + config_.stabilization_strength >= 0.0 && + config_.stabilization_strength <= 1.0; + } + + static StabilizedFrame dropped(std::int64_t timestamp_ns) { + StabilizedFrame result; + result.timestamp_ns = timestamp_ns; + return result; + } + + Mat3 intrinsicsFor(const FrameMetadata &frame) const { + const double focal = static_cast(config_.output_width) / + frame.inverse_focal_length; + return Mat3::cameraIntrinsics( + focal, focal, static_cast(config_.output_width) * 0.5, + static_cast(config_.output_height) * 0.5); + } + + bool queryPair(const type18::GyroPoseQueue &queue, + std::int64_t timestamp_ns, type18::PosePair *pair) const { + return queue.query(timestamp_ns, &pair->primary, &pair->secondary); + } + + type18::BaselinePoseWindow makeBaselineWindow( + const type18::GyroPoseQueue &queue, std::int64_t center_timestamp_ns, + std::int64_t measured_frame_period_ns) const { + type18::BaselinePoseWindow window; + if (!queryPair(queue, center_timestamp_ns, &window.current)) { + throw std::runtime_error("Current delayed gyro pose is unavailable"); + } + if (!queryPair(queue, + center_timestamp_ns - type18::Parameters::kFramePeriodNs, + &window.previous)) { + window.previous = window.current; + } + + // 0x22D6944 increments the historical counter only after querying + // center - 2*period, and continues while counter < params+272. With + // the profile-specific half-window this includes the corresponding extra deltas through + // center - 11*period, in addition to the initial center-to-previous + // delta assembled by 0x22D66A4..0x22D66DC. + for (int distance = 2; + distance <= parameters_.half_window_frames + 1; ++distance) { + type18::PosePair older; + if (!queryPair(queue, + center_timestamp_ns - + type18::Parameters::kFramePeriodNs * distance, + &older)) { + break; + } + window.older.push_back(older); + } + for (int distance = 1; distance <= parameters_.half_window_frames; + ++distance) { + Quaternion future; + if (!queue.query(center_timestamp_ns + + type18::Parameters::kFramePeriodNs * distance, + &future)) { + break; + } + window.future_primary.push_back(future); + } + const std::int64_t positive_period = + std::max(measured_frame_period_ns, 1); + window.nominal_to_measured_period_ratio = + 33'333'000.0 / static_cast(positive_period); + return window; + } + + type18::PoseCandidates makeCandidates( + const type18::GyroPoseQueue &queue, std::int64_t center_timestamp_ns, + const Quaternion &reference) const { + std::vector poses; + poses.reserve(static_cast( + parameters_.half_window_frames * 2 + 1)); + for (int distance = -parameters_.half_window_frames; + distance <= parameters_.half_window_frames; ++distance) { + Quaternion primary; + const std::int64_t timestamp = + center_timestamp_ns + type18::Parameters::kFramePeriodNs * distance; + bool queried = false; + if (parameters_.candidate_uses_secondary_pose_stream) { + Quaternion secondary; + queried = queue.query(timestamp, &primary, &secondary); + if (queried) { + poses.push_back(secondary); + } + } else { + // 0x22FD848 passes a null secondary output pointer when selector + // lookahead+352 (params+272) is false. Requiring a secondary sample + // here silently discarded the newest primary future poses, because + // that stream is intentionally delayed; it was the source of the + // incorrect low-amplitude wide candidate. + queried = queue.query(timestamp, &primary); + if (queried) { + poses.push_back(primary); + } + } + if (!queried) { + // 0x22FD848 skips a failed query. Supplying the reference produces + // exactly the same identity relative contribution in the fixed-size + // clean-room accumulator. + poses.push_back(reference); + } + } + return type18::accumulatePoseCandidates(poses, reference, parameters_); + } + + std::vector queryRowOrientations( + const type18::GyroPoseQueue &queue, std::int64_t first_row_timestamp_ns, + std::int64_t rolling_shutter_ns) const { + const std::vector offsets = + type18::makeRollingShutterRowOffsets(rolling_shutter_ns, + config_.num_strips); + std::vector result; + result.reserve(offsets.size()); + for (const std::int64_t offset : offsets) { + Quaternion orientation; + if (!queue.query(first_row_timestamp_ns + offset, &orientation)) { + return {}; + } + result.push_back(orientation); + } + return result; + } + + FutureGeometry buildFutureGeometry( + const type18::GyroPoseQueue &queue, const FrameMetadata &metadata, + std::int64_t center_timestamp_ns, bool dense) const { + std::vector orientations; + if (dense) { + orientations = queryRowOrientations( + queue, center_timestamp_ns - metadata.rolling_shutter_skew_ns / 2, + metadata.rolling_shutter_skew_ns); + } else { + const std::array source_rows{ + kLookaheadCropMargin * static_cast(config_.output_height), + (1.0 - kLookaheadCropMargin) * + static_cast(config_.output_height), + }; + const auto offsets = type18::makeBoundingRowOffsets( + metadata.rolling_shutter_skew_ns, source_rows, + static_cast(config_.output_height)); + orientations.reserve(2); + for (const std::int64_t offset : offsets) { + Quaternion orientation; + const std::int64_t first_row = + center_timestamp_ns - metadata.rolling_shutter_skew_ns / 2; + if (!queue.query(first_row + offset, &orientation)) { + return {}; + } + orientations.push_back(orientation); + } + } + + FutureGeometry geometry; + if (orientations.empty()) { + return geometry; + } + geometry.real = type18::buildRealCameraProjectionRows( + orientations, {intrinsicsFor(metadata)}); + geometry.inverse_real.reserve(geometry.real.size()); + for (const Mat3 &projection : geometry.real) { + geometry.inverse_real.push_back(projection.inverse()); + } + return geometry; + } + + std::vector virtualProjection(const Quaternion &pose, + const Mat3 &intrinsics) const { + // Parameter-set byte +415 is zero: V25 uses one shared virtual + // projection even though each real rolling-shutter row has its own pose. + return type18::buildVirtualCameraProjectionRows(pose, {}, {intrinsics}); + } + + double fullGridCorrection(const Quaternion &requested, + const Quaternion &fallback, + const FutureGeometry &geometry, + const Mat3 &virtual_intrinsics) const { + if (geometry.inverse_real.size() < 2) { + return 1.1; + } + const double width = static_cast(config_.output_width); + const double height = static_cast(config_.output_height); + // The dense feasibility pass has a different domain from the earlier + // two-row probe. It projects the complete source frame and asks whether + // the fixed 5% output safety frame can be reverse-projected inside that + // source. Feeding the two-row 5%-inset input rectangle here pairs each + // rolling-shutter boundary with the wrong source scanline and makes the + // outer correction oscillate as it alternates between incompatible + // geometry models. + const type18::ProtrusionRect input{0.0, width, 0.0, height}; + const type18::ProtrusionRect output = + insetRect(width, height, kLookaheadCropMargin); + const type18::ProtrusionRect allowed{0.0, width, 0.0, height}; + return type18::computeFullGridCropCorrectionFraction( + requested, fallback, geometry.inverse_real, + [this, &virtual_intrinsics](const Quaternion &pose) { + return virtualProjection(pose, virtual_intrinsics); + }, + input, output, allowed, width, height, + kMaximumAllowedProtrusion); + } + + double twoRowScore(const Quaternion &virtual_pose, + const FutureGeometry &geometry, + const Mat3 &virtual_intrinsics) const { + if (geometry.inverse_real.size() < 2) { + return 1.0; + } + const double width = static_cast(config_.output_width); + const double height = static_cast(config_.output_height); + const type18::ProtrusionRect input = + insetRect(width, height, kLookaheadCropMargin); + const type18::ProtrusionRect output = + insetRect(width, height, kLookaheadCropMargin); + const type18::ProtrusionRect allowed = + insetRect(width, height, kAllowedInnerMargin); + const std::vector mask(geometry.inverse_real.size() - 1, true); + return type18::evaluateProjectionProtrusion( + geometry.inverse_real, + virtualProjection(virtual_pose, virtual_intrinsics), input, + output, allowed, mask, width, height) + .maximum; + } + + Vec2 projectedPoseDisplacement(const Quaternion &from, + const Quaternion &to, + const Mat3 &intrinsics) const { + // 0x22DEAA4: H = P(to) * inverse(P(from)); project the image centre, + // divide both axes by image width, and retain the binary's +1e-6 + // homogeneous denominator bias. + const Mat3 from_projection = + type18::makeCameraProjection(intrinsics, from); + const Mat3 to_projection = type18::makeCameraProjection(intrinsics, to); + const Mat3 relative = to_projection * from_projection.inverse(); + const double x = static_cast(config_.output_width) * 0.5; + const double y = static_cast(config_.output_height) * 0.5; + const double homogeneous_x = + relative.at(0, 0) * x + relative.at(0, 1) * y + + relative.at(0, 2); + const double homogeneous_y = + relative.at(1, 0) * x + relative.at(1, 1) * y + + relative.at(1, 2); + const double homogeneous_w = + relative.at(2, 0) * x + relative.at(2, 1) * y + + relative.at(2, 2) + kProjectionDenominatorEpsilon; + const double width = static_cast(config_.output_width); + return {(homogeneous_x / homogeneous_w - x) / width, + (homogeneous_y / homogeneous_w - y) / width}; + } + + Vec2 projectedExposureMotion( + const type18::GyroPoseQueue &queue, std::int64_t center_timestamp_ns, + std::int64_t exposure_time_ns, const Mat3 &intrinsics) const { + // 0x22D91D8 reads frame metadata +56, the exposure duration, and builds + // the two projections at center +/- exposure/2. Rolling-shutter skew is + // used by the independent per-row real-camera projection path. + Quaternion exposure_start; + Quaternion exposure_end; + if (!queue.query(center_timestamp_ns - exposure_time_ns / 2, + &exposure_start) || + !queue.query(center_timestamp_ns + exposure_time_ns / 2, + &exposure_end)) { + return {}; + } + return projectedPoseDisplacement(exposure_start, exposure_end, + intrinsics); + } + + double projectedMotionCandidateBlend(double magnitude) const { + // Exact two-branch scalar at 0x22D95E8..0x22D9654. Both branches are + // multiplied by the hard-coded 0.2 candidate ceiling. + if (magnitude <= parameters_.projected_motion_threshold) { + return std::max( + magnitude * parameters_.projected_motion_small_slope + + parameters_.projected_motion_small_offset, + 0.0) * + parameters_.projected_candidate_max_blend; + } + const double exponent = + -parameters_.projected_motion_large_slope * + (magnitude - parameters_.projected_motion_center); + return parameters_.projected_candidate_max_blend / + (std::exp(exponent) + 1.0); + } + + double capProjectedCandidateBlend(double requested, + const Quaternion &previous_output, + const Quaternion &measured_pose, + const Vec2 &raw_projected_motion, + const Mat3 &intrinsics) const { + const double maximum = parameters_.projected_pose_motion_limit * + std::hypot(raw_projected_motion.x, + raw_projected_motion.y); + const auto displacement_for = [&](double amount) { + const Quaternion candidate = type18::interpolatePose( + previous_output, measured_pose, amount, previous_output); + const Vec2 displacement = projectedPoseDisplacement( + previous_output, candidate, intrinsics); + return std::hypot(displacement.x, displacement.y); + }; + if (displacement_for(requested) <= maximum) { + return requested; + } + double low = 0.0; + double high = requested; + while (low + 0.000001 < high) { + const double middle = (low + high) * 0.5; + if (displacement_for(middle) <= maximum) { + low = middle; + } else { + high = middle; + } + } + return low; + } + + void prepareProjectedMotionHistory(const Vec2 ¤t_motion, + std::int64_t frame_sequence) { + const double magnitude = + std::hypot(current_motion.x, current_motion.y); + projected_motion_magnitudes_.push_back(magnitude); + while (projected_motion_magnitudes_.size() > 60) { + projected_motion_magnitudes_.pop_front(); + } + if (projected_motion_magnitudes_.size() < 3) { + return; + } + const std::size_t size = projected_motion_magnitudes_.size(); + const double prior = projected_motion_magnitudes_[size - 2]; + if (prior > projected_motion_magnitudes_[size - 3] && + prior >= projected_motion_magnitudes_.back() && + prior >= parameters_.projected_peak_threshold) { + projected_motion_peak_frames_.push_back(frame_sequence); + while (projected_motion_peak_frames_.size() > 60) { + projected_motion_peak_frames_.pop_front(); + } + } + } + + double updateProjectedMotionHistoryGain( + std::int64_t frame_sequence, + std::int64_t measured_frame_period_ns) { + // V25 0x22D8BD4. The state at engine +2656 is constructed as zero. + // With fewer than two detected peaks its target is one; otherwise the + // reciprocal mean peak spacing over the last 30 normalized frames drives + // the very steep rate logistic at params +392/+396. + double target = 1.0; + const double normalized_periods = + std::round(33'333'000.0 / static_cast( + std::max( + measured_frame_period_ns, 1))); + if (projected_motion_peak_frames_.size() >= 2) { + const std::int64_t oldest_allowed = std::max( + static_cast( + static_cast(frame_sequence) - + normalized_periods * + parameters_.projected_history_window_frames), + 0); + double interval_sum = 0.0; + int interval_count = 0; + for (std::size_t upper = projected_motion_peak_frames_.size() - 1; + upper > 0; --upper) { + const std::int64_t lower_frame = + projected_motion_peak_frames_[upper - 1]; + if (lower_frame < oldest_allowed) { + break; + } + interval_sum += static_cast( + projected_motion_peak_frames_[upper] - lower_frame); + ++interval_count; + } + if (interval_count >= + parameters_.projected_history_min_intervals && + interval_sum > 0.0 && normalized_periods > 0.0) { + const double reciprocal_mean_spacing = + 1.0 / + (interval_sum / + (normalized_periods * static_cast(interval_count))); + const double exponent = + -parameters_.projected_history_rate_slope * + (reciprocal_mean_spacing - + parameters_.projected_history_rate_center); + target = 1.0 - 1.0 / (std::exp(exponent) + 1.0); + } + } + const double previous_weight = + target >= projected_motion_history_gain_ + ? parameters_.projected_gain_rise_previous_weight + : parameters_.projected_gain_fall_previous_weight; + projected_motion_history_gain_ = + projected_motion_history_gain_ * previous_weight + + target * (1.0 - previous_weight); + return projected_motion_history_gain_; + } + + struct CandidateBlendControl { + double requested = 0.0; + double capped = 0.0; + double history_gain = 0.0; + double result = 0.0; + }; + + CandidateBlendControl lookaheadCandidateBlend( + const type18::GyroPoseQueue &queue, + std::int64_t center_timestamp_ns, std::int64_t exposure_time_ns, + const Quaternion &measured_pose, const Mat3 &intrinsics, + double current_motion_blend, const Vec2 ¤t, + double motion_history_gain) { + const double motion_scale = 1.0 - current_motion_blend; + const double requested = projectedMotionCandidateBlend( + std::hypot(current.x * motion_scale, current.y * motion_scale)); + const double capped = capProjectedCandidateBlend( + requested, previous_output_pose_, measured_pose, current, intrinsics); + + double maximum = capped; + int maximum_distance = 0; + for (int distance = 1; distance <= parameters_.half_window_frames; + ++distance) { + const Vec2 future = projectedExposureMotion( + queue, + center_timestamp_ns + + type18::Parameters::kFramePeriodNs * distance, + exposure_time_ns, intrinsics); + const double value = projectedMotionCandidateBlend( + std::hypot(future.x * motion_scale, future.y * motion_scale)); + if (value > maximum) { + maximum = value; + maximum_distance = distance; + } + } + const double raw_result = capped + + (maximum - capped) / + static_cast(maximum_distance + 1); + // 0x22D9814..0x22D984C multiplies by the persistent history gain before + // comparing with the previous final control value and damping a fall. + double result = raw_result * motion_history_gain; + if (result < previous_projected_candidate_blend_) { + result = previous_projected_candidate_blend_ * + parameters_.projected_blend_fall_previous_weight + + result * + (1.0 - + parameters_.projected_blend_fall_previous_weight); + } + previous_projected_candidate_blend_ = result; + return {requested, capped, motion_history_gain, result}; + } + + type18::GyroActivityMetrics activityMetrics( + const type18::GyroPoseQueue &queue, + std::int64_t first_row_timestamp_ns, + std::int64_t statistics_window_ns, + std::int64_t sample_period_ns) const { + // 0x22D5648..0x22D56A8 fixes the future endpoint search to + // half_window*33,333,333ns. 0x230F094 backs the endpoint toward the + // current frame until the primary pose ring covers it, then computes pose + // deltas over the caller-selected interval and minimum sample cadence. + std::int64_t end_timestamp_ns = + first_row_timestamp_ns + + parameters_.half_window_frames * type18::Parameters::kFramePeriodNs; + if (parameters_.half_window_frames >= 1) { + do { + if (queue.isTimestampCovered(end_timestamp_ns, false)) { + break; + } + end_timestamp_ns -= type18::Parameters::kFramePeriodNs; + } while (end_timestamp_ns > first_row_timestamp_ns); + } + const std::int64_t start_timestamp_ns = + statistics_window_ns > 0 + ? end_timestamp_ns - statistics_window_ns + : first_row_timestamp_ns; + if (!queue.isTimestampCovered(start_timestamp_ns, false)) { + return {}; + } + return type18::computeGyroActivityMetrics( + type18::collectHorizonRotationVectors( + queue.primaryRecords(), start_timestamp_ns, end_timestamp_ns, + sample_period_ns), + parameters_); + } + + StabilizedFrame stabilizeFront() { + const FrameMetadata &frame = pending_frames_.front(); + const type18::GyroPoseQueue &queue = + frame.half_resolution_sensor_mode ? realtime_gyro_ : delayed_gyro_; + const std::int64_t center_timestamp = + frame.frame_timestamp_ns + frame.rolling_shutter_skew_ns / 2; + // 0x22D660C..0x22D666C uses the current output frame minus the previous + // output frame. It never uses the next buffered frame's period. + const std::int64_t measured_period = + previous_frame_timestamp_ns_ > 0 + ? frame.frame_timestamp_ns - previous_frame_timestamp_ns_ + : 33'333'000; + + type18::PosePair current; + if (!queryPair(queue, center_timestamp, ¤t)) { + return dropped(frame.frame_timestamp_ns); + } + + // gyro_nonlinear_filter.cc's first-valid-frame branch (engine +2080) + // seeds +1168 and +1200 from the measured primary pose before method 4 + // composes its baseline increment. Starting this persistent pose at the + // global quaternion identity instead makes the filter fight all rotation + // accumulated between gyro registration and the first camera frame. + const bool initialize_output_pose = !output_pose_initialized_; + if (initialize_output_pose) { + previous_output_pose_ = current.primary; + output_pose_initialized_ = true; + } + + // gyro_nonlinear_filter.cc 0x22DA58C..0x22DA994 does not run method 4 on + // the first valid frame. It seeds +1168/+1200 from the measured primary + // pose, keeps +1184 at identity, builds the virtual projection directly + // from +1168 and jumps to the dense-warp output path. Running look-ahead + // here mixes an uninitialized motion history into the first output and + // creates a startup drag in the opposite direction. + if (initialize_output_pose) { + const Mat3 virtual_intrinsics = intrinsicsFor(frame); + const FutureGeometry dense_current = + buildFutureGeometry(queue, frame, center_timestamp, true); + if (dense_current.real.size() != + static_cast(config_.num_strips)) { + return dropped(frame.frame_timestamp_ns); + } + const std::vector virtual_rows = + virtualProjection(current.primary, virtual_intrinsics); + const std::vector pixel_warps = type18::composeDenseWarpRows( + dense_current.real, virtual_rows, false, Mat3::identity()); + + StabilizedFrame output; + output.timestamp_ns = frame.frame_timestamp_ns; + output.tripod_mode = tripod_mode_; + output.applied_strength = config_.stabilization_strength; + output.diagnostic_measured_pose = current.primary; + output.diagnostic_secondary_measured_pose = current.secondary; + output.diagnostic_virtual_pose = current.primary; + output.strip_input_to_output.reserve(pixel_warps.size()); + for (const Mat3 &pixel_warp : pixel_warps) { + output.strip_input_to_output.push_back( + type18::applyCropZoomToClipHomography( + type18::convertPixelHomographyToClip( + pixel_warp, static_cast(config_.output_width), + static_cast(config_.output_height)), + kOutputCropZoom)); + } + return output; + } + + const type18::BaselinePoseWindow baseline_window = + makeBaselineWindow(queue, center_timestamp, measured_period); + const Quaternion baseline_increment = + type18::computeBaselineVirtualPose(baseline_window, parameters_); + const Quaternion motion_pose = + (baseline_increment * previous_output_pose_).normalized(); + const type18::PoseCandidates candidates = + makeCandidates(queue, center_timestamp, + parameters_.candidate_uses_secondary_pose_stream + ? current.secondary + : current.primary); + const Mat3 virtual_intrinsics = intrinsicsFor(frame); + const Vec2 projected_current_motion = projectedExposureMotion( + queue, center_timestamp, frame.exposure_time_ns, + virtual_intrinsics); + prepareProjectedMotionHistory(projected_current_motion, + frame.sequence_id); + const double projected_motion_history_gain = + updateProjectedMotionHistoryGain(frame.sequence_id, + measured_period); + + std::vector future_geometry; + std::vector raw_two_row_scores; + future_geometry.reserve(static_cast( + parameters_.half_window_frames + 1)); + raw_two_row_scores.reserve(future_geometry.capacity()); + for (int index = 0; index <= parameters_.half_window_frames; ++index) { + const std::int64_t future_center = + center_timestamp + type18::Parameters::kFramePeriodNs * index; + // 0x22FD640 receives the one frame-state/metadata object being + // stabilized and advances only its gyro/OIS timestamps by 33,333,333ns. + // Later buffered frames are not substituted as future intrinsics. + future_geometry.push_back(buildFutureGeometry( + queue, frame, future_center, false)); + raw_two_row_scores.push_back(twoRowScore( + previous_output_pose_, future_geometry.back(), virtual_intrinsics)); + } + + const std::int64_t horizon_statistics_window_ns = + static_cast( + parameters_.horizon_statistics_window_seconds * 1.0e9); + const type18::GyroActivityMetrics activity = activityMetrics( + queue, frame.frame_timestamp_ns, horizon_statistics_window_ns, + type18::Parameters::kActivitySamplePeriodNs); + double current_motion_blend = activity.motion_blend; + // 0x230F094 leaves sqrt(mean.x² + mean.y² + mean.z²) in S0 on return. + // 0x22D9C20 compares that mean-motion magnitude with params+312 before + // multiplying the logistic blend by the directional signal written to + // the out parameter. It does not compare the directional signal itself. + // Thus a low net-motion window retains its logistic blend even when its + // individual samples have a high directional alignment. + if (norm(activity.mean) >= parameters_.motion_direction_gate) { + current_motion_blend *= activity.directional_alignment; + } + current_motion_blend = clamp01(current_motion_blend); + const CandidateBlendControl candidate_control = lookaheadCandidateBlend( + queue, center_timestamp, frame.exposure_time_ns, + current.primary, virtual_intrinsics, current_motion_blend, + projected_current_motion, + projected_motion_history_gain); + const double tight_candidate_blend = candidate_control.result; + // 0x22FE420..0x22FE48C invokes the same primitive a second time with no + // past statistics window. Its independent directional scalar is measured + // only across [frame_timestamp, frame_timestamp + 10 frames) and controls + // the 10-to-3 future-score horizon. + const type18::GyroActivityMetrics future_activity = activityMetrics( + queue, frame.frame_timestamp_ns, 0, + type18::Parameters::kFramePeriodNs); + const int future_index = type18::effectiveFutureIndex( + future_activity.directional_alignment, + static_cast(raw_two_row_scores.size()), parameters_); + // 0x22FDA40 evaluates and averages the complete 0..N two-row horizon + // before 0x22FDEE4 composes the virtual pose. The independent horizon + // signal below only limits the later expensive full-grid probing; using + // it to truncate this average changed V25's input-11 oracle pressure + // from 0.266624421 to 0.005074956 and made the controller appear almost + // inactive. + const double two_row_pressure = + type18::meanNormalizedProtrusionScore(raw_two_row_scores, + parameters_); + + std::vector selected_scores; + if (future_index >= 0) { + selected_scores.assign(raw_two_row_scores.begin(), + raw_two_row_scores.begin() + future_index + 1); + } + double full_grid_future_pressure = + type18::meanNormalizedProtrusionScore(selected_scores, parameters_); + + // 0x22BDA3C seeds its first candidate blend from the newest virtual-pose + // history entry (the first output is seeded from the measured pose), then + // moves toward the sigma-6 candidate by the two-row pressure. + const Quaternion two_row_pose = type18::interpolatePose( + previous_output_pose_, candidates.wide, two_row_pressure, + previous_output_pose_); + const double filtered_motion_blend = + // 0x22BDEE0 is invoked before full-grid scoring and consumes the + // same complete two-row aggregate used for the first pose SLERP. + motion_filter_.update(current_motion_blend, two_row_pressure); + // Type 18 sets params+352, so 0x22FDEE4 always performs this first SLERP + // using frame-state +136 before blending toward the baseline motion pose. + const Quaternion preblended_pose = type18::interpolatePose( + two_row_pose, candidates.tight, tight_candidate_blend, two_row_pose); + const Quaternion intermediate_pose = type18::interpolatePose( + preblended_pose, motion_pose, filtered_motion_blend, preblended_pose); + + const FutureGeometry dense_current = + buildFutureGeometry(queue, frame, center_timestamp, true); + if (dense_current.real.size() != + static_cast(config_.num_strips)) { + return dropped(frame.frame_timestamp_ns); + } + const double current_full_grid_pressure = fullGridCorrection( + intermediate_pose, candidates.tight, dense_current, + virtual_intrinsics); + + for (int index = 0; index < future_index; ++index) { + const int next = index + 1; + if (!type18::shouldProbeFutureFullGrid( + raw_two_row_scores[static_cast(index)], + raw_two_row_scores[static_cast(next)])) { + continue; + } + const std::int64_t future_center = + center_timestamp + type18::Parameters::kFramePeriodNs * next; + const FutureGeometry full_future = buildFutureGeometry( + queue, frame, future_center, true); + Quaternion future_actual; + if (queue.query(future_center, &future_actual)) { + const double future_full_grid = fullGridCorrection( + intermediate_pose, future_actual, full_future, + virtual_intrinsics); + full_grid_future_pressure += + (future_full_grid - full_grid_future_pressure) / + static_cast(next + 1); + } + break; + } + + const double spatial_pressure = type18::combineSpatialPressure( + filtered_motion_blend, current_full_grid_pressure, + full_grid_future_pressure); + const double temporal_pressure = pressure_filter_.update(spatial_pressure); + // pack_lookahead_frame_state writes min(filter+0x98c, filter+0x988) to + // frame-state +0x84. Both constructor fields start at 1.0, and valid + // strength is <= 1, so type-18 supplies the current strength here. + const double final_blend = type18::finalPoseBlend( + temporal_pressure, config_.stabilization_strength); + Quaternion output_pose = type18::interpolatePose( + intermediate_pose, candidates.tight, final_blend, + intermediate_pose); + + // 0x22DB9F4 performs the method-4 outer full-grid feasibility pass and + // applies its returned correction directly. The strength-adjusted form at + // 0x22DDF44 belongs to the method-3/6 branch, not this path. + const double outer_correction = fullGridCorrection( + output_pose, current.primary, dense_current, virtual_intrinsics); + output_pose = type18::interpolatePose( + output_pose, current.primary, outer_correction, output_pose); + previous_output_pose_ = output_pose; + + const std::vector virtual_rows = + virtualProjection(output_pose, virtual_intrinsics); + const std::vector pixel_warps = type18::composeDenseWarpRows( + dense_current.real, virtual_rows, false, Mat3::identity()); + + StabilizedFrame output; + output.timestamp_ns = frame.frame_timestamp_ns; + output.tripod_mode = tripod_mode_; + output.applied_strength = config_.stabilization_strength; + output.diagnostic_measured_pose = current.primary; + output.diagnostic_secondary_measured_pose = current.secondary; + output.diagnostic_virtual_pose = output_pose; + output.diagnostic_baseline_increment = baseline_increment; + output.diagnostic_motion_pose = motion_pose; + output.diagnostic_wide_pose = candidates.wide; + output.diagnostic_tight_pose = candidates.tight; + output.diagnostic_intermediate_pose = intermediate_pose; + output.diagnostic_horizon_mean_rotation = activity.mean; + output.diagnostic_horizon_rotation_stddev = activity.standard_deviation; + output.diagnostic_horizon_directional_alignment = + activity.directional_alignment; + output.diagnostic_horizon_logistic_motion_blend = activity.motion_blend; + output.diagnostic_future_horizon_index = future_index; + output.diagnostic_future_horizon_alignment = + future_activity.directional_alignment; + output.diagnostic_future_horizon_pressure = full_grid_future_pressure; + output.diagnostic_current_motion_blend = current_motion_blend; + output.diagnostic_filtered_motion_blend = filtered_motion_blend; + output.diagnostic_projected_motion = projected_current_motion; + output.diagnostic_projected_candidate_requested = + candidate_control.requested; + output.diagnostic_projected_candidate_capped = candidate_control.capped; + output.diagnostic_projected_candidate_history_gain = + candidate_control.history_gain; + output.diagnostic_tight_candidate_blend = tight_candidate_blend; + output.diagnostic_raw_two_row_scores = raw_two_row_scores; + output.diagnostic_mean_future_pressure = two_row_pressure; + output.diagnostic_current_full_grid_pressure = current_full_grid_pressure; + output.diagnostic_temporal_pressure = temporal_pressure; + output.diagnostic_final_blend = final_blend; + output.diagnostic_outer_correction = outer_correction; + output.strip_input_to_output.reserve(pixel_warps.size()); + for (const Mat3 &pixel_warp : pixel_warps) { + output.strip_input_to_output.push_back( + type18::applyCropZoomToClipHomography( + type18::convertPixelHomographyToClip( + pixel_warp, static_cast(config_.output_width), + static_cast(config_.output_height)), + kOutputCropZoom)); + } + return output; + } + + void cacheOutput(const StabilizedFrame &frame) { + if (frame.strip_input_to_output.empty()) { + return; + } + output_cache_.push_back({frame.timestamp_ns, frame.strip_input_to_output}); + while (output_cache_.size() > kMaximumOutputCacheSize) { + output_cache_.pop_front(); + } + } + + EngineConfig config_; + type18::Parameters parameters_; + type18::GyroStationaryDetector gyro_stationary_detector_; + type18::GyroPoseQueue delayed_gyro_; + type18::GyroPoseQueue realtime_gyro_; + type18::LowProtrusionMotionFilter motion_filter_; + type18::TemporalPressureFilter pressure_filter_; + std::deque lens_offsets_; + std::deque pending_frames_; + std::deque output_cache_; + std::deque projected_motion_magnitudes_; + std::deque projected_motion_peak_frames_; + Quaternion previous_output_pose_ = Quaternion::identity(); + std::int64_t next_frame_sequence_ = 0; + std::int64_t previous_frame_timestamp_ns_ = 0; + double projected_motion_history_gain_ = 0.0; + double previous_projected_candidate_blend_ = 0.0; + bool output_pose_initialized_ = false; + bool tripod_mode_ = false; +}; + +Engine::Engine(EngineConfig config) + : impl_(std::make_unique(std::move(config))) {} + +Engine::~Engine() = default; +Engine::Engine(Engine &&) noexcept = default; +Engine &Engine::operator=(Engine &&) noexcept = default; + +void Engine::setActiveArraySize(int width, int height) { + impl_->setActiveArraySize(width, height); +} + +void Engine::setCropWindowSize(int width, int height) { + impl_->setCropWindowSize(width, height); +} + +void Engine::setStabilizationStrength(double strength) { + impl_->setStrength(strength); +} + +int Engine::numStrips() const { return impl_->numStrips(); } +int Engine::numFramesToLookAhead() const { + return impl_->numFramesToLookAhead(); +} +bool Engine::isTripodMode() const { return impl_->isTripodMode(); } + +bool Engine::pushGyro(const GyroSample &sample) { + return impl_->pushGyro(sample); +} + +bool Engine::pushLensOffset(const LensOffsetSample &sample) { + return impl_->pushLensOffset(sample); +} + +std::optional +Engine::processFrame(const FrameMetadata &frame) { + return impl_->processFrame(frame); +} + +std::vector Engine::flush() { return impl_->flush(); } + +bool Engine::getTransformBetweenFrames( + std::int64_t from_timestamp_ns, std::int64_t to_timestamp_ns, + std::vector *strip_transforms) const { + return impl_->getTransformBetweenFrames(from_timestamp_ns, to_timestamp_ns, + strip_transforms); +} + +} // namespace mgc_eis_reconstruction diff --git a/research/mgc_eis_reconstruction/mgc_type18_gyro.cpp b/research/mgc_eis_reconstruction/mgc_type18_gyro.cpp new file mode 100644 index 00000000..b291be5b --- /dev/null +++ b/research/mgc_eis_reconstruction/mgc_type18_gyro.cpp @@ -0,0 +1,564 @@ +#include "mgc_type18_gyro.hpp" + +#include +#include +#include + +namespace mgc_eis_reconstruction::type18 { +namespace { + +constexpr double kVectorEpsilon = 9.999999974752427e-7; +constexpr float kSlerpEndpointEpsilon = 9.999999974752427e-7F; +constexpr float kSlerpNearParallel = 0.9999989867210388F; +constexpr float kSlerpInvalidDot = 1.0000009536743164F; + +Vec3 projectedOntoAxis(const Vec3 &value, const Vec3 &axis) { + // 0x340FEF4/0x3410200 evaluates this projection in scalar float, with the + // first two products folded before adding z. The delayed pose stream is + // sensitive to this exact reduction. + const float axis_x = static_cast(axis.x); + const float axis_y = static_cast(axis.y); + const float axis_z = static_cast(axis.z); + const float value_x = static_cast(value.x); + const float value_y = static_cast(value.y); + const float value_z = static_cast(value.z); + const float projection = + axis_x * value_x + axis_y * value_y + axis_z * value_z; + return {static_cast(axis_x * projection), + static_cast(axis_y * projection), + static_cast(axis_z * projection)}; +} + +// gyro.cc stores and composes xyzw float quaternions. The public +// reconstruction type is double precision for matrix work, so keep the +// storage-boundary conversion explicit instead of allowing the pose queue to +// silently retain higher precision than the original ring. +struct FloatQuaternion { + float x = 0.0F; + float y = 0.0F; + float z = 0.0F; + float w = 1.0F; +}; + +FloatQuaternion toFloatQuaternion(const Quaternion &value) { + return {static_cast(value.x), static_cast(value.y), + static_cast(value.z), static_cast(value.w)}; +} + +Quaternion toQuaternion(const FloatQuaternion &value) { + return {static_cast(value.w), static_cast(value.x), + static_cast(value.y), static_cast(value.z)}; +} + +float floatQuaternionDot(const FloatQuaternion &lhs, + const FloatQuaternion &rhs) { + // 0x3411D10..0x3411D28 folds x·x'+z·z' and y·y'+w·w' before + // the final scalar add; do not replace this with an arbitrary reduction. + const float xz = lhs.x * rhs.x + lhs.z * rhs.z; + const float yw = lhs.y * rhs.y + lhs.w * rhs.w; + return xz + yw; +} + +FloatQuaternion normalizeFloatQuaternion(FloatQuaternion value) { + // 0x340FDB0..0x340FDC8 squares xyzw, folds x²+z² and y²+w² + // in parallel, then adds those lanes. This pairing is observable in the + // stored primary pose after the second gyro sample. + const float xz = value.x * value.x + value.z * value.z; + const float yw = value.y * value.y + value.w * value.w; + const float reciprocal = 1.0F / std::sqrt(xz + yw); + return {value.x * reciprocal, value.y * reciprocal, value.z * reciprocal, + value.w * reciprocal}; +} + +FloatQuaternion multiplyFloatQuaternion(const FloatQuaternion &lhs, + const FloatQuaternion &rhs) { + // 0x3411A28 is the usual Hamilton product, but its NEON implementation + // fixes the reduction tree. In particular x and y are *not* evaluated as + // a left-associated four-term expression. These groupings are observable + // after a long run of float-only gyro integration. + const float x = + (lhs.y * rhs.z + (rhs.x * lhs.w + lhs.x * rhs.w)) - lhs.z * rhs.y; + const float y = + rhs.x * lhs.z + ((lhs.w * rhs.y - lhs.x * rhs.z) + lhs.y * rhs.w); + const float z = + ((lhs.x * rhs.y + lhs.w * rhs.z) - lhs.y * rhs.x) + lhs.z * rhs.w; + const float w = + ((lhs.w * rhs.w - lhs.x * rhs.x) - lhs.y * rhs.y) - lhs.z * rhs.z; + return {x, y, z, w}; +} + +FloatQuaternion axisAngleToFloatQuaternion(float axis_x, float axis_y, + float axis_z, float angle) { + // 0x3411894 first renormalizes the supplied axis before calling sincosf. + // Retaining both normalizations is essential: even an axis that was just + // normalized by the ingress routine differs by float ULPs. + const float xy = axis_x * axis_x + axis_y * axis_y; + const float norm_axis = std::sqrt(xy + axis_z * axis_z); + if (norm_axis < 9.999999974752427e-7F) { + return {}; + } + const float reciprocal_axis = 1.0F / norm_axis; + const float half_angle = angle * 0.5F; + float sine = 0.0F; + float cosine = 1.0F; +#if defined(__APPLE__) + // macOS exposes the paired float helper under its Darwin spelling. Bionic + // exports sincosf, which is the original V25 call target. + __sincosf(half_angle, &sine, &cosine); +#else + ::sincosf(half_angle, &sine, &cosine); +#endif + const float scale = sine * reciprocal_axis; + return {axis_x * scale, axis_y * scale, axis_z * scale, cosine}; +} + +FloatQuaternion fromFloatAngularRate(const Vec3 &radians_per_second, + std::int64_t delta_ns) { + const float rate_x = static_cast(radians_per_second.x); + const float rate_y = static_cast(radians_per_second.y); + const float rate_z = static_cast(radians_per_second.z); + // 0x340FD08..0x340FD78: the rate norm is evaluated before time scaling. + const float rate_xy = rate_x * rate_x + rate_y * rate_y; + const float rate_norm = std::sqrt(rate_xy + rate_z * rate_z); + const float seconds = static_cast(delta_ns) * 1.0e-9F; + if (rate_norm < 9.999999974752427e-7F) { + return axisAngleToFloatQuaternion(1.0F, 0.0F, 0.0F, 0.0F); + } + const float reciprocal_rate = 1.0F / rate_norm; + return axisAngleToFloatQuaternion( + rate_x * reciprocal_rate, rate_y * reciprocal_rate, + rate_z * reciprocal_rate, rate_norm * seconds); +} + +FloatQuaternion querySlerpFloat(FloatQuaternion from, FloatQuaternion to, + float amount) { + from = normalizeFloatQuaternion(from); + amount = std::max(0.0F, std::min(amount, 1.0F)); + if (amount < 9.999999974752427e-7F) { + return from; + } + + to = normalizeFloatQuaternion(to); + if (amount > 0.9999989867210388F) { + return to; + } + + const float cosine = floatQuaternionDot(from, to); + const float absolute_cosine = std::abs(cosine); + if (absolute_cosine >= 1.0000009536743164F) { + return to; + } + if (absolute_cosine > 0.9999989867210388F) { + return normalizeFloatQuaternion( + {from.x * (1.0F - amount) + to.x * amount, + from.y * (1.0F - amount) + to.y * amount, + from.z * (1.0F - amount) + to.z * amount, + from.w * (1.0F - amount) + to.w * amount}); + } + + // 0x3411D90..0x3411DEC calls the float Bionic entry points and forms the + // signed `to` weight as inv_sin * signed_sin(amount * angle). Keeping the + // operation tree explicit matters for the sub-sample pose used by EIS. + const float angle = ::acosf(absolute_cosine); + const float inverse_sine = 1.0F / ::sinf(angle); + const float signed_to_sine = cosine < 0.0F + ? -::sinf(amount * angle) + : ::sinf(amount * angle); + const float to_weight = inverse_sine * signed_to_sine; + const float from_weight = + ::sinf((1.0F - amount) * angle) * inverse_sine; + return {from.x * from_weight + to.x * to_weight, + from.y * from_weight + to.y * to_weight, + from.z * from_weight + to.z * to_weight, + from.w * from_weight + to.w * to_weight}; +} + +} // namespace + +GyroSample GyroStationaryDetector::gate(const GyroSample &sample) { + // Exact constructor constants from V25 0x6BCB90/0x6B69C8: + // mean=0.004, variance=0.001, high-rate scale=5, rate threshold=0.02, + // window=100. The remaining threshold multiplier fields are all 1.0 in + // this createHandle path, so the effective limits stay fixed. + constexpr float kMeanThreshold = 0.004000000189989805f; + constexpr float kVarianceThreshold = 0.0010000000474974513f; + constexpr float kHighRateScale = 5.0f; + constexpr float kRateThreshold = 0.019999999552965164f; + constexpr std::size_t kWindowLength = 100; + constexpr float kInverseWindow = 1.0f / 100.0f; + + const float raw_x = static_cast(sample.radians_per_second.x); + const float raw_y = static_cast(sample.radians_per_second.y); + const float raw_z = static_cast(sample.radians_per_second.z); + const float maximum_rate = + std::max(std::abs(raw_z), std::max(std::abs(raw_y), std::abs(raw_x))); + const float scale = + maximum_rate <= kRateThreshold ? 1.0f : kHighRateScale; + const StoredSample stored{raw_x * scale, raw_y * scale, raw_z * scale}; + + samples_.push_back(stored); + sum_.x += stored.x; + sum_.y += stored.y; + sum_.z += stored.z; + sum_squares_.x += stored.x * stored.x; + sum_squares_.y += stored.y * stored.y; + sum_squares_.z += stored.z * stored.z; + if (samples_.size() > kWindowLength) { + const StoredSample oldest = samples_.front(); + samples_.pop_front(); + sum_.x -= oldest.x; + sum_.y -= oldest.y; + sum_.z -= oldest.z; + sum_squares_.x -= oldest.x * oldest.x; + sum_squares_.y -= oldest.y * oldest.y; + sum_squares_.z -= oldest.z * oldest.z; + } + + if (samples_.size() == kWindowLength) { + const float mean_x = sum_.x * kInverseWindow; + const float mean_y = sum_.y * kInverseWindow; + const float mean_z = sum_.z * kInverseWindow; + const float variance_x = + sum_squares_.x * kInverseWindow - mean_x * mean_x; + const float variance_y = + sum_squares_.y * kInverseWindow - mean_y * mean_y; + const float variance_z = + sum_squares_.z * kInverseWindow - mean_z * mean_z; + stationary_ = variance_x < kVarianceThreshold && + variance_y < kVarianceThreshold && + variance_z < kVarianceThreshold && + std::abs(mean_x) < kMeanThreshold && + std::abs(mean_y) < kMeanThreshold && + std::abs(mean_z) < kMeanThreshold; + } + + if (!stationary_) { + return sample; + } + GyroSample gated = sample; + gated.radians_per_second = {}; + return gated; +} + +bool GyroStationaryDetector::isStationary() const { return stationary_; } + +std::vector collectHorizonRotationVectors( + const std::deque &records, std::int64_t start_timestamp_ns, + std::int64_t end_timestamp_ns, std::int64_t sample_period_ns) { + std::vector result; + if (start_timestamp_ns >= end_timestamp_ns || sample_period_ns < 1) { + return result; + } + + auto current = std::lower_bound( + records.begin(), records.end(), start_timestamp_ns, + [](const GyroPoseRecord &record, std::int64_t timestamp) { + return record.timestamp_ns < timestamp; + }); + if (current == records.end() || current->timestamp_ns >= end_timestamp_ns) { + return result; + } + + Quaternion previous_orientation = current->orientation; + std::int64_t previous_timestamp_ns = current->timestamp_ns; + ++current; + for (; current != records.end() && current->timestamp_ns < end_timestamp_ns; + ++current) { + if (current->timestamp_ns - previous_timestamp_ns < sample_period_ns) { + continue; + } + const Quaternion delta = + current->orientation * previous_orientation.inverse(); + result.push_back(quaternionLog(delta)); + previous_orientation = current->orientation; + previous_timestamp_ns = current->timestamp_ns; + } + return result; +} + +GyroPoseQueue::GyroPoseQueue(std::int64_t decomposed_pose_delay_ns, + std::size_t capacity) + : decomposed_pose_delay_ns_(decomposed_pose_delay_ns), + capacity_(capacity) { + if (decomposed_pose_delay_ns < 0) { + throw std::invalid_argument("Decomposed-pose delay must be non-negative"); + } + if (capacity == 0) { + throw std::invalid_argument("Gyro ring capacity must be positive"); + } +} + +Quaternion GyroPoseQueue::integrate(const Quaternion &previous, + const Vec3 &radians_per_second, + std::int64_t delta_ns) { + const FloatQuaternion delta = + fromFloatAngularRate(radians_per_second, delta_ns); + const FloatQuaternion previous_float = toFloatQuaternion(previous); + // 0x340FD98..0x340FDDC: DeltaQ * previous pose, then pairwise float + // normalization before storing the new primary record. + return toQuaternion( + normalizeFloatQuaternion(multiplyFloatQuaternion(delta, previous_float))); +} + +void GyroPoseQueue::pushPrimary(const GyroPoseRecord &record) { + if (primary_records_.size() == capacity_) { + primary_records_.pop_front(); + } + primary_records_.push_back(record); +} + +void GyroPoseQueue::pushSecondary(const GyroPoseRecord &record) { + if (secondary_records_.size() == capacity_) { + secondary_records_.pop_front(); + } + secondary_records_.push_back(record); +} + +const GyroPoseRecord & +GyroPoseQueue::primaryAt(std::int64_t timestamp_ns) const { + const auto found = std::lower_bound( + primary_records_.begin(), primary_records_.end(), timestamp_ns, + [](const GyroPoseRecord &record, std::int64_t timestamp) { + return record.timestamp_ns < timestamp; + }); + if (found == primary_records_.end() || found->timestamp_ns != timestamp_ns) { + throw std::logic_error( + "Delayed decomposed cursor is missing from the primary gyro ring"); + } + return *found; +} + +Vec3 GyroPoseQueue::updateRunningGyroMean( + const GyroPoseRecord &previous_record) { + // The V25 queue stores the running sums and final mean as three float32 + // scalars (0x3410508..0x3410540 and 0x34106A4..0x34106B8). Vec3 is a + // double public type, so explicitly round every persisted update rather + // than allowing a higher-precision accumulator to leak into the axis. + const float previous_x = + static_cast(previous_record.radians_per_second.x); + const float previous_y = + static_cast(previous_record.radians_per_second.y); + const float previous_z = + static_cast(previous_record.radians_per_second.z); + running_sum_.x = static_cast(static_cast(running_sum_.x) + + previous_x); + running_sum_.y = static_cast(static_cast(running_sum_.y) + + previous_y); + running_sum_.z = static_cast(static_cast(running_sum_.z) + + previous_z); + ++running_count_; + + if (running_oldest_timestamp_ns_ == -1) { + running_oldest_timestamp_ns_ = previous_record.timestamp_ns; + } else if (previous_record.timestamp_ns - running_oldest_timestamp_ns_ >= + kRunningGyroWindowThresholdNs) { + const auto oldest = std::lower_bound( + primary_records_.begin(), primary_records_.end(), + running_oldest_timestamp_ns_, + [](const GyroPoseRecord &record, std::int64_t timestamp) { + return record.timestamp_ns < timestamp; + }); + if (oldest == primary_records_.end() || + oldest->timestamp_ns != running_oldest_timestamp_ns_) { + throw std::logic_error( + "Running-average cursor is missing from the primary gyro ring"); + } + running_sum_.x = static_cast(static_cast(running_sum_.x) - + static_cast( + oldest->radians_per_second.x)); + running_sum_.y = static_cast(static_cast(running_sum_.y) - + static_cast( + oldest->radians_per_second.y)); + running_sum_.z = static_cast(static_cast(running_sum_.z) - + static_cast( + oldest->radians_per_second.z)); + --running_count_; + const auto next = std::next(oldest); + running_oldest_timestamp_ns_ = + next == primary_records_.end() ? previous_record.timestamp_ns + : next->timestamp_ns; + } + + if (running_count_ < 1) { + running_mean_ = {}; + } else { + const float count = static_cast(running_count_); + running_mean_ = { + static_cast(static_cast(running_sum_.x) / count), + static_cast(static_cast(running_sum_.y) / count), + static_cast(static_cast(running_sum_.z) / count), + }; + } + return running_mean_; +} + +bool GyroPoseQueue::push(const GyroSample &sample) { + if (!primary_records_.empty() && + sample.timestamp_ns <= primary_records_.back().timestamp_ns) { + return false; + } + + const Vec3 float_rate{static_cast(sample.radians_per_second.x), + static_cast(sample.radians_per_second.y), + static_cast(sample.radians_per_second.z)}; + + if (primary_records_.empty()) { + const GyroPoseRecord first{float_rate, + sample.timestamp_ns, + Quaternion::identity()}; + pushPrimary(first); + if (decomposed_pose_delay_ns_ == 0) { + pushSecondary(first); + } + return true; + } + + const GyroPoseRecord &previous_primary = primary_records_.back(); + const std::int64_t primary_delta_ns = + sample.timestamp_ns - previous_primary.timestamp_ns; + const Quaternion primary_orientation = + integrate(previous_primary.orientation, float_rate, + primary_delta_ns); + + // 0x33BDBB4 passes the previous primary record, before the current primary + // record is enqueued. This one-sample ordering is observable in the delayed + // stream and must not be replaced by an average including the current rate. + const Vec3 mean = updateRunningGyroMean(previous_primary); + const float mean_x = static_cast(mean.x); + const float mean_y = static_cast(mean.y); + const float mean_z = static_cast(mean.z); + const float mean_magnitude = + std::sqrt(mean_x * mean_x + mean_y * mean_y + mean_z * mean_z); + const Vec3 dominant_axis = + mean_magnitude > static_cast(kVectorEpsilon) + ? Vec3{static_cast(mean_x / mean_magnitude), + static_cast(mean_y / mean_magnitude), + static_cast(mean_z / mean_magnitude)} + : Vec3{}; + + if (decomposed_pose_delay_ns_ == 0) { + const Vec3 projected = + projectedOntoAxis(float_rate, dominant_axis); + const Quaternion previous_secondary = secondary_records_.back().orientation; + const std::int64_t secondary_delta_ns = + sample.timestamp_ns - secondary_records_.back().timestamp_ns; + pushSecondary({projected, sample.timestamp_ns, + integrate(previous_secondary, projected, + secondary_delta_ns)}); + } else if (next_decomposed_timestamp_ns_ == -1) { + // 0x33BDC94 seeds the delayed ring on the second gyro sample. Its rate is + // copied verbatim and its pose is identity; the cursor is the same current + // timestamp even though that primary record is enqueued below. + next_decomposed_timestamp_ns_ = sample.timestamp_ns; + pushSecondary({float_rate, sample.timestamp_ns, + Quaternion::identity()}); + } else { + while (sample.timestamp_ns - next_decomposed_timestamp_ns_ >= + decomposed_pose_delay_ns_) { + const GyroPoseRecord &historical = + primaryAt(next_decomposed_timestamp_ns_); + const Vec3 projected = + projectedOntoAxis(historical.radians_per_second, dominant_axis); + const GyroPoseRecord &previous_secondary = secondary_records_.back(); + pushSecondary( + {projected, historical.timestamp_ns, + integrate(previous_secondary.orientation, projected, + historical.timestamp_ns - + previous_secondary.timestamp_ns)}); + + const auto current = std::lower_bound( + primary_records_.begin(), primary_records_.end(), + historical.timestamp_ns, + [](const GyroPoseRecord &record, std::int64_t timestamp) { + return record.timestamp_ns < timestamp; + }); + const auto next = std::next(current); + next_decomposed_timestamp_ns_ = + next == primary_records_.end() ? sample.timestamp_ns + : next->timestamp_ns; + } + } + + pushPrimary( + {float_rate, sample.timestamp_ns, primary_orientation}); + return true; +} + +bool GyroPoseQueue::isTimestampCovered(std::int64_t timestamp_ns, + bool require_secondary) const { + constexpr std::int64_t kTimestampToleranceNs = 50'000'000; + if (timestamp_ns < 0 || primary_records_.empty() || + primary_records_.front().timestamp_ns > timestamp_ns + kTimestampToleranceNs || + primary_records_.back().timestamp_ns + kTimestampToleranceNs < timestamp_ns) { + return false; + } + return !require_secondary || + (!secondary_records_.empty() && + secondary_records_.front().timestamp_ns <= timestamp_ns + kTimestampToleranceNs && + secondary_records_.back().timestamp_ns + kTimestampToleranceNs >= timestamp_ns); +} + +Quaternion GyroPoseQueue::interpolate( + const std::deque &records, + std::int64_t timestamp_ns) { + if (records.empty()) { + return Quaternion::identity(); + } + if (timestamp_ns <= records.front().timestamp_ns) { + return records.front().orientation; + } + if (timestamp_ns >= records.back().timestamp_ns) { + return records.back().orientation; + } + const auto upper = std::lower_bound( + records.begin(), records.end(), timestamp_ns, + [](const GyroPoseRecord &record, std::int64_t timestamp) { + return record.timestamp_ns < timestamp; + }); + if (upper == records.end()) { + return records.back().orientation; + } + if (upper->timestamp_ns == timestamp_ns || upper == records.begin()) { + return upper->orientation; + } + const GyroPoseRecord &lower = *std::prev(upper); + // 0x3410A88..0x3410A94 explicitly converts both integer deltas to float + // before division, then passes that float to the float-only gyro SLERP. + const float amount = + static_cast(timestamp_ns - lower.timestamp_ns) / + static_cast(upper->timestamp_ns - lower.timestamp_ns); + return toQuaternion(querySlerpFloat(toFloatQuaternion(lower.orientation), + toFloatQuaternion(upper->orientation), + amount)); +} + +bool GyroPoseQueue::query(std::int64_t timestamp_ns, Quaternion *primary, + Quaternion *secondary) const { + if (primary == nullptr) { + throw std::invalid_argument("Primary gyro pose output must not be null"); + } + if (!isTimestampCovered(timestamp_ns, secondary != nullptr)) { + return false; + } + *primary = interpolate(primary_records_, timestamp_ns); + if (secondary != nullptr) { + *secondary = interpolate(secondary_records_, timestamp_ns); + } + return true; +} + +const std::deque &GyroPoseQueue::primaryRecords() const { + return primary_records_; +} + +const std::deque &GyroPoseQueue::secondaryRecords() const { + return secondary_records_; +} + +Vec3 GyroPoseQueue::runningGyroMean() const { return running_mean_; } + +std::int64_t GyroPoseQueue::nextDecomposedTimestamp() const { + return next_decomposed_timestamp_ns_; +} + +} // namespace mgc_eis_reconstruction::type18 diff --git a/research/mgc_eis_reconstruction/mgc_type18_gyro.hpp b/research/mgc_eis_reconstruction/mgc_type18_gyro.hpp new file mode 100644 index 00000000..5c012e48 --- /dev/null +++ b/research/mgc_eis_reconstruction/mgc_type18_gyro.hpp @@ -0,0 +1,109 @@ +#pragma once + +#include "mgc_eis_reconstruction.hpp" + +#include +#include +#include +#include + +namespace mgc_eis_reconstruction::type18 { + +// Confirmed at 0x22820F0 for device type 18: 33333333ns multiplied by the +// method-4 half-window (10 frames). +constexpr std::int64_t kDecomposedPoseDelayNs = 333'333'330; +constexpr std::int64_t kRunningGyroWindowThresholdNs = 1'000'000'001; +constexpr std::size_t kGyroRingCapacity = 10'000; + +// V25 createHandle 0x22BFD38..0x22BFD78 constructs this detector immediately +// in front of both gyro queues. processGyro 0x22C0980 then replaces xyz with +// zero whenever the detector reports a stationary 100-sample window. +class GyroStationaryDetector { +public: + GyroSample gate(const GyroSample &sample); + bool isStationary() const; + +private: + struct StoredSample { + float x = 0.0f; + float y = 0.0f; + float z = 0.0f; + }; + + std::deque samples_; + StoredSample sum_; + StoredSample sum_squares_; + bool stationary_ = false; +}; + +// Logical form of gyro.cc's 48-byte ring record. The binary stores float xyz, +// two int64 timestamps and an xyzw float quaternion; this clean-room form uses +// the reconstruction's double-precision math types without changing the +// update order. +struct GyroPoseRecord { + Vec3 radians_per_second; + std::int64_t timestamp_ns = 0; + Quaternion orientation = Quaternion::identity(); +}; + +struct QueriedGyroPose { + Quaternion primary = Quaternion::identity(); + Quaternion secondary = Quaternion::identity(); +}; + +// V25 0x3411340 followed by 0x230F094: collect primary gyro-pose records in +// [start, end), then retain a record only after at least sample_period_ns has +// elapsed and convert selected_pose * inverse(previous_selected_pose) to an +// axis-angle rotation vector. The first collected pose is the reference and +// is not itself emitted. +std::vector collectHorizonRotationVectors( + const std::deque &records, std::int64_t start_timestamp_ns, + std::int64_t end_timestamp_ns, std::int64_t sample_period_ns); + +// Stateful reconstruction of gyro.cc 0x33BDA1C, 0x33BE2D4, 0x33BE698, +// 0x33BE798 and 0x33BEA28. The secondary ring is not a smoothed copy of the +// primary orientation: it is a delayed integration of historical angular +// rates projected onto a one-second running-average axis. +class GyroPoseQueue { +public: + explicit GyroPoseQueue( + std::int64_t decomposed_pose_delay_ns = kDecomposedPoseDelayNs, + std::size_t capacity = kGyroRingCapacity); + + bool push(const GyroSample &sample); + + bool isTimestampCovered(std::int64_t timestamp_ns, + bool require_secondary) const; + bool query(std::int64_t timestamp_ns, Quaternion *primary, + Quaternion *secondary = nullptr) const; + + const std::deque &primaryRecords() const; + const std::deque &secondaryRecords() const; + Vec3 runningGyroMean() const; + std::int64_t nextDecomposedTimestamp() const; + +private: + Vec3 updateRunningGyroMean(const GyroPoseRecord &previous_record); + void pushPrimary(const GyroPoseRecord &record); + void pushSecondary(const GyroPoseRecord &record); + const GyroPoseRecord &primaryAt(std::int64_t timestamp_ns) const; + static Quaternion integrate(const Quaternion &previous, + const Vec3 &radians_per_second, + std::int64_t delta_ns); + static Quaternion interpolate(const std::deque &records, + std::int64_t timestamp_ns); + + std::int64_t decomposed_pose_delay_ns_; + std::size_t capacity_; + std::deque primary_records_; + std::deque secondary_records_; + + std::int64_t running_oldest_timestamp_ns_ = -1; + std::int64_t running_count_ = 0; + Vec3 running_sum_; + Vec3 running_mean_; + + std::int64_t next_decomposed_timestamp_ns_ = -1; +}; + +} // namespace mgc_eis_reconstruction::type18 diff --git a/research/mgc_eis_reconstruction/mgc_type18_lookahead.cpp b/research/mgc_eis_reconstruction/mgc_type18_lookahead.cpp new file mode 100644 index 00000000..781ffd82 --- /dev/null +++ b/research/mgc_eis_reconstruction/mgc_type18_lookahead.cpp @@ -0,0 +1,844 @@ +#include "mgc_type18_lookahead.hpp" + +#include +#include +#ifdef MGC_EIS_BASELINE_TRACE +#include +#endif +#include + +namespace mgc_eis_reconstruction::type18 { +namespace { + +constexpr double kPi = 3.14159265358979323846; +constexpr double kSlerpEndpointEpsilon = 9.999999974752427e-7; +constexpr double kSlerpNearParallel = 0.9999989867210388; +constexpr double kSlerpInvalidDot = 1.0000009536743164; + +double quaternionDot(const Quaternion &lhs, const Quaternion &rhs) { + return lhs.w * rhs.w + lhs.x * rhs.x + lhs.y * rhs.y + lhs.z * rhs.z; +} + +Quaternion add(const Quaternion &lhs, const Quaternion &rhs) { + return {lhs.w + rhs.w, lhs.x + rhs.x, lhs.y + rhs.y, lhs.z + rhs.z}; +} + +Quaternion scale(const Quaternion &value, double amount) { + return {value.w * amount, value.x * amount, value.y * amount, + value.z * amount}; +} + +// Behavior of 0x33BF8C0, including the binary's endpoint and near-parallel +// thresholds. The fallback is returned only for a numerically invalid dot +// product outside the tolerated normalized range. +Quaternion mgcSlerp(Quaternion from, Quaternion to, Quaternion fallback, + double amount) { + from = from.normalized(); + amount = std::min(amount, 1.0); + amount = std::max(amount, 0.0); + if (amount < kSlerpEndpointEpsilon) { + return from; + } + + to = to.normalized(); + if (amount > kSlerpNearParallel) { + return to; + } + + const double dot = quaternionDot(from, to); + const double absolute_dot = std::abs(dot); + if (absolute_dot >= kSlerpInvalidDot) { + return fallback; + } + if (absolute_dot > kSlerpNearParallel) { + const double signed_amount = dot < 0.0 ? -amount : amount; + return add(scale(from, 1.0 - amount), scale(to, signed_amount)) + .normalized(); + } + + const double angle = std::acos(absolute_dot); + const double inverse_sine = 1.0 / std::sin(angle); + const double from_weight = std::sin((1.0 - amount) * angle) * inverse_sine; + const double to_weight = + std::sin(amount * angle) * inverse_sine * (dot < 0.0 ? -1.0 : 1.0); + return add(scale(from, from_weight), scale(to, to_weight)); +} + +void pushRing(std::deque *history, double value, int capacity) { + if (capacity <= 0) { + return; + } + if (history->size() == static_cast(capacity)) { + history->pop_front(); + } + history->push_back(value); +} + +struct AxisAngle { + Vec3 axis{1.0, 0.0, 0.0}; + double angle = 0.0; +}; + +AxisAngle quaternionToAxisAngle(const Quaternion &input) { + const Quaternion q = input.normalized(); + const double vector_norm = std::sqrt(q.x * q.x + q.y * q.y + q.z * q.z); + if (vector_norm < 1.0e-6) { + return {}; + } + return {{q.x / vector_norm, q.y / vector_norm, q.z / vector_norm}, + 2.0 * std::acos(std::max(-1.0, std::min(q.w, 1.0)))}; +} + +Quaternion axisAngleToQuaternion(const Vec3 &rotation_vector) { + const double angle = norm(rotation_vector); + if (angle < 1.0e-6) { + return Quaternion::identity(); + } + return Quaternion::fromRotationVector(rotation_vector); +} + +Quaternion multiplyLeftToRight(const std::vector &values) { + Quaternion product = Quaternion::identity(); + for (const Quaternion &value : values) { + product = value * product; + } + return product; +} + +// The baseline path is a separate float-only routine in libgcastartup. Keep +// its arithmetic here rather than feeding its intermediate values through the +// app-wide double-precision Quaternion helpers: the latter erases the ULP +// differences that the original's adaptive future-domain gate preserves. +struct FloatQuaternion { + float x = 0.0F; + float y = 0.0F; + float z = 0.0F; + float w = 1.0F; +}; + +struct FloatAxisAngle { + float x = 1.0F; + float y = 0.0F; + float z = 0.0F; + float angle = 0.0F; +}; + +FloatQuaternion toFloatQuaternion(const Quaternion &value) { + return {static_cast(value.x), static_cast(value.y), + static_cast(value.z), static_cast(value.w)}; +} + +Quaternion toQuaternion(const FloatQuaternion &value) { + return {static_cast(value.w), static_cast(value.x), + static_cast(value.y), static_cast(value.z)}; +} + +float floatQuaternionDot(const FloatQuaternion &lhs, + const FloatQuaternion &rhs) { + // Every V25 quaternion primitive folds the xyzw lanes as (x,z) + (y,w): + // 0x3411824, 0x3411AE4 and 0x3411E1C all use EXT/FADD/FADDP. Do not use + // the conventional left-to-right four-term expression here. + const float xz = lhs.x * rhs.x + lhs.z * rhs.z; + const float yw = lhs.y * rhs.y + lhs.w * rhs.w; + return xz + yw; +} + +FloatQuaternion normalizeFloatQuaternion(FloatQuaternion value) { + const float xz = value.x * value.x + value.z * value.z; + const float yw = value.y * value.y + value.w * value.w; + const float inverse_length = 1.0F / std::sqrt(xz + yw); + value.x *= inverse_length; + value.y *= inverse_length; + value.z *= inverse_length; + value.w *= inverse_length; + return value; +} + +FloatQuaternion invertFloatQuaternion(const FloatQuaternion &value) { + const float squared_length = floatQuaternionDot(value, value); + FloatQuaternion inverse{-value.x, -value.y, -value.z, value.w}; + if (squared_length > 9.999999974752427e-7F) { + const float reciprocal = 1.0F / squared_length; + inverse.x *= reciprocal; + inverse.y *= reciprocal; + inverse.z *= reciprocal; + inverse.w *= reciprocal; + } + return inverse; +} + +FloatQuaternion multiplyFloatQuaternion(const FloatQuaternion &lhs, + const FloatQuaternion &rhs) { + // Exact addition tree of the shared V25 quaternion multiply helper + // (0x3411A28). The same primitive is used by the baseline and gyro paths. + const float x = + (lhs.y * rhs.z + (rhs.x * lhs.w + lhs.x * rhs.w)) - lhs.z * rhs.y; + const float y = + rhs.x * lhs.z + ((lhs.w * rhs.y - lhs.x * rhs.z) + lhs.y * rhs.w); + const float z = + ((lhs.x * rhs.y + lhs.w * rhs.z) - lhs.y * rhs.x) + lhs.z * rhs.w; + const float w = + ((lhs.w * rhs.w - lhs.x * rhs.x) - lhs.y * rhs.y) - lhs.z * rhs.z; + return {x, y, z, w}; +} + +#ifdef MGC_EIS_BASELINE_TRACE +void traceFloatQuaternion(const char *label, std::size_t index, + const FloatQuaternion &value) { + std::fprintf(stderr, "%s index=%zu q=%.9g,%.9g,%.9g,%.9g\n", label, + index, value.x, value.y, value.z, value.w); +} + +void traceFloatAxisAngle(const char *label, std::size_t index, + const FloatAxisAngle &value) { + std::fprintf(stderr, "%s index=%zu axis=%.9g,%.9g,%.9g angle=%.9g\n", + label, index, value.x, value.y, value.z, value.angle); +} +#endif + +FloatQuaternion slerpFloatQuaternion(FloatQuaternion from, + FloatQuaternion to, + FloatQuaternion fallback, float amount) { + from = normalizeFloatQuaternion(from); + amount = std::min(amount, 1.0F); + amount = std::max(amount, 0.0F); + if (amount < 9.999999974752427e-7F) { + return from; + } + + to = normalizeFloatQuaternion(to); + if (amount > 0.9999989867210388F) { + return to; + } + + const float cosine = floatQuaternionDot(from, to); + const float absolute_cosine = std::abs(cosine); + if (absolute_cosine >= 1.0000009536743164F) { + return fallback; + } + if (absolute_cosine > 0.9999989867210388F) { + // Unlike the general SLERP branch, 0x3411BA8 does not apply the sign of + // the dot product to `to` in its near-parallel linear path. + return normalizeFloatQuaternion( + {from.x * (1.0F - amount) + to.x * amount, + from.y * (1.0F - amount) + to.y * amount, + from.z * (1.0F - amount) + to.z * amount, + from.w * (1.0F - amount) + to.w * amount}); + } + + const float angle = ::acosf(absolute_cosine); + const float inverse_sine = 1.0F / ::sinf(angle); + const float from_weight = ::sinf((1.0F - amount) * angle) * inverse_sine; + const float to_weight = inverse_sine * + (cosine < 0.0F ? -::sinf(amount * angle) + : ::sinf(amount * angle)); + return {from.x * from_weight + to.x * to_weight, + from.y * from_weight + to.y * to_weight, + from.z * from_weight + to.z * to_weight, + from.w * from_weight + to.w * to_weight}; +} + +FloatAxisAngle toFloatAxisAngle(const FloatQuaternion &input) { + const FloatQuaternion value = normalizeFloatQuaternion(input); + const float xy = value.x * value.x + value.y * value.y; + const float vector_length = std::sqrt(xy + value.z * value.z); + if (vector_length < 9.999999974752427e-7F) { + return {}; + } + const float reciprocal = 1.0F / vector_length; + return {value.x * reciprocal, value.y * reciprocal, value.z * reciprocal, + 2.0F * ::acosf(value.w)}; +} + +FloatQuaternion fromFloatRotationVector(float x, float y, float z) { + // The baseline supplies a vector angle here, but V25 expands it back into + // axis+angle and calls 0x3411894, which normalizes the axis once more + // before sincosf. Preserve both float boundaries. + const float xy = x * x + y * y; + const float angle = std::sqrt(xy + z * z); + if (angle < 9.999999974752427e-7F) { + return {}; + } + const float reciprocal = 1.0F / angle; + const float axis_x = x * reciprocal; + const float axis_y = y * reciprocal; + const float axis_z = z * reciprocal; + const float axis_xy = axis_x * axis_x + axis_y * axis_y; + const float axis_reciprocal = + 1.0F / std::sqrt(axis_xy + axis_z * axis_z); + float sine = 0.0F; + float cosine = 1.0F; +#if defined(__APPLE__) + __sincosf(angle * 0.5F, &sine, &cosine); +#else + ::sincosf(angle * 0.5F, &sine, &cosine); +#endif + const float scale = sine * axis_reciprocal; + return {axis_x * scale, axis_y * scale, axis_z * scale, cosine}; +} + +float floatHalfAngleDistance(const FloatQuaternion &lhs, + const FloatQuaternion &rhs) { + const float cosine = floatQuaternionDot(normalizeFloatQuaternion(lhs), + normalizeFloatQuaternion(rhs)); + const float capped_high = cosine > 1.0F ? 1.0F : cosine; + const float capped = capped_high < -1.0F ? -1.0F : capped_high; + return ::acosf(std::abs(capped)); +} + +} // namespace + +Quaternion interpolatePose(const Quaternion &from, const Quaternion &to, + double amount, const Quaternion &fallback) { + return mgcSlerp(from, to, fallback, amount); +} + +double quaternionHalfAngleDistance(const Quaternion &lhs, + const Quaternion &rhs) { + const double normalized_dot = + quaternionDot(lhs.normalized(), rhs.normalized()); + return std::acos(std::abs(std::max(-1.0, std::min(normalized_dot, 1.0)))); +} + +Quaternion computeBaselineVirtualPose(const BaselinePoseWindow &window, + const Parameters ¶meters) { + const std::size_t half_window = + static_cast(parameters.half_window_frames); + if (window.older.size() > half_window || + window.future_primary.size() > half_window) { + throw std::invalid_argument( + "Baseline pose window exceeds the type-18 half-window"); + } + if (!(window.nominal_to_measured_period_ratio > 0.0)) { + throw std::invalid_argument("Frame-period ratio must be positive"); + } + + const FloatQuaternion current_selected = toFloatQuaternion( + parameters.use_secondary_pose_stream ? window.current.secondary + : window.current.primary); + FloatQuaternion previous_selected = toFloatQuaternion( + parameters.use_secondary_pose_stream ? window.previous.secondary + : window.previous.primary); + + // 0x22D66A4..0x22D6F8C: adaptively retained selected-stream deltas. + std::vector retained; + FloatQuaternion previous_selected_delta = multiplyFloatQuaternion( + current_selected, invertFloatQuaternion(previous_selected)); + retained.push_back(previous_selected_delta); + + // Complete primary-stream domain. The binary prepends older deltas and + // appends future deltas before computing its float-only running mean axis. + std::vector all_primary_deltas; + FloatQuaternion previous_primary = toFloatQuaternion(window.previous.primary); + all_primary_deltas.push_back(multiplyFloatQuaternion( + toFloatQuaternion(window.current.primary), + invertFloatQuaternion(previous_primary))); + + float historical_distance = 0.0F; + const float angular_scale = static_cast(parameters.domain_angular_scale); + const float distance_budget = + static_cast(parameters.domain_distance_budget); + for (std::size_t index = 0; index < window.older.size(); ++index) { + const PosePair &older = window.older[index]; + const FloatQuaternion older_selected = toFloatQuaternion( + parameters.use_secondary_pose_stream ? older.secondary : older.primary); + const FloatQuaternion selected_delta = multiplyFloatQuaternion( + previous_selected, invertFloatQuaternion(older_selected)); + const FloatQuaternion older_primary = toFloatQuaternion(older.primary); + const FloatQuaternion primary_delta = multiplyFloatQuaternion( + previous_primary, invertFloatQuaternion(older_primary)); + all_primary_deltas.insert(all_primary_deltas.begin(), primary_delta); + + historical_distance += angular_scale * + floatHalfAngleDistance(selected_delta, + previous_selected_delta); + if (historical_distance + static_cast(index + 1) < + distance_budget) { + retained.insert(retained.begin(), selected_delta); + } + previous_selected_delta = selected_delta; + previous_selected = older_selected; + previous_primary = older_primary; + } + + previous_primary = toFloatQuaternion(window.current.primary); + std::vector future_primary_deltas; + future_primary_deltas.reserve(window.future_primary.size()); + for (const Quaternion &future_primary : window.future_primary) { + const FloatQuaternion future = toFloatQuaternion(future_primary); + const FloatQuaternion delta = multiplyFloatQuaternion( + future, invertFloatQuaternion(previous_primary)); + all_primary_deltas.push_back(delta); + future_primary_deltas.push_back(delta); + previous_primary = future; + } + +#ifdef MGC_EIS_BASELINE_TRACE + for (std::size_t index = 0; index < all_primary_deltas.size(); ++index) { + traceFloatQuaternion("RECON_DOMAIN", index, all_primary_deltas[index]); + } +#endif + + FloatQuaternion remaining_product{}; + for (const FloatQuaternion &value : all_primary_deltas) { + remaining_product = multiplyFloatQuaternion(value, remaining_product); + } + FloatQuaternion remaining_mean = slerpFloatQuaternion( + {}, remaining_product, {}, + 1.0F / static_cast(all_primary_deltas.size())); + FloatAxisAngle mean_axis_angle = toFloatAxisAngle(remaining_mean); + + float future_distance = 0.0F; + FloatQuaternion previous_projected = previous_selected_delta; + + for (std::size_t index = 0; index < future_primary_deltas.size(); ++index) { + const FloatAxisAngle future_axis_angle = + toFloatAxisAngle(future_primary_deltas[index]); +#ifdef MGC_EIS_BASELINE_TRACE + traceFloatAxisAngle("RECON_MEAN_AXIS", index, mean_axis_angle); + traceFloatAxisAngle("RECON_FUTURE_AXIS", index, future_axis_angle); +#endif + // 0x22D6DC8..0x22D6DF0 first multiplies each mean-axis lane by the + // dot product, then multiplies that result by the future angle. Do not + // fold the angle into the dot product: these are distinct float rounds + // and the adaptive retention predicate is intentionally ULP-sensitive. + const float projected_dot = + future_axis_angle.x * mean_axis_angle.x + + future_axis_angle.y * mean_axis_angle.y + + future_axis_angle.z * mean_axis_angle.z; + const float projected_x = + (mean_axis_angle.x * projected_dot) * future_axis_angle.angle; + const float projected_y = + (mean_axis_angle.y * projected_dot) * future_axis_angle.angle; + const float projected_z = + (mean_axis_angle.z * projected_dot) * future_axis_angle.angle; + const FloatQuaternion projected = fromFloatRotationVector( + projected_x, projected_y, projected_z); + +#ifdef MGC_EIS_BASELINE_TRACE + traceFloatQuaternion("RECON_PROJECTED", index, projected); +#endif + + if (index > 0) { + future_distance += angular_scale * + floatHalfAngleDistance(projected, previous_projected); + if (future_distance + static_cast(index) < distance_budget) { + retained.push_back(previous_projected); + } + + // 0x22D6D2C indexes the complete domain by the future-loop index, + // right-multiplies its inverse into the running product, then rebuilds + // the remaining mean axis using count - index. + remaining_product = multiplyFloatQuaternion( + remaining_product, invertFloatQuaternion(all_primary_deltas[index])); + const float remaining_count = + static_cast(all_primary_deltas.size() - index); + remaining_mean = slerpFloatQuaternion( + {}, remaining_product, {}, 1.0F / remaining_count); + mean_axis_angle = toFloatAxisAngle(remaining_mean); + } + previous_projected = projected; + } + + FloatQuaternion retained_product{}; +#ifdef MGC_EIS_BASELINE_TRACE + for (std::size_t index = 0; index < retained.size(); ++index) { + traceFloatQuaternion("RECON_RETAINED", index, retained[index]); + } +#endif + for (const FloatQuaternion &value : retained) { + retained_product = multiplyFloatQuaternion(value, retained_product); + } + const float output_denominator = + static_cast(window.nominal_to_measured_period_ratio) * + static_cast(retained.size()); + return toQuaternion(slerpFloatQuaternion( + {}, retained_product, {}, 1.0F / output_denominator)); +} + +std::vector makeSymmetricHalfGaussian(int half_window_frames, + double sigma) { + if (half_window_frames < 0) { + throw std::invalid_argument("Gaussian half-window must be non-negative"); + } + if (!(sigma > 0.0)) { + throw std::invalid_argument("Gaussian sigma must be positive"); + } + + std::vector result( + static_cast(half_window_frames + 1)); + const double denominator = 2.0 * sigma * sigma; + double symmetric_sum = 0.0; + for (int distance = 0; distance <= half_window_frames; ++distance) { + const double unnormalized = + std::exp(-static_cast(distance * distance) / denominator); + result[static_cast(distance)] = unnormalized; + symmetric_sum += distance == 0 ? unnormalized : 2.0 * unnormalized; + } + for (double &weight : result) { + weight /= symmetric_sum; + } + return result; +} + +PoseCandidates accumulatePoseCandidates( + const std::vector &poses, + const Quaternion &reference_orientation, const Parameters ¶meters) { + const int half_window = parameters.half_window_frames; + const std::size_t expected_size = + static_cast(2 * half_window + 1); + if (poses.size() != expected_size) { + throw std::invalid_argument("Pose window must contain exactly 2*N+1 poses"); + } + + const std::vector wide_weights = + makeSymmetricHalfGaussian(half_window, parameters.gaussian_sigma); + const std::vector tight_weights = + makeSymmetricHalfGaussian(half_window, 1.0); + + // 0x22BC790 reverses the positive half of the sigma-1 kernel and + // renormalizes it by w[0] + sum(w[1..N]) == (1 + w[0]) / 2. + const double future_sum = + tight_weights.front() + (1.0 - tight_weights.front()) * 0.5; + std::vector future_weights( + static_cast(half_window + 1)); + for (int index = 0; index <= half_window; ++index) { + future_weights[static_cast(index)] = + tight_weights[static_cast(half_window - index)] / + future_sum; + } + + const Quaternion inverse_reference = reference_orientation.inverse(); + Quaternion wide = Quaternion::identity(); + Quaternion tight = Quaternion::identity(); + Quaternion future = Quaternion::identity(); + for (int signed_index = -half_window; signed_index <= half_window; + ++signed_index) { + const Quaternion relative = + poses[static_cast(signed_index + half_window)] * + inverse_reference; + const std::size_t distance = + static_cast(std::abs(signed_index)); + + // This left-multiplication order is the one emitted at 0x22BD96C, + // 0x22BD99C and 0x22BD9CC. It is deliberately not replaced with a + // tangent-space average. + wide = mgcSlerp(Quaternion::identity(), relative, + Quaternion::identity(), wide_weights[distance]) * + wide; + tight = mgcSlerp(Quaternion::identity(), relative, + Quaternion::identity(), tight_weights[distance]) * + tight; + if (signed_index >= 0) { + const std::size_t future_index = + static_cast(signed_index); + future = mgcSlerp(Quaternion::identity(), relative, + Quaternion::identity(), + future_weights[future_index]) * + future; + } + } + + return { + (wide * reference_orientation).normalized(), + (tight * reference_orientation).normalized(), + (future * reference_orientation).normalized(), + }; +} + +double normalizeProtrusionScore(double raw_score, + const Parameters ¶meters) { + const double non_negative = std::max(raw_score, 0.0); + const double normalized = + std::pow(non_negative / parameters.protrusion_score_divisor, + parameters.protrusion_score_exponent); + return std::min(normalized, 1.0); +} + +double meanNormalizedProtrusionScore(const std::vector &raw_scores, + const Parameters ¶meters) { + if (raw_scores.empty()) { + return 0.0; + } + double sum = 0.0; + for (const double raw_score : raw_scores) { + sum += normalizeProtrusionScore(raw_score, parameters); + } + return sum / static_cast(raw_scores.size()); +} + +double signedPointProtrusion(const ProtrusionRect &allowed, + const Vec2 &point) { + if (!(allowed.left < allowed.right) || !(allowed.top < allowed.bottom)) { + throw std::invalid_argument("Protrusion rectangle must have positive area"); + } + + const double beyond_left = allowed.left - point.x; + const double beyond_right = point.x - allowed.right; + const double beyond_top = allowed.top - point.y; + const double beyond_bottom = point.y - allowed.bottom; + const double outside_x = std::max({beyond_left, beyond_right, 0.0}); + const double outside_y = std::max({beyond_top, beyond_bottom, 0.0}); + if (outside_x > 0.0 || outside_y > 0.0) { + return std::hypot(outside_x, outside_y); + } + return std::max( + {beyond_left, beyond_right, beyond_top, beyond_bottom}); +} + +double maximumBoundaryProtrusion(const ProtrusionRect &allowed, + const std::vector &boundary_points) { + double maximum = -1.0; + for (const Vec2 &point : boundary_points) { + maximum = std::max(maximum, signedPointProtrusion(allowed, point)); + } + return maximum; +} + +int effectiveFutureIndex(double gyro_activity_signal, int score_count, + const Parameters ¶meters) { + if (score_count <= 0) { + return -1; + } + // ARM64 FCVTAS matches std::lround for finite values: nearest integer with + // halfway cases rounded away from zero. + const long selected = std::lround( + gyro_activity_signal * (3.0 - parameters.half_window_frames) + + parameters.half_window_frames); + return std::min(score_count - 1, static_cast(selected)); +} + +bool shouldProbeFutureFullGrid(double current_raw_score, + double next_raw_score) { + return next_raw_score >= Parameters::kFutureScoreThreshold && + next_raw_score - current_raw_score >= + Parameters::kFutureScoreDeltaThreshold; +} + +double combineSpatialPressure(double motion_blend, + double current_full_grid_score, + double mean_two_row_score) { + const double weighted_future = + std::cos(motion_blend * kPi * 0.5) * mean_two_row_score; + return std::min(std::max(current_full_grid_score, weighted_future), 1.0); +} + +GyroActivityMetrics computeGyroActivityMetrics( + const std::vector &rotation_vectors, + const Parameters ¶meters) { + constexpr double kActivityEpsilon = 9.999999974752427e-7; + GyroActivityMetrics result; + if (rotation_vectors.empty()) { + return result; + } + + Vec3 squared_sum; + for (const Vec3 &value : rotation_vectors) { + result.mean += value; + squared_sum.x += value.x * value.x; + squared_sum.y += value.y * value.y; + squared_sum.z += value.z * value.z; + } + const double count = static_cast(rotation_vectors.size()); + result.mean = result.mean / count; + result.standard_deviation = { + std::sqrt(std::max(squared_sum.x / count - + result.mean.x * result.mean.x, + 0.0)), + std::sqrt(std::max(squared_sum.y / count - + result.mean.y * result.mean.y, + 0.0)), + std::sqrt(std::max(squared_sum.z / count - + result.mean.z * result.mean.z, + 0.0)), + }; + + const double standard_deviation_sum = result.standard_deviation.x + + result.standard_deviation.y + + result.standard_deviation.z; + const double mean_l1 = std::abs(result.mean.x) + std::abs(result.mean.y) + + std::abs(result.mean.z); + if (standard_deviation_sum < kActivityEpsilon) { + result.motion_blend = mean_l1 > kActivityEpsilon ? 1.0 : 0.0; + } else { + const double ratio = mean_l1 / standard_deviation_sum; + const double logit = parameters.motion_logistic_offset + + parameters.motion_logistic_scale * ratio; + result.motion_blend = 1.0 / (std::exp(-logit) + 1.0); + } + + const double mean_magnitude = norm(result.mean); + if (mean_magnitude > kActivityEpsilon) { + double alignment_sum = 0.0; + for (const Vec3 &value : rotation_vectors) { + const double magnitude = norm(value); + const double divisor = magnitude > kActivityEpsilon ? magnitude : 1.0; + const double cosine = dot(result.mean, value) / + (mean_magnitude * divisor); + alignment_sum += std::max(cosine, 0.0); + } + result.directional_alignment = + std::min(alignment_sum / count, 1.0); + } + return result; +} + +EffectiveCropMarginResult updateEffectiveCropMargin( + const EffectiveCropMarginInput &input, EffectiveCropMarginState *state) { + if (state == nullptr) { + throw std::invalid_argument("Effective crop-margin state is null"); + } + if (input.filtering_method == 4 && !(input.method4_scale > 0.0)) { + throw std::invalid_argument("Method-4 crop scale must be positive"); + } + + const double frame_scale = std::max(input.frame_scale, 1.0); + const double unscaled_margin = + 0.5 * (1.0 - (1.0 - 2.0 * input.configured_crop_ratio) / + frame_scale); + const double method_scale = + input.filtering_method == 4 ? input.method4_scale : 1.0; + const double current_margin = + std::min(input.maximum_margin, unscaled_margin / method_scale); + + double filtering_margin = current_margin; + if (input.filtering_enabled && input.frame_mode != 5) { + if (input.frame_mode == 1) { + if (current_margin > state->filtering_margin) { + filtering_margin = + state->filtering_margin * input.filter_alpha + + current_margin * (1.0 - input.filter_alpha); + } + } else { + const double filtered = + state->filtering_margin * input.filter_alpha + + input.configured_crop_ratio * (1.0 - input.filter_alpha); + filtering_margin = std::min(current_margin, filtered); + } + } + state->filtering_margin = filtering_margin; + + double optimization_input_margin = filtering_margin; + if (input.frame_mode != 1) { + const double mixed = + (1.0 - input.secondary_mix) * filtering_margin + + input.secondary_margin * input.secondary_mix; + optimization_input_margin = std::min(filtering_margin, mixed); + } + + if (input.frame_mode == 5) { + state->optimization_margin = current_margin; + } else { + const bool zero_history_weight = + input.filtering_method == 4 && + input.method4_zero_optimization_history_weight; + const double history_weight = + zero_history_weight ? 0.0 : input.filter_alpha; + state->optimization_margin = + state->optimization_margin * history_weight + + optimization_input_margin * (1.0 - history_weight); + } + + return {current_margin, state->filtering_margin, optimization_input_margin, + state->optimization_margin}; +} + +TemporalPressureFilter::TemporalPressureFilter(Parameters parameters) + : parameters_(parameters), + release_weight_(parameters.pressure_release_initial) {} + +double TemporalPressureFilter::update(double pressure) { + double filtered = pressure; + if (!history_.empty()) { + const double previous = history_.back(); + if (pressure >= previous) { + release_weight_ = parameters_.pressure_release_initial; + } else { + release_weight_ = + std::max(release_weight_ - parameters_.pressure_release_step, 0.0); + filtered = release_weight_ * previous + + (1.0 - release_weight_) * pressure; + } + } + pushRing(&history_, filtered, parameters_.history_capacity); + return filtered; +} + +void TemporalPressureFilter::reset() { + history_.clear(); + release_weight_ = parameters_.pressure_release_initial; +} + +LowProtrusionMotionFilter::LowProtrusionMotionFilter(Parameters parameters) + : parameters_(parameters) {} + +double LowProtrusionMotionFilter::update(double current_motion_blend, + double protrusion_score) { + double filtered = current_motion_blend; + if (parameters_.low_protrusion_threshold > protrusion_score && + !history_.empty() && current_motion_blend > history_.back()) { + filtered = parameters_.motion_rise_previous_weight * history_.back() + + (1.0 - parameters_.motion_rise_previous_weight) * + current_motion_blend; + } + pushRing(&history_, filtered, parameters_.history_capacity); + return filtered; +} + +void LowProtrusionMotionFilter::reset() { history_.clear(); } + +double finalPoseBlend(double pressure, double frame_blend) { + // V25 0x22FDF94 combines the temporal crop pressure with frame-state +132 + // before the last lookahead pose blend. The later method-4 outer crop pass + // applies its correction directly and does not call this scalar helper. + return 1.0 - (1.0 - pressure) * frame_blend; +} + +LookaheadPoseComposer::LookaheadPoseComposer(Parameters parameters) + : motion_filter_(parameters), pressure_filter_(parameters) {} + +LookaheadCompositionResult +LookaheadPoseComposer::update(const LookaheadCompositionInput &input) { + LookaheadCompositionResult result; + + // 0x22BDA3C takes the newest virtual-pose history entry as its first + // endpoint, then pressure-selects the sigma-6 candidate. + result.two_row_pose = + mgcSlerp(input.previous_output_pose, input.candidates.wide, + input.previous_output_pose, input.two_row_protrusion_score); + + // 0x22BDEE0: only low-protrusion upward motion changes are rate-limited. + result.filtered_motion_blend = motion_filter_.update( + input.current_motion_blend, input.two_row_protrusion_score); + result.intermediate_pose = result.two_row_pose; + if (input.preblend_tight_candidate) { + result.intermediate_pose = + mgcSlerp(result.intermediate_pose, input.candidates.tight, + result.intermediate_pose, input.tight_candidate_blend); + } + result.intermediate_pose = + mgcSlerp(result.intermediate_pose, input.motion_pose, + result.intermediate_pose, result.filtered_motion_blend); + + // 0x22BE240 receives the filtered motion blend in ARM64 S0. It is not a + // gyro-speed signal. Rising spatial pressure is immediate; falling + // pressure uses the asymmetric release state. + result.spatial_pressure = + combineSpatialPressure(result.filtered_motion_blend, + input.current_full_grid_pressure, + input.mean_future_pressure); + result.temporal_pressure = pressure_filter_.update(result.spatial_pressure); + result.final_blend = + finalPoseBlend(result.temporal_pressure, input.frame_blend); + result.output_pose = + mgcSlerp(result.intermediate_pose, input.candidates.tight, + result.intermediate_pose, result.final_blend); + return result; +} + +void LookaheadPoseComposer::reset() { + motion_filter_.reset(); + pressure_filter_.reset(); +} + +} // namespace mgc_eis_reconstruction::type18 diff --git a/research/mgc_eis_reconstruction/mgc_type18_lookahead.hpp b/research/mgc_eis_reconstruction/mgc_type18_lookahead.hpp new file mode 100644 index 00000000..87955359 --- /dev/null +++ b/research/mgc_eis_reconstruction/mgc_type18_lookahead.hpp @@ -0,0 +1,291 @@ +#pragma once + +#include "mgc_eis_reconstruction.hpp" + +#include +#include +#include + +namespace mgc_eis_reconstruction::type18 { + +// Exact constants selected by motion_filtering_params.cc for device type 18 +// (switch case 0x12) and consumed by the non-Ceres method-4 lookahead path. +// Field offsets refer to the original parameter block at 0x22D6164. +struct Parameters { + int domain_transform_window_length = 30; // +188 + double domain_angular_scale = 2000.0; // +192 + double domain_distance_budget = 32.0; // +196 + double horizon_statistics_window_seconds = 0.7; // +208 + bool use_secondary_pose_stream = true; // +220 + int half_window_frames = 10; // +264 + // The lookahead constructor copies this parameter block at offset +80. + // Consequently accumulate_weighted_gyro_poses() reads this selector at + // lookahead +352 == parameters +272. Type 18 leaves it at the factory + // default of zero and therefore queries/accumulates the primary pose. + bool candidate_uses_secondary_pose_stream = false; // +272 + double gaussian_sigma = 6.0; // +276 + double protrusion_score_divisor = 0.2; // +280 + double protrusion_score_exponent = 2.0; // +284 + double pressure_release_initial = 0.95; // +288 + double pressure_release_step = 0.05; // +292 + double motion_logistic_offset = -8.3469; // +296 + double motion_logistic_scale = 10.7854; // +300 + double low_protrusion_threshold = 0.001; // +304 + double motion_rise_previous_weight = 0.925; // +308 + double motion_direction_gate = 0.01; // +312 + // Projected rolling-shutter motion controller at 0x22D9520. The + // nonlinear filter copies the parameter block beginning at filter +8; + // therefore the binary reads this sequence at filter +364..+416. These + // values are decoded directly from V25's type-18 factory, not inferred + // from the controller branches. + double projected_motion_large_slope = 1200.0; // params +356 + double projected_motion_center = 0.006; // params +360 + double projected_motion_small_slope = 26.2687; // params +364 + double projected_motion_small_offset = -0.0525; // params +368 + double projected_motion_threshold = 0.002798; // params +372 + double projected_blend_fall_previous_weight = 0.8; // params +376 + double projected_peak_threshold = 0.01; // params +380 + int projected_history_window_frames = 30; // params +384 + int projected_history_min_intervals = 2; // params +388 + double projected_history_rate_center = 15.0; // params +392 + double projected_history_rate_slope = 150.0; // params +396 + double projected_gain_rise_previous_weight = 0.5; // params +400 + double projected_gain_fall_previous_weight = 0.95; // params +404 + double projected_pose_motion_limit = 0.5; // params +408 + double projected_candidate_max_blend = 0.2; + int history_capacity = 50; // +68 + bool lookahead_enabled = true; // +344 + bool nonlinear_pose_blend_enabled = true; // +352 + // The factory selects false for profile 7 and true for type 18. V25 passes + // this directly to build_real_camera_projection_rows(), where it gates the + // optional lens-offset-to-intrinsics transform. It is not a stabilization + // gain and must never be interpreted as one. + bool apply_lens_offsets_to_intrinsics = true; // +416 + bool ceres_optimization_enabled = false; // +526 + + static constexpr std::int64_t kFramePeriodNs = 33'333'333; + static constexpr std::int64_t kActivitySamplePeriodNs = 33'333'332; + static constexpr double kFutureScoreThreshold = 0.06; + static constexpr double kFutureScoreDeltaThreshold = 0.04; +}; + +// The nonlinear filter receives two gyro-pose streams from QueryPose. Device +// type 18 selects the secondary stream for the adaptive-domain decisions but +// retains the primary stream for its symmetric past/future motion axis. +struct PosePair { + Quaternion primary; + Quaternion secondary; +}; + +// Public form of V25 0x33BF8C0 used by every type-18 pose blend. The separate +// fallback argument is observable in the original ABI and is returned only +// for an invalid normalized dot product. +Quaternion interpolatePose(const Quaternion &from, const Quaternion &to, + double amount, + const Quaternion &fallback); + +struct BaselinePoseWindow { + PosePair current; + PosePair previous; + // Ordered newest to oldest: t-2, t-3, ... . MGC stops at the first pose + // query failure, so fewer than half_window_frames entries are valid. + std::vector older; + // Ordered nearest to farthest: t+1, t+2, ... . Only the primary stream is + // queried for future timestamps. + std::vector future_primary; + // 33,333,000 / measured frame period, recovered at 0x22966B8..0x22966C8. + double nominal_to_measured_period_ratio = 1.0; +}; + +// Exact scalar primitive at 0x33BF600: acos(abs(dot(normalize(a), +// normalize(b)))). It is a quaternion half-angle, not the full SO(3) angle. +double quaternionHalfAngleDistance(const Quaternion &lhs, + const Quaternion &rhs); + +// Reconstructs the active method-4 branch of 0x2296470. The returned +// quaternion is a per-frame baseline virtual-camera increment; the caller at +// 0x229BAB4/0x229BD74 composes it with the persistent virtual pose before the +// lookahead crop-pressure stages. +Quaternion computeBaselineVirtualPose( + const BaselinePoseWindow &window, + const Parameters ¶meters = Parameters{}); + +// MGC stores only the center-to-edge half of a symmetric Gaussian. The +// returned vector contains weights for distances [0, half_window_frames] and +// is normalized against the complete symmetric kernel. +std::vector makeSymmetricHalfGaussian(int half_window_frames, + double sigma); + +struct PoseCandidates { + Quaternion wide; + Quaternion tight; + Quaternion future; +}; + +// Reconstructs 0x22BD844. poses must be ordered from -N through +N around the +// reference frame and therefore contain exactly 2*N+1 quaternions. +PoseCandidates accumulatePoseCandidates( + const std::vector &poses, + const Quaternion &reference_orientation, + const Parameters ¶meters = Parameters{}); + +double normalizeProtrusionScore( + double raw_score, const Parameters ¶meters = Parameters{}); + +double meanNormalizedProtrusionScore( + const std::vector &raw_scores, + const Parameters ¶meters = Parameters{}); + +struct ProtrusionRect { + double left = 0.0; + double right = 0.0; + double top = 0.0; + double bottom = 0.0; +}; + +// Reconstructs geometry helper 0x588A840. The result is negative inside the +// allowed rectangle, zero on its edge, and positive outside. Corner overflow +// uses Euclidean distance. +double signedPointProtrusion(const ProtrusionRect &allowed, + const Vec2 &point); + +double maximumBoundaryProtrusion(const ProtrusionRect &allowed, + const std::vector &boundary_points); + +// 0x22BE240 reduces the future horizon as the gyro activity signal rises. +// score_count is the number of already computed two-row protrusion scores. +int effectiveFutureIndex(double gyro_activity_signal, int score_count, + const Parameters ¶meters = Parameters{}); + +bool shouldProbeFutureFullGrid(double current_raw_score, + double next_raw_score); + +double combineSpatialPressure(double motion_blend, + double current_full_grid_score, + double mean_two_row_score); + +struct GyroActivityMetrics { + Vec3 mean; + Vec3 standard_deviation; + double motion_blend = 0.0; + double directional_alignment = 0.0; +}; + +// Scalar/vector core of 0x22CF250 after its gyro records have been collected +// or resampled. Type 18 derives motion_blend from mean-L1/stddev-sum with its +// logistic constants, and derives the future-horizon signal from the mean +// non-negative cosine alignment with the window's mean motion direction. +GyroActivityMetrics computeGyroActivityMetrics( + const std::vector &rotation_vectors, + const Parameters ¶meters = Parameters{}); + +// Scalar inputs consumed by 0x229DCC8. The two persistent margins are kept +// separate because MGC returns filtering_margin (+3168) to the packed frame +// state while updating optimization_margin (+3172) from the optional +// secondary-margin blend. +struct EffectiveCropMarginInput { + double configured_crop_ratio = 0.0; // engine +32 + double frame_scale = 1.0; // frame metadata +44 + int filtering_method = 4; // frame metadata +224 + int frame_mode = 1; // frame metadata +184 + double method4_scale = 1.0; // engine +3164 + double maximum_margin = 0.0; // engine +632 + double filter_alpha = 0.0; // engine +640 + bool filtering_enabled = false; // engine +533 + double secondary_margin = 0.0; // engine +636 + double secondary_mix = 0.0; // ARM64 S0 / a5 + // engine +74: when non-zero in method 4, 0x229DDDC..0x229DDE0 selects a + // zero history weight for optimization_margin. + bool method4_zero_optimization_history_weight = false; +}; + +struct EffectiveCropMarginState { + double filtering_margin = 0.0; // engine +3168 + double optimization_margin = 0.0; // engine +3172 +}; + +struct EffectiveCropMarginResult { + double current_margin = 0.0; + double filtering_margin = 0.0; + double optimization_input_margin = 0.0; + double optimization_margin = 0.0; +}; + +// Reconstructs the scalar state transitions of 0x229DCC8. The original also +// emits a small frame-geometry object through sub_588A964; that independent +// geometry packaging is intentionally not represented by this scalar API. +EffectiveCropMarginResult updateEffectiveCropMargin( + const EffectiveCropMarginInput &input, EffectiveCropMarginState *state); + +class TemporalPressureFilter { +public: + explicit TemporalPressureFilter(Parameters parameters = {}); + + // Exact release behavior at the end of 0x22BE240. Rising pressure is + // applied immediately. Falling pressure is blended with the previous frame + // using a coefficient that decreases by pressure_release_step per frame. + double update(double pressure); + void reset(); + +private: + Parameters parameters_; + std::deque history_; + double release_weight_; +}; + +class LowProtrusionMotionFilter { +public: + explicit LowProtrusionMotionFilter(Parameters parameters = {}); + + // Reconstructs the scalar branch in 0x22BDEE0. Only a rising motion blend + // under very low protrusion is slowed; all other changes pass through. + double update(double current_motion_blend, double protrusion_score); + void reset(); + +private: + Parameters parameters_; + std::deque history_; +}; + +double finalPoseBlend(double pressure, double frame_blend); + +struct LookaheadCompositionInput { + PoseCandidates candidates; + // 0x22BDA3C starts its first blend from the newest output-pose ring entry, + // or identity when that ring is empty. + Quaternion previous_output_pose = Quaternion::identity(); + Quaternion motion_pose = Quaternion::identity(); // frame state +112 + double two_row_protrusion_score = 0.0; + double current_motion_blend = 0.0; // frame state +128 + bool preblend_tight_candidate = false; // lookahead object +432 + double tight_candidate_blend = 0.0; // frame state +136 + double current_full_grid_pressure = 0.0; + double mean_future_pressure = 0.0; + double frame_blend = 0.0; // frame state +132 +}; + +struct LookaheadCompositionResult { + Quaternion two_row_pose; + Quaternion intermediate_pose; + Quaternion output_pose; + double filtered_motion_blend = 0.0; + double spatial_pressure = 0.0; + double temporal_pressure = 0.0; + double final_blend = 0.0; +}; + +// Stateful reconstruction of 0x22BDA3C -> 0x22BDEE0 -> 0x22BE240 after the +// geometry evaluators have produced their scalar protrusion pressures. +class LookaheadPoseComposer { +public: + explicit LookaheadPoseComposer(Parameters parameters = {}); + + LookaheadCompositionResult update(const LookaheadCompositionInput &input); + void reset(); + +private: + LowProtrusionMotionFilter motion_filter_; + TemporalPressureFilter pressure_filter_; +}; + +} // namespace mgc_eis_reconstruction::type18 diff --git a/research/mgc_eis_reconstruction/mgc_type18_projection.cpp b/research/mgc_eis_reconstruction/mgc_type18_projection.cpp new file mode 100644 index 00000000..4282a7aa --- /dev/null +++ b/research/mgc_eis_reconstruction/mgc_type18_projection.cpp @@ -0,0 +1,421 @@ +#include "mgc_type18_projection.hpp" + +#include +#include +#include +#include +#include +#include + +namespace mgc_eis_reconstruction::type18 { +namespace { + +const Mat3 &matrixForRow(const std::vector &matrices, + std::size_t row, std::size_t row_count, + const char *label) { + if (matrices.size() == 1) { + return matrices.front(); + } + if (matrices.size() == row_count) { + return matrices[row]; + } + throw std::invalid_argument(std::string(label) + + " must contain one or one-per-row matrix"); +} + +Mat3 fitHomography(const std::array &source, + const std::array &destination) { + // h22 is fixed to one, leaving the same eight projective degrees of + // freedom solved by geometry helper 0x5886CD8. + std::array, 8> augmented{}; + for (std::size_t point = 0; point < source.size(); ++point) { + const double x = source[point].x; + const double y = source[point].y; + const double u = destination[point].x; + const double v = destination[point].y; + auto &x_equation = augmented[point * 2]; + x_equation = {x, y, 1.0, 0.0, 0.0, 0.0, -u * x, -u * y, u}; + auto &y_equation = augmented[point * 2 + 1]; + y_equation = {0.0, 0.0, 0.0, x, y, 1.0, -v * x, -v * y, v}; + } + + for (std::size_t column = 0; column < 8; ++column) { + std::size_t pivot = column; + for (std::size_t row = column + 1; row < 8; ++row) { + if (std::abs(augmented[row][column]) > + std::abs(augmented[pivot][column])) { + pivot = row; + } + } + if (std::abs(augmented[pivot][column]) <= + std::numeric_limits::epsilon()) { + throw std::invalid_argument("Scanline quadrilateral is degenerate"); + } + if (pivot != column) { + std::swap(augmented[pivot], augmented[column]); + } + + const double divisor = augmented[column][column]; + for (std::size_t entry = column; entry < 9; ++entry) { + augmented[column][entry] /= divisor; + } + for (std::size_t row = 0; row < 8; ++row) { + if (row == column) { + continue; + } + const double factor = augmented[row][column]; + for (std::size_t entry = column; entry < 9; ++entry) { + augmented[row][entry] -= factor * augmented[column][entry]; + } + } + } + + Mat3 result = Mat3::identity(); + result.at(0, 0) = augmented[0][8]; + result.at(0, 1) = augmented[1][8]; + result.at(0, 2) = augmented[2][8]; + result.at(1, 0) = augmented[3][8]; + result.at(1, 1) = augmented[4][8]; + result.at(1, 2) = augmented[5][8]; + result.at(2, 0) = augmented[6][8]; + result.at(2, 1) = augmented[7][8]; + return result; +} + +ProtrusionRect normalizedRect(const ProtrusionRect &rect, double width, + double height) { + return {rect.left / width, rect.right / width, rect.top / height, + rect.bottom / height}; +} + +std::array rectangleCorners(const ProtrusionRect &rect) { + return {{{rect.left, rect.top}, + {rect.right, rect.top}, + {rect.left, rect.bottom}, + {rect.right, rect.bottom}}}; +} + +} // namespace + +std::vector +makeRollingShutterRowOffsets(std::int64_t rolling_shutter_ns, int row_count) { + if (row_count <= 0) { + throw std::invalid_argument("Rolling-shutter row count must be positive"); + } + if (row_count == 1) { + return {0}; + } + + std::vector offsets; + offsets.reserve(static_cast(row_count)); + const std::int64_t denominator = row_count - 1; + for (int row = 0; row < row_count; ++row) { + offsets.push_back(static_cast(row) * rolling_shutter_ns / + denominator); + } + return offsets; +} + +std::array makeBoundingRowOffsets( + std::int64_t rolling_shutter_ns, + const std::array &source_rows, double frame_height) { + const std::int64_t integer_height = + static_cast(static_cast(frame_height)); + if (integer_height == 0) { + throw std::invalid_argument("Frame height must not truncate to zero"); + } + const float skew = static_cast(rolling_shutter_ns); + return { + static_cast(static_cast(source_rows[0]) * skew) / + integer_height, + static_cast(static_cast(source_rows[1]) * skew) / + integer_height, + }; +} + +std::int64_t adjustGyroQueryTimestamp(std::int64_t requested_ns, + std::int64_t newest_gyro_ns, + std::int64_t tolerance_ns) { + const std::int64_t gap = requested_ns - newest_gyro_ns; + if (gap > 0 && gap < tolerance_ns && newest_gyro_ns >= 0) { + return newest_gyro_ns; + } + return requested_ns; +} + +Mat3 makeCameraProjection(const Mat3 &intrinsics, + const Quaternion &orientation) { + // 0x229B7AC writes R first and 0x5885F18 performs lhs = rhs * lhs. + return intrinsics * Mat3::fromQuaternion(orientation); +} + +std::vector buildRealCameraProjectionRows( + const std::vector &actual_orientations, + const std::vector &intrinsics) { + if (actual_orientations.empty()) { + return {}; + } + std::vector result; + result.reserve(actual_orientations.size()); + for (std::size_t row = 0; row < actual_orientations.size(); ++row) { + result.push_back(makeCameraProjection( + matrixForRow(intrinsics, row, actual_orientations.size(), + "Real intrinsics"), + actual_orientations[row])); + } + return result; +} + +std::vector buildVirtualCameraProjectionRows( + const Quaternion &base_virtual_orientation, + const std::vector &row_relative_orientations, + const std::vector &intrinsics) { + const std::size_t row_count = + row_relative_orientations.empty() ? 1 + : row_relative_orientations.size(); + std::vector result; + result.reserve(row_count); + for (std::size_t row = 0; row < row_count; ++row) { + const Quaternion orientation = + row_relative_orientations.empty() + ? base_virtual_orientation + : row_relative_orientations[row] * base_virtual_orientation; + result.push_back(makeCameraProjection( + matrixForRow(intrinsics, row, row_count, "Virtual intrinsics"), + orientation)); + } + return result; +} + +std::vector composeDenseWarpRows( + const std::vector &real_projections, + const std::vector &virtual_projections, + bool virtual_projection_per_row, const Mat3 &injected_projection) { + if (real_projections.empty()) { + return {}; + } + if (virtual_projections.empty()) { + throw std::invalid_argument("Virtual projection vector is empty"); + } + if (virtual_projection_per_row && + virtual_projections.size() != real_projections.size()) { + throw std::invalid_argument( + "Per-row real and virtual projection counts must match"); + } + + std::vector result; + result.reserve(real_projections.size()); + for (std::size_t row = 0; row < real_projections.size(); ++row) { + const Mat3 &virtual_projection = + virtual_projection_per_row ? virtual_projections[row] + : virtual_projections.front(); + result.push_back((virtual_projection * injected_projection) * + real_projections[row].inverse()); + } + return result; +} + +Mat3 convertPixelHomographyToClip(const Mat3 &pixel_homography, + double frame_width, + double frame_height) { + if (!(frame_width > 0.0) || !(frame_height > 0.0)) { + throw std::invalid_argument("Frame dimensions must be positive"); + } + const Mat3 clip_to_pixel{{ + frame_width * 0.5, 0.0, frame_width * 0.5, + 0.0, -frame_height * 0.5, frame_height * 0.5, + 0.0, 0.0, 1.0, + }}; + const Mat3 pixel_to_clip{{ + 2.0 / frame_width, 0.0, -1.0, + 0.0, -2.0 / frame_height, 1.0, + 0.0, 0.0, 1.0, + }}; + Mat3 result = pixel_to_clip * pixel_homography * clip_to_pixel; + const double scale = result.at(2, 2); + if (std::abs(scale) <= std::numeric_limits::epsilon()) { + throw std::domain_error("Clip homography has a zero normalization term"); + } + for (double &value : result.v) { + value /= scale; + } + return result; +} + +Mat3 applyCropZoomToClipHomography(const Mat3 &clip_homography, + double zoom_factor) { + if (zoom_factor == 0.0 || !std::isfinite(zoom_factor)) { + throw std::invalid_argument("Crop zoom factor must be finite and nonzero"); + } + Mat3 result = clip_homography; + // homography_transform.cc::Zoom at V25 0x5666FA0 divides precisely the + // third row (h20, h21, h22). Do not renormalize h22 afterwards: qhi/iha + // consumes the homogeneous w and the projective scale is the crop itself. + result.at(2, 0) /= zoom_factor; + result.at(2, 1) /= zoom_factor; + result.at(2, 2) /= zoom_factor; + return result; +} + +ProjectionProtrusionResult evaluateProjectionProtrusion( + const std::vector &inv_real_projections, + const std::vector &virtual_projections, + const ProtrusionRect &input_interval, + const ProtrusionRect &output_interval, + const ProtrusionRect &allowed, + const std::vector &input_protrusion_mask, double frame_width, + double frame_height) { + if (inv_real_projections.size() < 2) { + throw std::invalid_argument( + "At least two inverse real projections are required"); + } + if (virtual_projections.empty()) { + throw std::invalid_argument("Virtual projection vector is empty"); + } + if (virtual_projections.size() >= 2 && + virtual_projections.size() != inv_real_projections.size()) { + throw std::invalid_argument( + "Real and per-row virtual projection counts must match"); + } + const std::size_t interval_count = inv_real_projections.size() - 1; + if (input_protrusion_mask.size() < interval_count) { + throw std::invalid_argument( + "Input protrusion mask is shorter than scanline interval count"); + } + if (!(input_interval.left < input_interval.right) || + !(input_interval.top < input_interval.bottom) || + !(output_interval.left < output_interval.right) || + !(output_interval.top < output_interval.bottom)) { + throw std::invalid_argument("Projection intervals must have positive area"); + } + if (!(frame_width > 0.0) || !(frame_height > 0.0)) { + throw std::invalid_argument("Frame dimensions must be positive"); + } + + ProjectionProtrusionResult result; + result.worst_interval_mask.assign(interval_count, false); + const ProtrusionRect normalized_allowed = + normalizedRect(allowed, frame_width, frame_height); + const double input_step = + (input_interval.bottom - input_interval.top) / + static_cast(interval_count); + const double output_step = + (output_interval.bottom - output_interval.top) / + static_cast(interval_count); + + for (std::size_t interval = 0; interval < interval_count; ++interval) { + if (!input_protrusion_mask[interval]) { + continue; + } + const double input_top = + input_interval.top + input_step * static_cast(interval); + const double input_bottom = input_interval.top + + input_step * static_cast(interval + 1); + const double output_top = + output_interval.top + output_step * static_cast(interval); + const double output_bottom = output_interval.top + + output_step * static_cast(interval + 1); + + const ProtrusionRect source_rect{input_interval.left, + input_interval.right, input_top, + input_bottom}; + const std::array source = rectangleCorners(source_rect); + const std::size_t virtual_top = + virtual_projections.size() >= 2 ? interval : 0; + const std::size_t virtual_bottom = + virtual_projections.size() >= 2 ? interval + 1 : 0; + const Mat3 top_projection = + virtual_projections[virtual_top] * inv_real_projections[interval]; + const Mat3 bottom_projection = + virtual_projections[virtual_bottom] * + inv_real_projections[interval + 1]; + const std::array projected{ + top_projection.transformPoint(source[0]), + top_projection.transformPoint(source[1]), + bottom_projection.transformPoint(source[2]), + bottom_projection.transformPoint(source[3]), + }; + + const Mat3 output_to_input = fitHomography(source, projected).inverse(); + const ProtrusionRect output_rect{output_interval.left, + output_interval.right, output_top, + output_bottom}; + const std::array output_corners = rectangleCorners(output_rect); + double interval_maximum = -1'000'000.0; + for (const Vec2 &output_corner : output_corners) { + const Vec2 input_point = output_to_input.transformPoint(output_corner); + interval_maximum = std::max( + interval_maximum, + signedPointProtrusion( + normalized_allowed, + Vec2{input_point.x / frame_width, + input_point.y / frame_height})); + } + if (interval_maximum > result.maximum) { + result.maximum = interval_maximum; + result.worst_interval = interval; + result.has_worst_interval = true; + } + } + + if (result.has_worst_interval && result.maximum > 0.0) { + result.worst_interval_mask[result.worst_interval] = true; + } + return result; +} + +double computeFullGridCropCorrectionFraction( + const Quaternion &requested_pose, const Quaternion &fallback_pose, + const std::vector &inv_real_projections, + const VirtualProjectionBuilder &build_virtual_projections, + const ProtrusionRect &input_interval, + const ProtrusionRect &output_interval, + const ProtrusionRect &allowed, double frame_width, double frame_height, + double maximum_allowed_protrusion) { + constexpr double kBinaryTolerance = 0.01; + if (inv_real_projections.size() < 2) { + return 1.0; + } + if (!build_virtual_projections) { + throw std::invalid_argument("Virtual projection builder is empty"); + } + + const std::vector all_intervals(inv_real_projections.size() - 1, + true); + const ProjectionProtrusionResult requested = evaluateProjectionProtrusion( + inv_real_projections, build_virtual_projections(requested_pose), + input_interval, output_interval, allowed, all_intervals, frame_width, + frame_height); + if (requested.maximum <= 0.0) { + return 0.0; + } + + const ProjectionProtrusionResult fallback = evaluateProjectionProtrusion( + inv_real_projections, build_virtual_projections(fallback_pose), + input_interval, output_interval, allowed, all_intervals, frame_width, + frame_height); + if (fallback.maximum > 0.0) { + return 1.0; + } + + double low = 0.0; + double high = 1.0; + do { + const double midpoint = (low + high) * 0.5; + const Quaternion candidate = interpolatePose( + requested_pose, fallback_pose, midpoint, requested_pose); + const ProjectionProtrusionResult score = evaluateProjectionProtrusion( + inv_real_projections, build_virtual_projections(candidate), + input_interval, output_interval, allowed, + requested.worst_interval_mask, frame_width, frame_height); + if (score.maximum > maximum_allowed_protrusion) { + low = midpoint; + } else { + high = midpoint; + } + } while (high - low > kBinaryTolerance); + + return std::min(high, 1.0); +} + +} // namespace mgc_eis_reconstruction::type18 diff --git a/research/mgc_eis_reconstruction/mgc_type18_projection.hpp b/research/mgc_eis_reconstruction/mgc_type18_projection.hpp new file mode 100644 index 00000000..334b3083 --- /dev/null +++ b/research/mgc_eis_reconstruction/mgc_type18_projection.hpp @@ -0,0 +1,113 @@ +#pragma once + +#include "mgc_eis_reconstruction.hpp" +#include "mgc_type18_lookahead.hpp" + +#include +#include +#include +#include +#include + +namespace mgc_eis_reconstruction::type18 { + +// Exact per-row offsets from 0x22CE380 when per-scanline projection is +// enabled. The samples cover both rolling-shutter endpoints: i*skew/(N-1). +std::vector +makeRollingShutterRowOffsets(std::int64_t rolling_shutter_ns, int row_count); + +// The non-per-scanline branch builds two projections at explicit source row +// coordinates. MGC converts the float numerator to int64 before signed +// division by the integer-valued frame height. +std::array makeBoundingRowOffsets( + std::int64_t rolling_shutter_ns, + const std::array &source_rows, double frame_height); + +// Exact decision at 0x33BF394. A request just beyond the newest gyro sample +// is clamped back only when its positive gap is smaller than tolerance_ns. +std::int64_t adjustGyroQueryTimestamp(std::int64_t requested_ns, + std::int64_t newest_gyro_ns, + std::int64_t tolerance_ns); + +Mat3 makeCameraProjection(const Mat3 &intrinsics, + const Quaternion &orientation); + +// Reconstructs the projection-matrix part of 0x22CE380 after timestamped gyro +// and optional OIS-adjusted intrinsics have been resolved. intrinsics accepts +// either one shared matrix or one matrix per row. +std::vector buildRealCameraProjectionRows( + const std::vector &actual_orientations, + const std::vector &intrinsics); + +// Reconstructs 0x229B84C/0x22CF06C. Each row pose is composed in the binary's +// order: row_relative * base_virtual, then P_virtual = K * R. +std::vector buildVirtualCameraProjectionRows( + const Quaternion &base_virtual_orientation, + const std::vector &row_relative_orientations, + const std::vector &intrinsics); + +// Matrix core of 0x229D234. 0x5886128 first post-multiplies the injected +// projection, then 0x5885F18 pre-multiplies inverse(P_real): +// H = (P_virtual * injected_projection) * inverse(P_real). +std::vector composeDenseWarpRows( + const std::vector &real_projections, + const std::vector &virtual_projections, + bool virtual_projection_per_row, + const Mat3 &injected_projection = Mat3::identity()); + +// Exact matrix-space adapter at V25 0x5667084. The native EIS core works in +// top-left-origin pixel coordinates while Java's qhi/iha mesh consumes clip +// coordinates. H_clip = C_pixel_to_clip * H_pixel * P_clip_to_pixel. +Mat3 convertPixelHomographyToClip(const Mat3 &pixel_homography, + double frame_width, + double frame_height); + +// V25 0x5666FA0, consumed at 0x22DD5AC after the pixel-to-clip adapter. +// MGC represents zoom projectively: dividing the homogeneous denominator row +// makes x/w and y/w expand about clip-space origin without changing the +// source texture coordinates. +Mat3 applyCropZoomToClipHomography(const Mat3 &clip_homography, + double zoom_factor); + +// Result of 0x22CDB08. MGC initializes the maximum to -1 and only marks the +// single worst scanline interval when that maximum is positive. +struct ProjectionProtrusionResult { + double maximum = -1.0; + std::size_t worst_interval = 0; + bool has_worst_interval = false; + std::vector worst_interval_mask; +}; + +// Reconstructs the geometric core at 0x22CDB08 and its helpers 0x5887A8C, +// 0x588A500, and 0x588A840. inv_real_projections must contain at least two +// scanline-boundary matrices. virtual_projections accepts one shared matrix or +// one matrix per real boundary. input_interval/output_interval/allowed are in +// pixel coordinates and are normalized by frame_width/frame_height only at +// the point where MGC performs the four protrusion tests. +ProjectionProtrusionResult evaluateProjectionProtrusion( + const std::vector &inv_real_projections, + const std::vector &virtual_projections, + const ProtrusionRect &input_interval, + const ProtrusionRect &output_interval, + const ProtrusionRect &allowed, + const std::vector &input_protrusion_mask, double frame_width, + double frame_height); + +using VirtualProjectionBuilder = + std::function(const Quaternion &)>; + +// Exact scalar returned by 0x22CEB9C. Zero means the requested virtual pose +// already fits. Otherwise MGC tests the fallback pose, then binary-searches +// the slerp fraction using only the initially worst scanline interval. A +// required correction above 0.99, an invalid fallback, or insufficient +// projection rows returns the binary's 1.1 sentinel. +double computeFullGridCropCorrectionFraction( + const Quaternion &requested_pose, const Quaternion &fallback_pose, + const std::vector &inv_real_projections, + const VirtualProjectionBuilder &build_virtual_projections, + const ProtrusionRect &input_interval, + const ProtrusionRect &output_interval, + const ProtrusionRect &allowed, double frame_width, double frame_height, + double maximum_allowed_protrusion); + +} // namespace mgc_eis_reconstruction::type18