feat: EIS+ (2)
This commit is contained in:
1 parent
ef7bb72add
commit
188b753222
40 files changed
+6999
-1610
No files matched your search
@@ -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(
|
||||
|
||||
@@ -0,0 +1,393 @@
|
||||
#include <jni.h>
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <exception>
|
||||
#include <memory>
|
||||
|
||||
#include <android/hardware_buffer_jni.h>
|
||||
#include <android/log.h>
|
||||
#include <EGL/egl.h>
|
||||
#include <EGL/eglext.h>
|
||||
#include <GLES2/gl2.h>
|
||||
#include <GLES2/gl2ext.h>
|
||||
|
||||
#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<Handle *>(static_cast<uintptr_t>(value));
|
||||
}
|
||||
|
||||
jlong toJlong(Handle *value) {
|
||||
return static_cast<jlong>(reinterpret_cast<uintptr_t>(value));
|
||||
}
|
||||
|
||||
void logFailure(const char *operation, const std::exception &error) {
|
||||
__android_log_print(ANDROID_LOG_ERROR, kLogTag, "%s failed: %s", operation,
|
||||
error.what());
|
||||
}
|
||||
|
||||
template <typename Procedure>
|
||||
Procedure eglProcedure(const char *name) {
|
||||
return reinterpret_cast<Procedure>(eglGetProcAddress(name));
|
||||
}
|
||||
|
||||
HardwareBufferEglImage *fromHardwareBufferImageJlong(jlong value) {
|
||||
return reinterpret_cast<HardwareBufferEglImage *>(
|
||||
static_cast<uintptr_t>(value));
|
||||
}
|
||||
|
||||
jlong toHardwareBufferImageJlong(HardwareBufferEglImage *value) {
|
||||
return static_cast<jlong>(reinterpret_cast<uintptr_t>(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<int>(lookahead_frames), 3, 10);
|
||||
config.stabilization_strength =
|
||||
std::clamp(static_cast<double>(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<long long>(result->timestamp_ns),
|
||||
static_cast<unsigned long long>(state->submitted_frames),
|
||||
static_cast<unsigned long long>(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<long long>(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<long long>(result->timestamp_ns),
|
||||
static_cast<unsigned long long>(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<long long>(result->timestamp_ns),
|
||||
static_cast<unsigned long long>(state->submitted_frames),
|
||||
static_cast<unsigned long long>(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<jfloat>(matrix[value]);
|
||||
}
|
||||
}
|
||||
env->ReleaseFloatArrayElements(row_homographies, matrices, 0);
|
||||
|
||||
if (output_state && env->GetArrayLength(output_state) >= 2) {
|
||||
const jfloat values[2] = {
|
||||
static_cast<jfloat>(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<PFNEGLGETNATIVECLIENTBUFFERANDROIDPROC>(
|
||||
"eglGetNativeClientBufferANDROID");
|
||||
const auto create_image =
|
||||
eglProcedure<PFNEGLCREATEIMAGEKHRPROC>("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<PFNGLEGLIMAGETARGETTEXTURE2DOESPROC>(
|
||||
"glEGLImageTargetTexture2DOES");
|
||||
if (!bind_image) {
|
||||
__android_log_print(ANDROID_LOG_WARN, kLogTag,
|
||||
"MGC glEGLImageTargetTexture2DOES unavailable");
|
||||
return JNI_FALSE;
|
||||
}
|
||||
glBindTexture(GL_TEXTURE_EXTERNAL_OES, static_cast<GLuint>(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<HardwareBufferEglImage> source(
|
||||
fromHardwareBufferImageJlong(image_handle));
|
||||
if (!source) {
|
||||
return;
|
||||
}
|
||||
const auto destroy_image =
|
||||
eglProcedure<PFNEGLDESTROYIMAGEKHRPROC>("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);
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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"),
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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()
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
@@ -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()
|
||||
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
|
||||
@@ -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
|
||||
}
|
||||
@@ -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<String>(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<String>(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)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
+688
-588
File diff suppressed because it is too large.
Load diff
@@ -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()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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 准备好且尺寸已就绪时,通知外部打开相机。
|
||||
|
||||
@@ -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()
|
||||
)
|
||||
}
|
||||
|
||||
@@ -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),
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
@@ -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<VideoColorEffectLayer> = 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
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -193,11 +193,17 @@
|
||||
<string name="settings_video_lock_lens">鎖定鏡頭</string>
|
||||
<string name="settings_video_lock_lens_description">影片錄製過程中變焦不切換鏡頭。</string>
|
||||
<string name="settings_video_stabilization_default">預設影片防震模式</string>
|
||||
<string name="settings_video_stabilization_default_description">選擇進入影片模式時使用的防震方式。EIS+ 在後置相機使用陀螺儀與滾動快門校正,並會將錄影規格切換為 1080p/30 fps。</string>
|
||||
<string name="settings_video_stabilization_default_description">選擇進入影片模式時使用的防震方式。EIS+ 在後置相機使用陀螺儀與滾動快門校正。</string>
|
||||
<string name="settings_video_stabilization_mode_off">關閉</string>
|
||||
<string name="settings_video_stabilization_mode_eis">電子防震 (EIS)</string>
|
||||
<string name="settings_video_stabilization_mode_ois">光學防震 (OIS)</string>
|
||||
<string name="settings_video_stabilization_mode_enhanced">增強防震 (EIS+)</string>
|
||||
<string name="settings_video_stabilization_strength">EIS+ 防震強度</string>
|
||||
<string name="settings_video_stabilization_strength_description">數值越高,套用的姿態修正越完整;數值越低,畫面越貼近手機移動。下次開始錄影時生效。</string>
|
||||
<string name="settings_video_stabilization_strength_value">%1$d%%</string>
|
||||
<string name="settings_video_stabilization_lookahead">EIS+ 前瞻影格數</string>
|
||||
<string name="settings_video_stabilization_lookahead_description">影格數越少,畫面延遲越低、跟手性越強;影格數越多,畫面防震越平滑穩定。預設為 7 幀。</string>
|
||||
<string name="settings_video_stabilization_lookahead_value">%1$d 幀</string>
|
||||
<string name="settings_video_lock_white_balance">鎖定白平衡</string>
|
||||
<string name="settings_video_lock_white_balance_description">影片錄製過程中鎖定白平衡。</string>
|
||||
<string name="settings_section_quality_perf">畫質與性能</string>
|
||||
|
||||
@@ -193,11 +193,17 @@
|
||||
<string name="settings_video_lock_lens">锁定镜头</string>
|
||||
<string name="settings_video_lock_lens_description">视频录制过程中变焦不切换镜头。</string>
|
||||
<string name="settings_video_stabilization_default">默认视频防抖模式</string>
|
||||
<string name="settings_video_stabilization_default_description">选择进入视频模式时使用的防抖方式。EIS+ 在后摄使用陀螺仪和滚动快门校正,并会将录像规格切换为 1080p/30 fps。</string>
|
||||
<string name="settings_video_stabilization_default_description">选择进入视频模式时使用的防抖方式。EIS+ 在后摄使用陀螺仪和滚动快门校正。</string>
|
||||
<string name="settings_video_stabilization_mode_off">关闭</string>
|
||||
<string name="settings_video_stabilization_mode_eis">电子防抖 (EIS)</string>
|
||||
<string name="settings_video_stabilization_mode_ois">光学防抖 (OIS)</string>
|
||||
<string name="settings_video_stabilization_mode_enhanced">增强防抖 (EIS+)</string>
|
||||
<string name="settings_video_stabilization_strength">EIS+ 防抖强度</string>
|
||||
<string name="settings_video_stabilization_strength_description">数值越高,应用的姿态修正越完整;数值越低,画面越贴近手机移动。下次开始录像时生效。</string>
|
||||
<string name="settings_video_stabilization_strength_value">%1$d%%</string>
|
||||
<string name="settings_video_stabilization_lookahead">EIS+ 前瞻帧数</string>
|
||||
<string name="settings_video_stabilization_lookahead_description">帧数越少,画面延时越低、跟手性越强;帧数越多,画面防抖越平滑稳定。默认为 7 帧。</string>
|
||||
<string name="settings_video_stabilization_lookahead_value">%1$d 帧</string>
|
||||
<string name="settings_video_lock_white_balance">锁定白平衡</string>
|
||||
<string name="settings_video_lock_white_balance_description">视频录制过程中锁定白平衡。</string>
|
||||
<string name="settings_section_quality_perf">画质与性能</string>
|
||||
|
||||
@@ -193,11 +193,17 @@
|
||||
<string name="settings_video_lock_lens">鎖定鏡頭</string>
|
||||
<string name="settings_video_lock_lens_description">影片錄製過程中變焦不切換鏡頭。</string>
|
||||
<string name="settings_video_stabilization_default">預設影片防震模式</string>
|
||||
<string name="settings_video_stabilization_default_description">選擇進入影片模式時使用的防震方式。EIS+ 在後置相機使用陀螺儀與滾動快門校正,並會將錄影規格切換為 1080p/30 fps。</string>
|
||||
<string name="settings_video_stabilization_default_description">選擇進入影片模式時使用的防震方式。EIS+ 在後置相機使用陀螺儀與滾動快門校正。</string>
|
||||
<string name="settings_video_stabilization_mode_off">關閉</string>
|
||||
<string name="settings_video_stabilization_mode_eis">電子防震 (EIS)</string>
|
||||
<string name="settings_video_stabilization_mode_ois">光學防震 (OIS)</string>
|
||||
<string name="settings_video_stabilization_mode_enhanced">增強防震 (EIS+)</string>
|
||||
<string name="settings_video_stabilization_strength">EIS+ 防震強度</string>
|
||||
<string name="settings_video_stabilization_strength_description">數值越高,套用的姿態修正越完整;數值越低,畫面越貼近手機移動。下次開始錄影時生效。</string>
|
||||
<string name="settings_video_stabilization_strength_value">%1$d%%</string>
|
||||
<string name="settings_video_stabilization_lookahead">EIS+ 前瞻影格數</string>
|
||||
<string name="settings_video_stabilization_lookahead_description">影格數越少,畫面延遲越低、跟手性越強;影格數越多,畫面防震越平滑穩定。預設為 7 幀。</string>
|
||||
<string name="settings_video_stabilization_lookahead_value">%1$d 幀</string>
|
||||
<string name="settings_video_lock_white_balance">鎖定白平衡</string>
|
||||
<string name="settings_video_lock_white_balance_description">影片錄製過程中鎖定白平衡。</string>
|
||||
<string name="settings_section_quality_perf">畫質與性能</string>
|
||||
|
||||
@@ -193,11 +193,17 @@
|
||||
<string name="settings_video_lock_lens">鎖定鏡頭</string>
|
||||
<string name="settings_video_lock_lens_description">影片錄製過程中變焦不切換鏡頭。</string>
|
||||
<string name="settings_video_stabilization_default">預設影片防震模式</string>
|
||||
<string name="settings_video_stabilization_default_description">選擇進入影片模式時使用的防震方式。EIS+ 在後置相機使用陀螺儀與滾動快門校正,並會將錄影規格切換為 1080p/30 fps。</string>
|
||||
<string name="settings_video_stabilization_default_description">選擇進入影片模式時使用的防震方式。EIS+ 在後置相機使用陀螺儀與滾動快門校正。</string>
|
||||
<string name="settings_video_stabilization_mode_off">關閉</string>
|
||||
<string name="settings_video_stabilization_mode_eis">電子防震 (EIS)</string>
|
||||
<string name="settings_video_stabilization_mode_ois">光學防震 (OIS)</string>
|
||||
<string name="settings_video_stabilization_mode_enhanced">增強防震 (EIS+)</string>
|
||||
<string name="settings_video_stabilization_strength">EIS+ 防震強度</string>
|
||||
<string name="settings_video_stabilization_strength_description">數值越高,套用的姿態修正越完整;數值越低,畫面越貼近手機移動。下次開始錄影時生效。</string>
|
||||
<string name="settings_video_stabilization_strength_value">%1$d%%</string>
|
||||
<string name="settings_video_stabilization_lookahead">EIS+ 前瞻影格數</string>
|
||||
<string name="settings_video_stabilization_lookahead_description">影格數越少,畫面延遲越低、跟手性越強;影格數越多,畫面防震越平滑穩定。預設為 7 幀。</string>
|
||||
<string name="settings_video_stabilization_lookahead_value">%1$d 幀</string>
|
||||
<string name="settings_video_lock_white_balance">鎖定白平衡</string>
|
||||
<string name="settings_video_lock_white_balance_description">影片錄製過程中鎖定白平衡。</string>
|
||||
<string name="settings_section_quality_perf">畫質與性能</string>
|
||||
|
||||
@@ -197,11 +197,17 @@
|
||||
<string name="settings_video_lock_lens">Lock Lens</string>
|
||||
<string name="settings_video_lock_lens_description">Prevent zooming from switching cameras while video is recording.</string>
|
||||
<string name="settings_video_stabilization_default">Default Video Stabilization</string>
|
||||
<string name="settings_video_stabilization_default_description">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.</string>
|
||||
<string name="settings_video_stabilization_default_description">Choose the stabilization mode used when video mode starts. EIS+ uses gyro-driven rolling-shutter correction on rear cameras.</string>
|
||||
<string name="settings_video_stabilization_mode_off">Off</string>
|
||||
<string name="settings_video_stabilization_mode_eis">Electronic (EIS)</string>
|
||||
<string name="settings_video_stabilization_mode_ois">Optical (OIS)</string>
|
||||
<string name="settings_video_stabilization_mode_enhanced">Enhanced (EIS+)</string>
|
||||
<string name="settings_video_stabilization_strength">EIS+ Strength</string>
|
||||
<string name="settings_video_stabilization_strength_description">Higher values apply more of the recovered pose correction; lower values follow camera movement more closely. Changes take effect when the next recording starts.</string>
|
||||
<string name="settings_video_stabilization_strength_value">%1$d%%</string>
|
||||
<string name="settings_video_stabilization_lookahead">EIS+ Lookahead Frames</string>
|
||||
<string name="settings_video_stabilization_lookahead_description">Lower frames reduce latency for better responsiveness; higher frames provide smoother stabilization. Default is 7 frames.</string>
|
||||
<string name="settings_video_stabilization_lookahead_value">%1$d frames</string>
|
||||
<string name="settings_video_lock_white_balance">Lock White Balance</string>
|
||||
<string name="settings_video_lock_white_balance_description">Keep automatic white balance fixed while video is recording.</string>
|
||||
<string name="settings_section_quality_perf">Quality & Performance</string>
|
||||
|
||||
@@ -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<Double, Double, Double>,
|
||||
actual: Triple<Double, Double, Double>,
|
||||
) {
|
||||
assertEquals(expected.first, actual.first, 1.0e-9)
|
||||
assertEquals(expected.second, actual.second, 1.0e-9)
|
||||
assertEquals(expected.third, actual.third, 1.0e-9)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user