diff --git a/apps/backend/crydaq-algorithm-runtime/src/main/java/com/opentest/core/jni/AlgorithmLibJNIBridge.java b/apps/backend/crydaq-algorithm-runtime/src/main/java/com/opentest/core/jni/AlgorithmLibJNIBridge.java index 6764e565..57720b4e 100644 --- a/apps/backend/crydaq-algorithm-runtime/src/main/java/com/opentest/core/jni/AlgorithmLibJNIBridge.java +++ b/apps/backend/crydaq-algorithm-runtime/src/main/java/com/opentest/core/jni/AlgorithmLibJNIBridge.java @@ -252,7 +252,19 @@ public native int calculateFftDataInto( * @param lifterKeepInside lifter 区间策略:1 保留区间内,0 保留区间外。 * @return JNI 状态码,0 表示成功,非 0 表示失败 */ - public native int createBkFftTask(String taskId, double sampleRateHz, + // Keep Java callers source-compatible while binding the neutral names exported by native SDK 2.4.1. + public int createBkFftTask(String taskId, double sampleRateHz, + int analysisMode, double spanHz, int lines, double centerFrequencyHz, int windowType, + double windowParam, double windowStartFraction, double windowEndFraction, + double overlapPercent, int averageMode, int averageCount, double averageTimeSeconds, + double exponentialAlpha, int scaling, int averageFixedMode, int averagingDomain, + int overloadExclude, int enableTimeResults, int enableLifteredSpectrum, + double lifterQuefrencyStartSeconds, double lifterQuefrencyStopSeconds, + int lifterKeepInside) { + return createAdvancedFftTask(taskId, sampleRateHz, analysisMode, spanHz, lines, centerFrequencyHz, windowType, windowParam, windowStartFraction, windowEndFraction, overlapPercent, averageMode, averageCount, averageTimeSeconds, exponentialAlpha, scaling, averageFixedMode, averagingDomain, overloadExclude, enableTimeResults, enableLifteredSpectrum, lifterQuefrencyStartSeconds, lifterQuefrencyStopSeconds, lifterKeepInside); + } + + private native int createAdvancedFftTask(String taskId, double sampleRateHz, int analysisMode, double spanHz, int lines, double centerFrequencyHz, int windowType, double windowParam, double windowStartFraction, double windowEndFraction, double overlapPercent, int averageMode, int averageCount, double averageTimeSeconds, @@ -261,7 +273,16 @@ public native int createBkFftTask(String taskId, double sampleRateHz, double lifterQuefrencyStartSeconds, double lifterQuefrencyStopSeconds, int lifterKeepInside); - public native int createBkFftSpectrogramTask(String taskId, double sampleRateHz, + public int createBkFftSpectrogramTask(String taskId, double sampleRateHz, + int analysisMode, double spanHz, int lines, double centerFrequencyHz, int windowType, + double windowParam, double windowStartFraction, double windowEndFraction, + double overlapPercent, int averageMode, int averageCount, double averageTimeSeconds, + double exponentialAlpha, int scaling, int averageFixedMode, int averagingDomain, + int overloadExclude) { + return createAdvancedFftSpectrogramTask(taskId, sampleRateHz, analysisMode, spanHz, lines, centerFrequencyHz, windowType, windowParam, windowStartFraction, windowEndFraction, overlapPercent, averageMode, averageCount, averageTimeSeconds, exponentialAlpha, scaling, averageFixedMode, averagingDomain, overloadExclude); + } + + private native int createAdvancedFftSpectrogramTask(String taskId, double sampleRateHz, int analysisMode, double spanHz, int lines, double centerFrequencyHz, int windowType, double windowParam, double windowStartFraction, double windowEndFraction, double overlapPercent, int averageMode, int averageCount, double averageTimeSeconds, @@ -277,7 +298,11 @@ public native int createBkFftSpectrogramTask(String taskId, double sampleRateHz, * @param sampleCount {@code sampleCount} 参数。 * @return JNI 状态码,0 表示成功,非 0 表示失败 */ - public native int pushBkFftTask(String taskId, double[] samples, int sampleCount); + public int pushBkFftTask(String taskId, double[] samples, int sampleCount) { + return pushAdvancedFftTask(taskId, samples, sampleCount); + } + + private native int pushAdvancedFftTask(String taskId, double[] samples, int sampleCount); /** * 一次读取 BK FFT 当前帧的全部结果集。 @@ -308,7 +333,12 @@ public native int createBkFftSpectrogramTask(String taskId, double sampleRateHz, * @param messageCollector Java 侧可写 Map,不允许为 null;按结果分组 Key 保存每项 Native message。 * @return JNI 发布状态码;0 表示 Key/Value 已成功写入 collector。算法状态请读取 {@code retCode}。 */ - public native int readBkFftTask(String taskId, int weighting, + public int readBkFftTask(String taskId, int weighting, + JniNamedDoubleResultCollector collector, Map messageCollector) { + return readAdvancedFftTask(taskId, weighting, collector, messageCollector); + } + + private native int readAdvancedFftTask(String taskId, int weighting, JniNamedDoubleResultCollector collector, Map messageCollector); /** @@ -328,7 +358,13 @@ public native int readBkFftTask(String taskId, int weighting, * @param messageOutput Native 消息输出,长度至少为 1。 * @return JNI 状态码,0 表示成功。 */ - public native int readBkFftSelectedResult(String taskId, int function, int coordinate, + public int readBkFftSelectedResult(String taskId, int function, int coordinate, + int spectralUnit, int weighting, JniNamedDoubleResultCollector collector, + String[] messageOutput) { + return readAdvancedFftSelectedResult(taskId, function, coordinate, spectralUnit, weighting, collector, messageOutput); + } + + private native int readAdvancedFftSelectedResult(String taskId, int function, int coordinate, int spectralUnit, int weighting, JniNamedDoubleResultCollector collector, String[] messageOutput); @@ -339,7 +375,11 @@ public native int readBkFftSelectedResult(String taskId, int function, int coord * @param taskId 任务标识。 * @return JNI 状态码,0 表示成功,非 0 表示失败 */ - public native int resetBkFftTask(String taskId); + public int resetBkFftTask(String taskId) { + return resetAdvancedFftTask(taskId); + } + + private native int resetAdvancedFftTask(String taskId); /** * JNI 接口:{@code disposeBkFftTask}。 @@ -348,7 +388,11 @@ public native int readBkFftSelectedResult(String taskId, int function, int coord * @param taskId 任务标识。 * @return JNI 状态码,0 表示成功,非 0 表示失败 */ - public native int disposeBkFftTask(String taskId); + public int disposeBkFftTask(String taskId) { + return disposeAdvancedFftTask(taskId); + } + + private native int disposeAdvancedFftTask(String taskId); /** * JNI 接口:{@code createBkFrfTask}。 @@ -382,7 +426,18 @@ public native int readBkFftSelectedResult(String taskId, int function, int coord * @param lifterKeepInside lifter 区间策略:1 保留区间内,0 保留区间外。 * @return JNI 状态码,0 表示成功,非 0 表示失败 */ - public native int createBkFrfTask(String taskId, double sampleRateHz, + public int createBkFrfTask(String taskId, double sampleRateHz, + int analysisMode, double spanHz, int lines, double centerFrequencyHz, int windowType, + double windowParam, double windowStartFraction, double windowEndFraction, + double overlapPercent, int averageMode, int averageCount, double averageTimeSeconds, + double exponentialAlpha, int scaling, int averageFixedMode, int averagingDomain, + int overloadExclude, int estimator, int unwrapPhase, int enableTimeResults, + int enableLifteredSpectrum, double lifterQuefrencyStartSeconds, + double lifterQuefrencyStopSeconds, int lifterKeepInside) { + return createAdvancedFrequencyResponseTask(taskId, sampleRateHz, analysisMode, spanHz, lines, centerFrequencyHz, windowType, windowParam, windowStartFraction, windowEndFraction, overlapPercent, averageMode, averageCount, averageTimeSeconds, exponentialAlpha, scaling, averageFixedMode, averagingDomain, overloadExclude, estimator, unwrapPhase, enableTimeResults, enableLifteredSpectrum, lifterQuefrencyStartSeconds, lifterQuefrencyStopSeconds, lifterKeepInside); + } + + private native int createAdvancedFrequencyResponseTask(String taskId, double sampleRateHz, int analysisMode, double spanHz, int lines, double centerFrequencyHz, int windowType, double windowParam, double windowStartFraction, double windowEndFraction, double overlapPercent, int averageMode, int averageCount, double averageTimeSeconds, @@ -401,7 +456,11 @@ public native int createBkFrfTask(String taskId, double sampleRateHz, * @param sampleCount {@code sampleCount} 参数。 * @return JNI 状态码,0 表示成功,非 0 表示失败 */ - public native int pushBkFrfTask(String taskId, double[] referenceSamples, double[] responseSamples, int sampleCount); + public int pushBkFrfTask(String taskId, double[] referenceSamples, double[] responseSamples, int sampleCount) { + return pushAdvancedFrequencyResponseTask(taskId, referenceSamples, responseSamples, sampleCount); + } + + private native int pushAdvancedFrequencyResponseTask(String taskId, double[] referenceSamples, double[] responseSamples, int sampleCount); /** * 一次读取 BK FRF 当前帧的全部结果集。 @@ -429,7 +488,12 @@ public native int createBkFrfTask(String taskId, double sampleRateHz, * @param messageCollector Java 侧可写 Map,不允许为 null;按结果分组 Key 保存每项 Native message。 * @return JNI 发布状态码;0 表示结果已写入 collector,算法状态读取 {@code retCode}。 */ - public native int readBkFrfTask(String taskId, int weighting, + public int readBkFrfTask(String taskId, int weighting, + JniNamedDoubleResultCollector collector, Map messageCollector) { + return readAdvancedFrequencyResponseTask(taskId, weighting, collector, messageCollector); + } + + private native int readAdvancedFrequencyResponseTask(String taskId, int weighting, JniNamedDoubleResultCollector collector, Map messageCollector); /** @@ -447,7 +511,13 @@ public native int readBkFrfTask(String taskId, int weighting, * @param messageOutput Native 消息输出,长度至少为 1。 * @return JNI 状态码,0 表示成功。 */ - public native int readBkFrfSelectedResult(String taskId, int function, int coordinate, + public int readBkFrfSelectedResult(String taskId, int function, int coordinate, + int spectralUnit, int weighting, JniNamedDoubleResultCollector collector, + String[] messageOutput) { + return readAdvancedFrequencyResponseSelectedResult(taskId, function, coordinate, spectralUnit, weighting, collector, messageOutput); + } + + private native int readAdvancedFrequencyResponseSelectedResult(String taskId, int function, int coordinate, int spectralUnit, int weighting, JniNamedDoubleResultCollector collector, String[] messageOutput); @@ -458,7 +528,11 @@ public native int readBkFrfSelectedResult(String taskId, int function, int coord * @param taskId 任务标识。 * @return JNI 状态码,0 表示成功,非 0 表示失败 */ - public native int resetBkFrfTask(String taskId); + public int resetBkFrfTask(String taskId) { + return resetAdvancedFrequencyResponseTask(taskId); + } + + private native int resetAdvancedFrequencyResponseTask(String taskId); /** * JNI 接口:{@code disposeBkFrfTask}。 @@ -467,7 +541,11 @@ public native int readBkFrfSelectedResult(String taskId, int function, int coord * @param taskId 任务标识。 * @return JNI 状态码,0 表示成功,非 0 表示失败 */ - public native int disposeBkFrfTask(String taskId); + public int disposeBkFrfTask(String taskId) { + return disposeAdvancedFrequencyResponseTask(taskId); + } + + private native int disposeAdvancedFrequencyResponseTask(String taskId); /** * JNI 接口:{@code createBkCpbTask}。 @@ -493,7 +571,17 @@ public native int readBkFrfSelectedResult(String taskId, int function, int coord * @param cursorUpperFrequencyHz {@code cursorUpperFrequencyHz} 参数。 * @return JNI 状态码,0 表示成功,非 0 表示失败 */ - public native int createBkCpbTask(String taskId, double sampleRateHz, + public int createBkCpbTask(String taskId, double sampleRateHz, + int bandwidth, double lowerCenterFrequencyHz, double upperCenterFrequencyHz, + double referenceValue, int frameLen, double frameDurationSeconds, + int filterCascadeCount, int averageMode, int averageCount, + double linearAveragingTimeSeconds, double exponentialAveragingTimeSeconds, + double tauSeconds, int acousticWeighting, int overallBands, + double cursorLowerFrequencyHz, double cursorUpperFrequencyHz) { + return createPrecisionOctaveTask(taskId, sampleRateHz, bandwidth, lowerCenterFrequencyHz, upperCenterFrequencyHz, referenceValue, frameLen, frameDurationSeconds, filterCascadeCount, averageMode, averageCount, linearAveragingTimeSeconds, exponentialAveragingTimeSeconds, tauSeconds, acousticWeighting, overallBands, cursorLowerFrequencyHz, cursorUpperFrequencyHz); + } + + private native int createPrecisionOctaveTask(String taskId, double sampleRateHz, int bandwidth, double lowerCenterFrequencyHz, double upperCenterFrequencyHz, double referenceValue, int frameLen, double frameDurationSeconds, int filterCascadeCount, int averageMode, int averageCount, @@ -510,11 +598,27 @@ public native int createBkCpbTask(String taskId, double sampleRateHz, * @param sampleCount {@code sampleCount} 参数。 * @return JNI 状态码,0 表示成功,非 0 表示失败 */ - public native long createBkCpbSharedGroup(String[] responseTaskIds); - public native int processBkCpbSharedGroup(long handle, double[][] alignedInputs); - public native void disposeBkCpbSharedGroup(long handle); + public long createBkCpbSharedGroup(String[] responseTaskIds) { + return createPrecisionOctaveSharedGroup(responseTaskIds); + } + + private native long createPrecisionOctaveSharedGroup(String[] responseTaskIds); + public int processBkCpbSharedGroup(long handle, double[][] alignedInputs) { + return processPrecisionOctaveSharedGroup(handle, alignedInputs); + } - public native int pushBkCpbTask(String taskId, double[] samples, int sampleCount); + private native int processPrecisionOctaveSharedGroup(long handle, double[][] alignedInputs); + public void disposeBkCpbSharedGroup(long handle) { + disposePrecisionOctaveSharedGroup(handle); + } + + private native void disposePrecisionOctaveSharedGroup(long handle); + + public int pushBkCpbTask(String taskId, double[] samples, int sampleCount) { + return pushPrecisionOctaveTask(taskId, samples, sampleCount); + } + + private native int pushPrecisionOctaveTask(String taskId, double[] samples, int sampleCount); /** * 创建单通道、五种分辨率共享输入的普通 BK CPB 任务。 @@ -527,7 +631,17 @@ public native int createBkCpbTask(String taskId, double sampleRateHz, * 一次释放任务。上述生命周期接口同时支持单分辨率和多分辨率任务。

* @return JNI 状态码,0 成功,非 0 失败;失败码不转换为成功。 */ - public native int createBkCpbMultiTask(String taskId, double sampleRateHz, + public int createBkCpbMultiTask(String taskId, double sampleRateHz, + double[] lowerCenterFrequencyHz, double[] upperCenterFrequencyHz, + double referenceValue, int frameLen, double frameDurationSeconds, + int filterCascadeCount, int averageMode, int averageCount, + double linearAveragingTimeSeconds, double exponentialAveragingTimeSeconds, + double tauSeconds, int acousticWeighting, int overallBands, + double cursorLowerFrequencyHz, double cursorUpperFrequencyHz) { + return createPrecisionOctaveMultiTask(taskId, sampleRateHz, lowerCenterFrequencyHz, upperCenterFrequencyHz, referenceValue, frameLen, frameDurationSeconds, filterCascadeCount, averageMode, averageCount, linearAveragingTimeSeconds, exponentialAveragingTimeSeconds, tauSeconds, acousticWeighting, overallBands, cursorLowerFrequencyHz, cursorUpperFrequencyHz); + } + + private native int createPrecisionOctaveMultiTask(String taskId, double sampleRateHz, double[] lowerCenterFrequencyHz, double[] upperCenterFrequencyHz, double referenceValue, int frameLen, double frameDurationSeconds, int filterCascadeCount, int averageMode, int averageCount, @@ -545,7 +659,12 @@ public native int createBkCpbMultiTask(String taskId, double sampleRateHz, * 分别保留批量操作状态和 BK 状态;单组或单项失败不应覆盖其他组结果。

* @return JNI 发布状态码;0 表示已发布,算法状态仍读取结果中的原始状态码。 */ - public native int readBkCpbMultiTask(String taskId, JniNamedDoubleResultCollector collector, + public int readBkCpbMultiTask(String taskId, JniNamedDoubleResultCollector collector, + Map messageCollector) { + return readPrecisionOctaveMultiTask(taskId, collector, messageCollector); + } + + private native int readPrecisionOctaveMultiTask(String taskId, JniNamedDoubleResultCollector collector, Map messageCollector); /** @@ -566,7 +685,12 @@ public native int readBkCpbMultiTask(String taskId, JniNamedDoubleResultCollecto * @param messageCollector Java 侧可写 Map,不允许为 null;按结果分组 Key 保存每项 Native message。 * @return JNI 发布状态码;0 表示结果已写入 collector,算法状态读取 {@code retCode}。 */ - public native int readBkCpbTask(String taskId, JniNamedDoubleResultCollector collector, + public int readBkCpbTask(String taskId, JniNamedDoubleResultCollector collector, + Map messageCollector) { + return readPrecisionOctaveTask(taskId, collector, messageCollector); + } + + private native int readPrecisionOctaveTask(String taskId, JniNamedDoubleResultCollector collector, Map messageCollector); /** @@ -583,7 +707,12 @@ public native int readBkCpbTask(String taskId, JniNamedDoubleResultCollector col * @param messageOutput Native 消息输出,长度至少为 1。 * @return JNI 状态码,0 表示成功。 */ - public native int readBkCpbSelectedResult(String taskId, int function, int coordinate, + public int readBkCpbSelectedResult(String taskId, int function, int coordinate, + int spectralUnit, JniNamedDoubleResultCollector collector, String[] messageOutput) { + return readPrecisionOctaveSelectedResult(taskId, function, coordinate, spectralUnit, collector, messageOutput); + } + + private native int readPrecisionOctaveSelectedResult(String taskId, int function, int coordinate, int spectralUnit, JniNamedDoubleResultCollector collector, String[] messageOutput); /** @@ -593,7 +722,11 @@ public native int readBkCpbSelectedResult(String taskId, int function, int coord * @param taskId 任务标识。 * @return JNI 状态码,0 表示成功,非 0 表示失败 */ - public native int resetBkCpbTask(String taskId); + public int resetBkCpbTask(String taskId) { + return resetPrecisionOctaveTask(taskId); + } + + private native int resetPrecisionOctaveTask(String taskId); /** * JNI 接口:{@code disposeBkCpbTask}。 @@ -602,9 +735,24 @@ public native int readBkCpbSelectedResult(String taskId, int function, int coord * @param taskId 任务标识。 * @return JNI 状态码,0 表示成功,非 0 表示失败 */ - public native int disposeBkCpbTask(String taskId); + public int disposeBkCpbTask(String taskId) { + return disposePrecisionOctaveTask(taskId); + } + + private native int disposePrecisionOctaveTask(String taskId); + + public int createBkCpbFrfTask(String taskId, double sampleRateHz, + int bandwidth, double lowerCenterFrequencyHz, double upperCenterFrequencyHz, + double referenceValue, int frameLen, double frameDurationSeconds, + int filterCascadeCount, int averageMode, int averageCount, + double linearAveragingTimeSeconds, double exponentialAveragingTimeSeconds, + double tauSeconds, int acousticWeighting, int overallBands, + double cursorLowerFrequencyHz, double cursorUpperFrequencyHz, + int estimator, int unwrapPhase) { + return createPrecisionOctaveFrequencyResponseTask(taskId, sampleRateHz, bandwidth, lowerCenterFrequencyHz, upperCenterFrequencyHz, referenceValue, frameLen, frameDurationSeconds, filterCascadeCount, averageMode, averageCount, linearAveragingTimeSeconds, exponentialAveragingTimeSeconds, tauSeconds, acousticWeighting, overallBands, cursorLowerFrequencyHz, cursorUpperFrequencyHz, estimator, unwrapPhase); + } - public native int createBkCpbFrfTask(String taskId, double sampleRateHz, + private native int createPrecisionOctaveFrequencyResponseTask(String taskId, double sampleRateHz, int bandwidth, double lowerCenterFrequencyHz, double upperCenterFrequencyHz, double referenceValue, int frameLen, double frameDurationSeconds, int filterCascadeCount, int averageMode, int averageCount, @@ -613,7 +761,12 @@ public native int createBkCpbFrfTask(String taskId, double sampleRateHz, double cursorLowerFrequencyHz, double cursorUpperFrequencyHz, int estimator, int unwrapPhase); - public native int pushBkCpbFrfTask(String taskId, double[] reference, + public int pushBkCpbFrfTask(String taskId, double[] reference, + double[] response, int sampleCount) { + return pushPrecisionOctaveFrequencyResponseTask(taskId, reference, response, sampleCount); + } + + private native int pushPrecisionOctaveFrequencyResponseTask(String taskId, double[] reference, double[] response, int sampleCount); /** @@ -635,7 +788,12 @@ public native int pushBkCpbFrfTask(String taskId, double[] reference, * @param messageCollector Java 侧可写 Map,不允许为 null;按结果分组 Key 保存每项 Native message。 * @return JNI 发布状态码;0 表示结果已写入 collector,算法状态读取 {@code retCode}。 */ - public native int readBkCpbFrfTask(String taskId, JniNamedDoubleResultCollector collector, + public int readBkCpbFrfTask(String taskId, JniNamedDoubleResultCollector collector, + Map messageCollector) { + return readPrecisionOctaveFrequencyResponseTask(taskId, collector, messageCollector); + } + + private native int readPrecisionOctaveFrequencyResponseTask(String taskId, JniNamedDoubleResultCollector collector, Map messageCollector); /** @@ -652,12 +810,25 @@ public native int readBkCpbFrfTask(String taskId, JniNamedDoubleResultCollector * @param messageOutput Native 消息输出,长度至少为 1。 * @return JNI 状态码,0 表示成功。 */ - public native int readBkCpbFrfSelectedResult(String taskId, int function, int coordinate, + public int readBkCpbFrfSelectedResult(String taskId, int function, int coordinate, + int spectralUnit, JniNamedDoubleResultCollector collector, String[] messageOutput) { + return readPrecisionOctaveFrequencyResponseSelectedResult(taskId, function, coordinate, spectralUnit, collector, messageOutput); + } + + private native int readPrecisionOctaveFrequencyResponseSelectedResult(String taskId, int function, int coordinate, int spectralUnit, JniNamedDoubleResultCollector collector, String[] messageOutput); - public native int resetBkCpbFrfTask(String taskId); + public int resetBkCpbFrfTask(String taskId) { + return resetPrecisionOctaveFrequencyResponseTask(taskId); + } - public native int disposeBkCpbFrfTask(String taskId); + private native int resetPrecisionOctaveFrequencyResponseTask(String taskId); + + public int disposeBkCpbFrfTask(String taskId) { + return disposePrecisionOctaveFrequencyResponseTask(taskId); + } + + private native int disposePrecisionOctaveFrequencyResponseTask(String taskId); /** * JNI 接口:{@code createBkTriggerTask}。 @@ -673,7 +844,20 @@ public native int readBkCpbFrfSelectedResult(String taskId, int function, int co * @param holdOffSamples {@code holdOffSamples} 参数。 * @return JNI 状态码,0 表示成功,非 0 表示失败 */ - public native int createBkTriggerTask( + public int createBkTriggerTask( + String taskId, + double referenceLevel, + double levelPercent, + double hysteresisPercent, + boolean positive, + int divider, + int delaySamples, + int holdOffSamples + ) { + return createSignalTriggerTask(taskId, referenceLevel, levelPercent, hysteresisPercent, positive, divider, delaySamples, holdOffSamples); + } + + private native int createSignalTriggerTask( String taskId, double referenceLevel, double levelPercent, @@ -693,7 +877,12 @@ public native int createBkTriggerTask( * @param forceTrigger {@code forceTrigger} 参数。 * @return 统一 JSON 响应字符串 */ - public native String searchBkTriggerTask(String taskId, double[] samples, + public String searchBkTriggerTask(String taskId, double[] samples, + boolean forceTrigger) { + return searchSignalTriggerTask(taskId, samples, forceTrigger); + } + + private native String searchSignalTriggerTask(String taskId, double[] samples, boolean forceTrigger); /** @@ -703,7 +892,11 @@ public native String searchBkTriggerTask(String taskId, double[] samples, * @param taskId 任务标识。 * @return JNI 状态码,0 表示成功,非 0 表示失败 */ - public native int resetBkTriggerTask(String taskId); + public int resetBkTriggerTask(String taskId) { + return resetSignalTriggerTask(taskId); + } + + private native int resetSignalTriggerTask(String taskId); /** * JNI 接口:{@code disposeBkTriggerTask}。 @@ -712,7 +905,11 @@ public native String searchBkTriggerTask(String taskId, double[] samples, * @param taskId 任务标识。 * @return JNI 状态码,0 表示成功,非 0 表示失败 */ - public native int disposeBkTriggerTask(String taskId); + public int disposeBkTriggerTask(String taskId) { + return disposeSignalTriggerTask(taskId); + } + + private native int disposeSignalTriggerTask(String taskId); /** diff --git a/apps/backend/crydaq-algorithm-runtime/src/test/java/com/opentest/algorithm/runtime/AlgorithmLibBridgeContractTest.java b/apps/backend/crydaq-algorithm-runtime/src/test/java/com/opentest/algorithm/runtime/AlgorithmLibBridgeContractTest.java index 0a96db6b..19ed688b 100644 --- a/apps/backend/crydaq-algorithm-runtime/src/test/java/com/opentest/algorithm/runtime/AlgorithmLibBridgeContractTest.java +++ b/apps/backend/crydaq-algorithm-runtime/src/test/java/com/opentest/algorithm/runtime/AlgorithmLibBridgeContractTest.java @@ -1,32 +1,69 @@ package com.opentest.algorithm.runtime; import com.opentest.core.jni.AlgorithmLibJNIBridge; -import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; import java.lang.reflect.Method; import java.lang.reflect.Modifier; +import java.util.Map; +import java.util.stream.Stream; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; class AlgorithmLibBridgeContractTest { - @Test - void bkTriggerMethodsExposeTheFinalRawJniContract() throws Exception { - assertNative("createBkTriggerTask", int.class, - String.class, double.class, double.class, double.class, boolean.class, - int.class, int.class, int.class); - assertNative("searchBkTriggerTask", String.class, - String.class, double[].class, boolean.class); - assertNative("resetBkTriggerTask", int.class, String.class); - assertNative("disposeBkTriggerTask", int.class, String.class); - } - - private void assertNative(String name, Class returnType, Class... parameterTypes) - throws Exception { + @ParameterizedTest(name = "{0} delegates to {1}") + @MethodSource("bindings") + void compatibilityMethodsMatchNeutralJniSignatures(String name, String nativeName, + Class returnType, Class[] parameterTypes) throws Exception { Method method = AlgorithmLibJNIBridge.class.getDeclaredMethod(name, parameterTypes); assertEquals(returnType, method.getReturnType()); assertTrue(Modifier.isPublic(method.getModifiers())); - assertTrue(Modifier.isNative(method.getModifiers())); + assertFalse(Modifier.isNative(method.getModifiers())); + Method nativeMethod = AlgorithmLibJNIBridge.class.getDeclaredMethod(nativeName, parameterTypes); + assertEquals(returnType, nativeMethod.getReturnType()); + assertTrue(Modifier.isPrivate(nativeMethod.getModifiers())); + assertTrue(Modifier.isNative(nativeMethod.getModifiers())); + } + + private static Stream bindings() { + return Stream.of( + Arguments.of("createBkFftTask", "createAdvancedFftTask", int.class, new Class[] {String.class, double.class, int.class, double.class, int.class, double.class, int.class, double.class, double.class, double.class, double.class, int.class, int.class, double.class, double.class, int.class, int.class, int.class, int.class, int.class, int.class, double.class, double.class, int.class}), + Arguments.of("createBkFftSpectrogramTask", "createAdvancedFftSpectrogramTask", int.class, new Class[] {String.class, double.class, int.class, double.class, int.class, double.class, int.class, double.class, double.class, double.class, double.class, int.class, int.class, double.class, double.class, int.class, int.class, int.class, int.class}), + Arguments.of("pushBkFftTask", "pushAdvancedFftTask", int.class, new Class[] {String.class, double[].class, int.class}), + Arguments.of("readBkFftTask", "readAdvancedFftTask", int.class, new Class[] {String.class, int.class, JniNamedDoubleResultCollector.class, Map.class}), + Arguments.of("readBkFftSelectedResult", "readAdvancedFftSelectedResult", int.class, new Class[] {String.class, int.class, int.class, int.class, int.class, JniNamedDoubleResultCollector.class, String[].class}), + Arguments.of("resetBkFftTask", "resetAdvancedFftTask", int.class, new Class[] {String.class}), + Arguments.of("disposeBkFftTask", "disposeAdvancedFftTask", int.class, new Class[] {String.class}), + Arguments.of("createBkFrfTask", "createAdvancedFrequencyResponseTask", int.class, new Class[] {String.class, double.class, int.class, double.class, int.class, double.class, int.class, double.class, double.class, double.class, double.class, int.class, int.class, double.class, double.class, int.class, int.class, int.class, int.class, int.class, int.class, int.class, int.class, double.class, double.class, int.class}), + Arguments.of("pushBkFrfTask", "pushAdvancedFrequencyResponseTask", int.class, new Class[] {String.class, double[].class, double[].class, int.class}), + Arguments.of("readBkFrfTask", "readAdvancedFrequencyResponseTask", int.class, new Class[] {String.class, int.class, JniNamedDoubleResultCollector.class, Map.class}), + Arguments.of("readBkFrfSelectedResult", "readAdvancedFrequencyResponseSelectedResult", int.class, new Class[] {String.class, int.class, int.class, int.class, int.class, JniNamedDoubleResultCollector.class, String[].class}), + Arguments.of("resetBkFrfTask", "resetAdvancedFrequencyResponseTask", int.class, new Class[] {String.class}), + Arguments.of("disposeBkFrfTask", "disposeAdvancedFrequencyResponseTask", int.class, new Class[] {String.class}), + Arguments.of("createBkCpbTask", "createPrecisionOctaveTask", int.class, new Class[] {String.class, double.class, int.class, double.class, double.class, double.class, int.class, double.class, int.class, int.class, int.class, double.class, double.class, double.class, int.class, int.class, double.class, double.class}), + Arguments.of("createBkCpbSharedGroup", "createPrecisionOctaveSharedGroup", long.class, new Class[] {String[].class}), + Arguments.of("processBkCpbSharedGroup", "processPrecisionOctaveSharedGroup", int.class, new Class[] {long.class, double[][].class}), + Arguments.of("pushBkCpbTask", "pushPrecisionOctaveTask", int.class, new Class[] {String.class, double[].class, int.class}), + Arguments.of("createBkCpbMultiTask", "createPrecisionOctaveMultiTask", int.class, new Class[] {String.class, double.class, double[].class, double[].class, double.class, int.class, double.class, int.class, int.class, int.class, double.class, double.class, double.class, int.class, int.class, double.class, double.class}), + Arguments.of("readBkCpbMultiTask", "readPrecisionOctaveMultiTask", int.class, new Class[] {String.class, JniNamedDoubleResultCollector.class, Map.class}), + Arguments.of("readBkCpbTask", "readPrecisionOctaveTask", int.class, new Class[] {String.class, JniNamedDoubleResultCollector.class, Map.class}), + Arguments.of("readBkCpbSelectedResult", "readPrecisionOctaveSelectedResult", int.class, new Class[] {String.class, int.class, int.class, int.class, JniNamedDoubleResultCollector.class, String[].class}), + Arguments.of("resetBkCpbTask", "resetPrecisionOctaveTask", int.class, new Class[] {String.class}), + Arguments.of("disposeBkCpbTask", "disposePrecisionOctaveTask", int.class, new Class[] {String.class}), + Arguments.of("createBkCpbFrfTask", "createPrecisionOctaveFrequencyResponseTask", int.class, new Class[] {String.class, double.class, int.class, double.class, double.class, double.class, int.class, double.class, int.class, int.class, int.class, double.class, double.class, double.class, int.class, int.class, double.class, double.class, int.class, int.class}), + Arguments.of("pushBkCpbFrfTask", "pushPrecisionOctaveFrequencyResponseTask", int.class, new Class[] {String.class, double[].class, double[].class, int.class}), + Arguments.of("readBkCpbFrfTask", "readPrecisionOctaveFrequencyResponseTask", int.class, new Class[] {String.class, JniNamedDoubleResultCollector.class, Map.class}), + Arguments.of("readBkCpbFrfSelectedResult", "readPrecisionOctaveFrequencyResponseSelectedResult", int.class, new Class[] {String.class, int.class, int.class, int.class, JniNamedDoubleResultCollector.class, String[].class}), + Arguments.of("resetBkCpbFrfTask", "resetPrecisionOctaveFrequencyResponseTask", int.class, new Class[] {String.class}), + Arguments.of("disposeBkCpbFrfTask", "disposePrecisionOctaveFrequencyResponseTask", int.class, new Class[] {String.class}), + Arguments.of("createBkTriggerTask", "createSignalTriggerTask", int.class, new Class[] {String.class, double.class, double.class, double.class, boolean.class, int.class, int.class, int.class}), + Arguments.of("searchBkTriggerTask", "searchSignalTriggerTask", String.class, new Class[] {String.class, double[].class, boolean.class}), + Arguments.of("resetBkTriggerTask", "resetSignalTriggerTask", int.class, new Class[] {String.class}), + Arguments.of("disposeBkTriggerTask", "disposeSignalTriggerTask", int.class, new Class[] {String.class})); } } diff --git a/apps/backend/crydaq-server/src/main/resources/native/macos-arm64/BUILD-INFO.json b/apps/backend/crydaq-server/src/main/resources/native/macos-arm64/BUILD-INFO.json new file mode 100644 index 00000000..4861730a --- /dev/null +++ b/apps/backend/crydaq-server/src/main/resources/native/macos-arm64/BUILD-INFO.json @@ -0,0 +1,24 @@ +{ + "platform": "macos-arm64", + "minimumMacOS": "12.0", + "configuration": "Release", + "algorithmCommit": "46a640bdc6d019ec4a51dbdef7f675d1c5700b06", + "nativeDriverBaseCommit": "a50dfde6fbb755c7b5171536f5c9d7d95b70647f", + "frameworkBaseCommit": "d2c55d82551e09d17cc288f8c07dfa2e741a2037", + "fftBackend": "FFTC", + "authorizationVariant": "production", + "validation": { + "algorithmCtestPassed": 16, + "driverSoftwareCtestPassed": 12, + "frontendNativeTestsPassed": 45, + "productionJniAuthorization": "default device001 license imported; unlicensed FFT feature correctly rejected (13300010)", + "hardwareTested": false, + "algorithmRuntimeJavaTestsPassed": 227, + "jniHeaderExportsMatched": 323, + "windowsAlgorithmExportsMatchedStatic": 148, + "packagingAndLicenseTestsPassed": 35, + "packagingAndLicenseTestsSkipped": 1, + "jniVerifierRegressionTestsPassed": 2, + "linuxBinaryCompatibilityVerified": false + } +} diff --git a/apps/backend/crydaq-server/src/main/resources/native/macos-arm64/License.dat b/apps/backend/crydaq-server/src/main/resources/native/macos-arm64/License.dat new file mode 100644 index 00000000..8a67d5c0 --- /dev/null +++ b/apps/backend/crydaq-server/src/main/resources/native/macos-arm64/License.dat @@ -0,0 +1 @@ +{"payload":"qER0eXBlZ2xpY2Vuc2VIZmVhdHVyZXOFpURjb2RlZTkyMDA0RXZhbHVlZHRydWVHZW5kVGltZRsAAAR68lOoEElzdGFydFRpbWUbAAABnLGwllBJdmFsdWVUeXBlAKVEY29kZWU5MjAxMkV2YWx1ZWExR2VuZFRpbWUbAAAEevJTqBBJc3RhcnRUaW1lGwAAAZyxsJZQSXZhbHVlVHlwZQGlRGNvZGVlOTIwMDhFdmFsdWVhNEdlbmRUaW1lGwAABHryU6gQSXN0YXJ0VGltZRsAAAGcsbCWUEl2YWx1ZVR5cGUBpURjb2RlZTkyMDA5RXZhbHVlZHRydWVHZW5kVGltZRsAAAR68lOoEElzdGFydFRpbWUbAAABnLGwllBJdmFsdWVUeXBlAKVEY29kZWU5MjAxMUV2YWx1ZWQyNDAwR2VuZFRpbWUbAAAEevJTqBBJc3RhcnRUaW1lGwAAAZyxsJZQSXZhbHVlVHlwZQFIaXNzdWVkQXQbAAABn9TII8ZJZXhwaXJlc0F0GwAABH3gXMQYSWxpY2Vuc2VJZAFJbWFjaGluZUlkaWRldmljZTAwMUlub3RCZWZvcmUbAAABn9TII8ZLb2ZmbGluZURheXMaAA9CPw==","signature":"MEQCIFHQzyRudRXO4MtZjTzit/evGvXk470bnocYxyJ4TXK4AiBRF4wSmnqscMa4uvhiohYfpioRWyLCr8/qx8rV5i/viQ==","algorithm":"sha256-ecdsa","assetList":[{"skuInfo":{"code":"community","name":"OpenTest Community","type":"EDITION","description_items":["2 Channels","Monitor & Generator","Basic FFT","Basic Octave","Basic Sweep"],"descriptionItems":["2 Channels","Monitor & Generator","Basic FFT","Basic Octave","Basic Sweep"],"features":[{"name":"Monitor"},{"name":"Generator"}]},"authorizationCode":"CKFR-SAX3-JSJ7-LZGN","expireTime":4926098090000,"isExpired":false}]} diff --git a/apps/backend/crydaq-server/src/main/resources/native/macos-arm64/OptDevHost b/apps/backend/crydaq-server/src/main/resources/native/macos-arm64/OptDevHost new file mode 100755 index 00000000..7fa72a57 Binary files /dev/null and b/apps/backend/crydaq-server/src/main/resources/native/macos-arm64/OptDevHost differ diff --git a/apps/backend/crydaq-server/src/main/resources/native/macos-arm64/README.md b/apps/backend/crydaq-server/src/main/resources/native/macos-arm64/README.md new file mode 100644 index 00000000..34c0c03d --- /dev/null +++ b/apps/backend/crydaq-server/src/main/resources/native/macos-arm64/README.md @@ -0,0 +1,33 @@ +# macOS ARM64 native runtime + +Production-only runtime, built from the same algorithm commit as the Windows SDK (`46a640bdc6d0`, on `sxp_dev`). The C++ driver and frontend use FFTC. `License.dat` and `libcry_analyst.dylib` reside directly in this directory; there is no `prd` override or development authorization payload. + +Core runtime requires macOS 12 or later. SonoDAQ is an external plugin and its SDK 1.4.0 requires macOS 26. It is not bundled here. Private diagnostic tools are not application runtime dependencies. + +See `BUILD-INFO.json` for provenance and test results. The signed default `device001` license imports successfully after aligning macOS with Windows machine-ID policy. It does not grant FFT access; full authorized FFT execution and hardware acceptance remain unverified. The development/test SDK remains in NativeDriver. Checksums cover the runtime binaries and default license; documentation and build metadata are excluded. They do not imply additional license rights. + +## Reproduce verification + +Run the following on Apple Silicon macOS. The Maven commands prepare the classpath without running unrelated backend tests; they are not acceptance tests. `javac -h` generates JNI declarations from the current bridge sources, including generics, multiline declarations, escaping and overloads. The verifier checks every generated macOS export, loads all eight dylibs, validates ARM64/hash/path constraints, optionally checks existing Windows algorithm exports, and runs the default-license smoke test under `-Xcheck:jni`. The smoke test releases the license state in a `finally` block. It does not exercise licensed FFT or hardware. + +```sh +# From the OpenTest repository root, with JDK 21+, Maven and Node on PATH. +mvn -B --no-transfer-progress -f apps/backend/pom.xml -pl crydaq-core -am -Dmaven.test.skip=true install +mvn -B --no-transfer-progress -f apps/backend/crydaq-core/pom.xml dependency:build-classpath -Dmdep.outputFile=target/macos-jni-dependencies.txt +JNI_CP="apps/backend/crydaq-core/target/classes:apps/backend/crydaq-algorithm-runtime/target/classes:$(cat apps/backend/crydaq-core/target/macos-jni-dependencies.txt)" +python3 tools/verify-macos-native.py --class-path "$JNI_CP" --windows-native apps/backend/crydaq-server/src/main/resources/native/windows-amd64 --smoke +``` + +The optional Windows check is static PE export inspection, not Windows execution. There is no Linux backend payload in this checkout; Linux binary compatibility remains unverified. NativeDriver's fixed base `a50dfde6fbb755c7b5171536f5c9d7d95b70647f` defines the neutral JNI names in the shared POSIX source/header, but this is source evidence only, not proof for externally supplied Linux binaries. Do not treat this delivery as Linux acceptance. + +## Algorithm provenance and authorization review + +`algorithm-build-info.json` identifies the exact historical algorithm commit, DLL hash and patch. The base was detached, so `sourceBranch` remains empty and `sourceTreeDirty` truthfully records the applied patch. The patch is preserved in the private NativeDriver repository at commit `92982a31a6545fb87103a0acaadaaa348ae0439b`, path `dependencies/algorithm/macos/algorithm-fftc.patch`, SHA256 `da3e70b9285619c23b8280488ff918b59b16dbd758fa392e852245c2dbed6655`. Authorized reviewers can check out algorithm commit `46a640bdc6d019ec4a51dbdef7f675d1c5700b06`, verify the patch hash and apply it with `git apply`. Access to the private sources/FFTC dependency is required to rebuild; no private algorithm source is published here. + +The signed initial `device001` PC license skips machine matching, as required for the default-license delivery. This does not grant additional features: the bundled default still rejects FFT with 13300010. Signature and explicit USB identity checks remain in the recorded patch. The patch does not restrict the machine-match exception by SKU; the authorization owner must confirm the issuer policy and prevent issuing higher-rights licenses to this initial ID. This is an outstanding policy review, not a reason to silently alter authorization logic in this macOS PR. + +The production-only layout is intentional. Selecting macOS test mode fails before staging, and a missing/empty root `License.dat` is rejected. A product/release owner should confirm the default community FFT feature-denial behavior. No test algorithm, replacement license or rights bypass is packaged to hide that result. + +The verifier regression tests run with `python3 -m unittest discover -s tools/__tests__ -p test_verify_macos_native.py` (JDK on PATH or JAVA_HOME). + +The macOS and existing Windows default license JSON payload and signature are identical; the files differ only by a trailing newline. The original macOS file is retained. diff --git a/apps/backend/crydaq-server/src/main/resources/native/macos-arm64/README.zh-CN.md b/apps/backend/crydaq-server/src/main/resources/native/macos-arm64/README.zh-CN.md new file mode 100644 index 00000000..d60f739c --- /dev/null +++ b/apps/backend/crydaq-server/src/main/resources/native/macos-arm64/README.zh-CN.md @@ -0,0 +1,33 @@ +# macOS ARM64 原生运行库 + +仅包含生产运行库,算法固定使用 Windows SDK 对应的 `sxp_dev` 历史提交 `46a640bdc6d0`。C++ 驱动和前端均使用 FFTC。`License.dat` 与 `libcry_analyst.dylib` 直接位于本目录,不再设置 `prd` 或分发开发授权材料。 + +核心运行库最低要求 macOS 12。SonoDAQ 属于外部插件,其 SDK 1.4.0 最低要求 macOS 26,不在本目录中打包。私有诊断工具不属于应用运行依赖。 + +构建来源及测试结果见 `BUILD-INFO.json`。已统一 macOS 与 Windows 的设备 ID 规则,签名有效的默认 `device001` 授权可正常导入。该默认文件未授予 FFT 权限,完整 FFT 调用及真机验收尚未验证。NativeDriver 保留开发/测试 SDK。校验和仅覆盖运行时二进制与默认授权,不覆盖文档和构建元数据,也不代表增加授权权益。 + +## 复现验证 + +在 Apple Silicon macOS、JDK 21+、Maven 与 Node 环境中执行以下命令。Maven 命令仅准备编译类和依赖,不运行无关后端测试,不等于验收通过。校验器使用 `javac -h` 从当前桥接源码生成 JNI 声明,正确处理泛型、多行声明、转义和重载,然后检查 macOS 导出、8 个动态库加载、ARM64 架构、校验和及开发机路径,并在真实 JVM 的 `-Xcheck:jni` 下验证默认授权。冒烟测试通过 `finally` 释放授权状态;不验证完整授权 FFT 和硬件。 + +```sh +# From the OpenTest repository root, with JDK 21+, Maven and Node on PATH. +mvn -B --no-transfer-progress -f apps/backend/pom.xml -pl crydaq-core -am -Dmaven.test.skip=true install +mvn -B --no-transfer-progress -f apps/backend/crydaq-core/pom.xml dependency:build-classpath -Dmdep.outputFile=target/macos-jni-dependencies.txt +JNI_CP="apps/backend/crydaq-core/target/classes:apps/backend/crydaq-algorithm-runtime/target/classes:$(cat apps/backend/crydaq-core/target/macos-jni-dependencies.txt)" +python3 tools/verify-macos-native.py --class-path "$JNI_CP" --windows-native apps/backend/crydaq-server/src/main/resources/native/windows-amd64 --smoke +``` + +可选的 Windows 检查仅静态读取 PE 导出表,不是 Windows 实际执行。当前仓库没有 Linux 后端运行库,因此 Linux 二进制兼容性尚未验证。NativeDriver 固定基线 `a50dfde6fbb755c7b5171536f5c9d7d95b70647f` 的共享 POSIX 源码/头文件已声明中性 JNI 名称,但源码证据不能证明外部 Linux 二进制兼容;本交付不代表 Linux 验收。 + +## 算法来源与授权审核 + +`algorithm-build-info.json` 记录算法历史提交、库哈希和补丁位置。基线以 detached 模式构建,因此保留空 `sourceBranch`,`sourceTreeDirty` 如实表示应用过补丁。补丁已保存于私有 NativeDriver 仓库提交 `92982a31a6545fb87103a0acaadaaa348ae0439b`,路径 `dependencies/algorithm/macos/algorithm-fftc.patch`,SHA256 为 `da3e70b9285619c23b8280488ff918b59b16dbd758fa392e852245c2dbed6655`。有权限的审核者可检出算法提交 `46a640bdc6d019ec4a51dbdef7f675d1c5700b06`,核对补丁哈希后通过 `git apply` 应用。复现构建需要私有源码及 FFTC 依赖,本仓库不公开私有算法源码。 + +按默认授权交付要求,签名有效的初始 `device001` PC 授权跳过机器匹配,但不会获得额外功能;默认文件的 FFT 仍返回 13300010。签名及显式 USB 身份检查仍保留于上述补丁。补丁没有按 SKU 限制这条机器匹配豁免,需授权负责人确认签发规则,避免用初始 ID 签发高权益许可证。这是待确认的策略事项,不在 macOS PR 中擅自修改授权逻辑。 + +仅生产运行库的平铺交付是明确要求。macOS 选择 test 模式会在暂存前失败,根目录缺失或空 `License.dat` 也会被拒绝。默认社区包的 FFT 权限拒绝行为仍需产品/发布负责人确认;不通过打入测试算法、替换授权或绕过权益来隐藏该结果。 + +校验工具自身的回归测试:`python3 -m unittest discover -s tools/__tests__ -p test_verify_macos_native.py`,需通过 PATH 或 JAVA_HOME 配置 JDK。 + +macOS 与当前 Windows 默认授权的 JSON 载荷和签名相同,仅文件末尾换行有差异;保留原始 macOS 文件。 diff --git a/apps/backend/crydaq-server/src/main/resources/native/macos-arm64/SHA256SUMS.txt b/apps/backend/crydaq-server/src/main/resources/native/macos-arm64/SHA256SUMS.txt new file mode 100644 index 00000000..7a8db587 --- /dev/null +++ b/apps/backend/crydaq-server/src/main/resources/native/macos-arm64/SHA256SUMS.txt @@ -0,0 +1,10 @@ +de7e0c68b56e8839e8238fd136c3afadc87b8c25b759d71d9a710a9c8f67f546 License.dat +2e817b12f464b17b48f1d635f2885e088567bc1c0c31154435d9824194eae7a1 OptDevHost +85b3259d266708f1c2304ed07738153416b9bb36a55fb1c63bf858ce0d370fe5 libCRYAlgorithmLib.dylib +8fc47546de322d18bc881b6556c0c4b90bd6595d96a41efee51aa44775a4f5a9 libCRYBluetoothLib.dylib +f71c304b10e9c4c4d02f0f8e12dc615e7e5c7e9673de7b8b1fdf5cba0895a6db libCRYJNIAudioProtocol.dylib +6d408c42b386600d6d16ba9b62721a2a98e012192c46a14a14284cc5ab1a5646 libCRYSequenceLib.dylib +c43f1a1d3d09cc118690898a0cfbebef82360fa1e3ef8bbdad0f09ee03b418e4 libCRYUnitConversion.dylib +15e2726e0040a1de74aa0d5d8ffb78737028867b44e591e6415b05320b786756 libcry_analyst.dylib +ee58d37ee55bed2bf2a5c2ef07a0c7a17703efba465633440610aec3c6d0edb0 libfftc3.dylib +3cecb75c42bfcc27172f21eaef44dfa7d215c0e0ebcd960fc8d74246ef80ee17 libfront-algorithm.dylib diff --git a/apps/backend/crydaq-server/src/main/resources/native/macos-arm64/algorithm-build-info.json b/apps/backend/crydaq-server/src/main/resources/native/macos-arm64/algorithm-build-info.json new file mode 100644 index 00000000..8f4a5b3c --- /dev/null +++ b/apps/backend/crydaq-server/src/main/resources/native/macos-arm64/algorithm-build-info.json @@ -0,0 +1,22 @@ +{ + "platform": "darwin", + "architecture": "arm64", + "configuration": "Release", + "sourceBranch": "", + "sourceCommit": "46a640bdc6d019ec4a51dbdef7f675d1c5700b06", + "builtAt": "2026-11-16T07:26:13.682754+00:00", + "authorizationVariant": "production", + "fftBackend": "FFTC", + "sourceTreeDirty": true, + "sourcePatchSha256": "da3e70b9285619c23b8280488ff918b59b16dbd758fa392e852245c2dbed6655", + "librarySha256": "15e2726e0040a1de74aa0d5d8ffb78737028867b44e591e6415b05320b786756", + "validation": { + "ctestPassed": true + }, + "defaultLicenseDeviceIdPolicy": "device001 skips PC machine matching on all platforms; explicit USB IDs still checked", + "sourceCheckoutMode": "detached historical sxp_dev base with recorded patch", + "sourcePatchRepository": "crysound/OpenTest-NativeDriver", + "sourcePatchCommit": "92982a31a6545fb87103a0acaadaaa348ae0439b", + "sourcePatchPath": "dependencies/algorithm/macos/algorithm-fftc.patch", + "sourcePatchUrl": "https://github.com/crysound/OpenTest-NativeDriver/blob/92982a31a6545fb87103a0acaadaaa348ae0439b/dependencies/algorithm/macos/algorithm-fftc.patch" +} diff --git a/apps/backend/crydaq-server/src/main/resources/native/macos-arm64/libCRYAlgorithmLib.dylib b/apps/backend/crydaq-server/src/main/resources/native/macos-arm64/libCRYAlgorithmLib.dylib new file mode 100755 index 00000000..aec5b4d9 Binary files /dev/null and b/apps/backend/crydaq-server/src/main/resources/native/macos-arm64/libCRYAlgorithmLib.dylib differ diff --git a/apps/backend/crydaq-server/src/main/resources/native/macos-arm64/libCRYBluetoothLib.dylib b/apps/backend/crydaq-server/src/main/resources/native/macos-arm64/libCRYBluetoothLib.dylib new file mode 100755 index 00000000..00672f17 Binary files /dev/null and b/apps/backend/crydaq-server/src/main/resources/native/macos-arm64/libCRYBluetoothLib.dylib differ diff --git a/apps/backend/crydaq-server/src/main/resources/native/macos-arm64/libCRYJNIAudioProtocol.dylib b/apps/backend/crydaq-server/src/main/resources/native/macos-arm64/libCRYJNIAudioProtocol.dylib new file mode 100755 index 00000000..83db4383 Binary files /dev/null and b/apps/backend/crydaq-server/src/main/resources/native/macos-arm64/libCRYJNIAudioProtocol.dylib differ diff --git a/apps/backend/crydaq-server/src/main/resources/native/macos-arm64/libCRYSequenceLib.dylib b/apps/backend/crydaq-server/src/main/resources/native/macos-arm64/libCRYSequenceLib.dylib new file mode 100755 index 00000000..99ed1688 Binary files /dev/null and b/apps/backend/crydaq-server/src/main/resources/native/macos-arm64/libCRYSequenceLib.dylib differ diff --git a/apps/backend/crydaq-server/src/main/resources/native/macos-arm64/libCRYUnitConversion.dylib b/apps/backend/crydaq-server/src/main/resources/native/macos-arm64/libCRYUnitConversion.dylib new file mode 100755 index 00000000..af45658b Binary files /dev/null and b/apps/backend/crydaq-server/src/main/resources/native/macos-arm64/libCRYUnitConversion.dylib differ diff --git a/apps/backend/crydaq-server/src/main/resources/native/macos-arm64/libcry_analyst.dylib b/apps/backend/crydaq-server/src/main/resources/native/macos-arm64/libcry_analyst.dylib new file mode 100755 index 00000000..3b779dd1 Binary files /dev/null and b/apps/backend/crydaq-server/src/main/resources/native/macos-arm64/libcry_analyst.dylib differ diff --git a/apps/backend/crydaq-server/src/main/resources/native/macos-arm64/libfftc3.dylib b/apps/backend/crydaq-server/src/main/resources/native/macos-arm64/libfftc3.dylib new file mode 100644 index 00000000..e140b426 Binary files /dev/null and b/apps/backend/crydaq-server/src/main/resources/native/macos-arm64/libfftc3.dylib differ diff --git a/apps/backend/crydaq-server/src/main/resources/native/macos-arm64/libfront-algorithm.dylib b/apps/backend/crydaq-server/src/main/resources/native/macos-arm64/libfront-algorithm.dylib new file mode 100755 index 00000000..470ebee9 Binary files /dev/null and b/apps/backend/crydaq-server/src/main/resources/native/macos-arm64/libfront-algorithm.dylib differ diff --git a/apps/backend/crydaq-server/src/main/resources/native/macos-arm64/licenses/FFTC-LICENSE.txt b/apps/backend/crydaq-server/src/main/resources/native/macos-arm64/licenses/FFTC-LICENSE.txt new file mode 100644 index 00000000..1cabf95d --- /dev/null +++ b/apps/backend/crydaq-server/src/main/resources/native/macos-arm64/licenses/FFTC-LICENSE.txt @@ -0,0 +1,28 @@ +BSD 3-Clause License + +Copyright (c) 2026 FFTC contributors + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +3. Neither the name of the copyright holder nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/apps/backend/crydaq-server/src/main/resources/native/macos-arm64/licenses/OpenSSL-LICENSE.txt b/apps/backend/crydaq-server/src/main/resources/native/macos-arm64/licenses/OpenSSL-LICENSE.txt new file mode 100644 index 00000000..49cc83d2 --- /dev/null +++ b/apps/backend/crydaq-server/src/main/resources/native/macos-arm64/licenses/OpenSSL-LICENSE.txt @@ -0,0 +1,177 @@ + + Apache License + Version 2.0, January 2004 + https://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS diff --git a/apps/backend/crydaq-server/src/main/resources/native/macos-arm64/licenses/pocketfft-LICENSE.txt b/apps/backend/crydaq-server/src/main/resources/native/macos-arm64/licenses/pocketfft-LICENSE.txt new file mode 100644 index 00000000..c3a4c06a --- /dev/null +++ b/apps/backend/crydaq-server/src/main/resources/native/macos-arm64/licenses/pocketfft-LICENSE.txt @@ -0,0 +1,25 @@ +Copyright (C) 2010-2018 Max-Planck-Society +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + +* Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. +* Redistributions in binary form must reproduce the above copyright notice, this + list of conditions and the following disclaimer in the documentation and/or + other materials provided with the distribution. +* Neither the name of the copyright holder nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON +ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/apps/backend/crydaq-server/src/main/resources/native/macos-arm64/native-libs-load-order.txt b/apps/backend/crydaq-server/src/main/resources/native/macos-arm64/native-libs-load-order.txt new file mode 100644 index 00000000..c2c3798c --- /dev/null +++ b/apps/backend/crydaq-server/src/main/resources/native/macos-arm64/native-libs-load-order.txt @@ -0,0 +1,7 @@ +libfftc3.dylib +libcry_analyst.dylib +libCRYUnitConversion.dylib +libCRYAlgorithmLib.dylib +libCRYJNIAudioProtocol.dylib +libCRYBluetoothLib.dylib +libCRYSequenceLib.dylib diff --git a/apps/desktop/packages/native-modules/scripts/posix-algorithm.js b/apps/desktop/packages/native-modules/scripts/posix-algorithm.js index 200e66af..036d2205 100644 --- a/apps/desktop/packages/native-modules/scripts/posix-algorithm.js +++ b/apps/desktop/packages/native-modules/scripts/posix-algorithm.js @@ -8,12 +8,13 @@ function resolveInputs({ projectRoot, env = process.env, platform = process.plat if (!['darwin', 'linux'].includes(platform)) throw new Error(`Unsupported POSIX native build: ${platform}/${arch}`) const nativePlatform = resolveNativePlatform({ platform, arch }) const repository = path.resolve(projectRoot, '../..') - const variant = env.OPENTEST_ALGORITHM_VARIANT || 'test' + const variant = env.OPENTEST_ALGORITHM_VARIANT || (platform === 'darwin' ? 'production' : 'test') if (!['test', 'production'].includes(variant)) throw new Error(`Invalid algorithm variant: ${variant}`) + if (platform === 'darwin' && variant !== 'production') throw new Error('macOS application runtime requires the production algorithm') const root = path.resolve(env.OPENTEST_PACKAGING_NATIVE || env[platform === 'darwin' ? 'OPENTEST_MAC_NATIVE' : 'OPENTEST_LINUX_NATIVE'] || path.join(repository, 'apps/backend/crydaq-server/src/main/resources/native', nativePlatform)) const analyst = platform === 'darwin' ? 'libcry_analyst.dylib' : 'libcry_analyst.so' - const library = path.join(root, variant === 'production' ? 'prd' : '', analyst) + const library = path.join(root, variant === 'production' && platform !== 'darwin' ? 'prd' : '', analyst) const files = algorithmLibraries(platform) .map(name => name === analyst ? library : path.join(root, name)) for (const file of files) { @@ -21,7 +22,7 @@ function resolveInputs({ projectRoot, env = process.env, platform = process.plat if (!stat?.isFile() || !stat.size) throw new Error(`Missing or invalid prebuilt native algorithm input: ${file}; provide runtime binary materials for ${nativePlatform}/${variant}`) } if (platform === 'darwin') { - const metadata = path.join(root, variant === 'production' ? 'production-algorithm-build-info.json' : 'algorithm-build-info.json') + const metadata = path.join(root, 'algorithm-build-info.json') const info = JSON.parse(fs.readFileSync(metadata, 'utf8')) const digest = crypto.createHash('sha256').update(fs.readFileSync(library)).digest('hex') if (info.authorizationVariant !== variant || info.platform !== platform || info.architecture !== arch || info.librarySha256 !== digest) { diff --git a/apps/desktop/packages/native-modules/test/algorithm_abi_contract.test.js b/apps/desktop/packages/native-modules/test/algorithm_abi_contract.test.js index 6f51315d..732aa1fb 100644 --- a/apps/desktop/packages/native-modules/test/algorithm_abi_contract.test.js +++ b/apps/desktop/packages/native-modules/test/algorithm_abi_contract.test.js @@ -1,3 +1,5 @@ +const nativeExtension = process.platform === 'win32' ? '.dll' : process.platform === 'darwin' ? '.dylib' : '.so' +const frontLibrary = (process.platform === 'win32' ? '' : 'lib') + 'front-algorithm' + nativeExtension const test = require('node:test') const assert = require('node:assert/strict') const path = require('node:path') @@ -6,8 +8,8 @@ const { spawnSync } = require('node:child_process') test('delivered DLL follows ABI, buffer, output_count and error semantics', () => { const packageRoot = path.join(__dirname, '..') const result = spawnSync( - path.join(packageRoot, 'build', 'Release', 'algorithm_abi_contract_test.exe'), - [path.join(packageRoot, 'dist', 'algorithm-bridge', 'front-algorithm.dll')], + path.join(packageRoot, 'build', 'Release', 'algorithm_abi_contract_test' + (process.platform === 'win32' ? '.exe' : '')), + [path.join(packageRoot, 'dist', 'algorithm-bridge', frontLibrary)], { encoding: 'utf8', windowsHide: true } ) diff --git a/apps/desktop/packages/native-modules/test/algorithm_bridge.test.js b/apps/desktop/packages/native-modules/test/algorithm_bridge.test.js index ccaa735b..e59c4a6a 100644 --- a/apps/desktop/packages/native-modules/test/algorithm_bridge.test.js +++ b/apps/desktop/packages/native-modules/test/algorithm_bridge.test.js @@ -1,3 +1,5 @@ +const nativeExtension = process.platform === 'win32' ? '.dll' : process.platform === 'darwin' ? '.dylib' : '.so' +const frontLibrary = (process.platform === 'win32' ? '' : 'lib') + 'front-algorithm' + nativeExtension const test = require('node:test') const assert = require('node:assert/strict') const fs = require('node:fs') @@ -21,7 +23,7 @@ const { const packageRoot = path.join(__dirname, '..') const addonPath = path.join(packageRoot, 'build', 'Release', 'algorithm_bridge.node') const statusFixturePath = path.join( - packageRoot, 'build', 'Release', 'front_algorithm_fixture_statuses.dll' + packageRoot, 'build', 'Release', 'front_algorithm_fixture_statuses' + nativeExtension ) function computeFixtureDeltaResult() { @@ -29,7 +31,7 @@ function computeFixtureDeltaResult() { try { const isolatedAddonPath = path.join(testDir, 'algorithm_bridge.node') fs.copyFileSync(addonPath, isolatedAddonPath) - fs.copyFileSync(statusFixturePath, path.join(testDir, 'front-algorithm.dll')) + fs.copyFileSync(statusFixturePath, path.join(testDir, frontLibrary)) const script = [ 'const addon = require(process.argv[1]);', 'const result = addon.computeTimeDelta(', @@ -53,7 +55,7 @@ function readFixtureUnitConversionConfig() { try { const isolatedAddonPath = path.join(testDir, 'algorithm_bridge.node') fs.copyFileSync(addonPath, isolatedAddonPath) - fs.copyFileSync(statusFixturePath, path.join(testDir, 'front-algorithm.dll')) + fs.copyFileSync(statusFixturePath, path.join(testDir, frontLibrary)) const script = [ 'const addon = require(process.argv[1]);', 'const result = addon.convertUnits({', diff --git a/apps/desktop/packages/native-modules/test/algorithm_loader_failures.test.js b/apps/desktop/packages/native-modules/test/algorithm_loader_failures.test.js index e1e690d2..0e223162 100644 --- a/apps/desktop/packages/native-modules/test/algorithm_loader_failures.test.js +++ b/apps/desktop/packages/native-modules/test/algorithm_loader_failures.test.js @@ -1,3 +1,5 @@ +const nativeExtension = process.platform === 'win32' ? '.dll' : process.platform === 'darwin' ? '.dylib' : '.so' +const frontLibrary = (process.platform === 'win32' ? '' : 'lib') + 'front-algorithm' + nativeExtension const test = require('node:test') const assert = require('node:assert/strict') const fs = require('node:fs') @@ -8,7 +10,7 @@ const { spawnSync } = require('node:child_process') const packageRoot = path.join(__dirname, '..') const addonPath = path.join(packageRoot, 'build', 'Release', 'algorithm_bridge.node') const buildDir = path.join(packageRoot, 'build', 'Release') -const vendorDir = path.join(packageRoot, 'vendor', 'algorithm-bridge') +const vendorDir = path.join(packageRoot, process.platform === 'win32' ? 'vendor' : 'dist', 'algorithm-bridge') function runIsolated(files = {}, invocation = 'addon.interpolatePoints(new Float64Array([0]), new Float64Array([0]), new Float64Array([0]))') { @@ -37,7 +39,7 @@ function runIsolated(files = {}, invocation = function vendorFilesExcept(excludedName) { return Object.fromEntries( - require('../../../src/config/algorithm-libraries').algorithmLibraries('win32') + require('../../../src/config/algorithm-libraries').algorithmLibraries() .filter(name => name !== excludedName) .map(name => [name, path.join(vendorDir, name)]) ) @@ -46,24 +48,27 @@ function vendorFilesExcept(excludedName) { test('reports a stable error when front-algorithm.dll is missing', () => { const error = runIsolated() assert.equal(error.code, 'FRONT_ALGORITHM_DLL_LOAD_FAILED') - assert.match(error.message, /front-algorithm\.dll/) + assert.ok(error.message.includes(frontLibrary)) }) test('reports a stable load error when cry_analyst.dll is missing', () => { - const error = runIsolated(vendorFilesExcept('cry_analyst.dll')) + const error = runIsolated(vendorFilesExcept((process.platform === 'win32' ? '' : 'lib') + 'cry_analyst' + nativeExtension)) assert.equal(error.code, 'FRONT_ALGORITHM_DLL_LOAD_FAILED') - assert.match(error.message, /front-algorithm\.dll/) + assert.ok(error.message.includes(frontLibrary)) }) -test('reports a stable load error when fftc3.dll is missing', () => { - const error = runIsolated(vendorFilesExcept('fftc3.dll')) +test('reports a stable load error when the configured FFT dependency is missing', () => { + const dependency = process.platform === 'linux' ? 'libfftw3.so.3' + : (process.platform === 'win32' ? '' : 'lib') + 'fftc3' + nativeExtension + assert.ok(require('../../../src/config/algorithm-libraries').algorithmLibraries().includes(dependency)) + const error = runIsolated(vendorFilesExcept(dependency)) assert.equal(error.code, 'FRONT_ALGORITHM_DLL_LOAD_FAILED') - assert.match(error.message, /front-algorithm\.dll/) + assert.ok(error.message.includes(frontLibrary)) }) test('reports a stable error when the required FFT Delta DLL export is missing', () => { const error = runIsolated({ - 'front-algorithm.dll': path.join(buildDir, 'front_algorithm_fixture_missing_export.dll') + [frontLibrary]: path.join(buildDir, 'front_algorithm_fixture_missing_export' + nativeExtension) }) assert.equal(error.code, 'FRONT_ALGORITHM_DLL_MISSING_EXPORT') assert.match(error.message, /FrontAlgorithm_ComputeFFTDelta/) @@ -71,7 +76,7 @@ test('reports a stable error when the required FFT Delta DLL export is missing', test('reports a stable error when the required CPB Delta DLL export is missing', () => { const error = runIsolated({ - 'front-algorithm.dll': path.join(buildDir, 'front_algorithm_fixture_missing_cpb_export.dll') + [frontLibrary]: path.join(buildDir, 'front_algorithm_fixture_missing_cpb_export' + nativeExtension) }) assert.equal(error.code, 'FRONT_ALGORITHM_DLL_MISSING_EXPORT') assert.match(error.message, /FrontAlgorithm_ComputeCPBDelta/) @@ -79,7 +84,7 @@ test('reports a stable error when the required CPB Delta DLL export is missing', test('reports a stable error when the required Time Delta DLL export is missing', () => { const error = runIsolated({ - 'front-algorithm.dll': path.join(buildDir, 'front_algorithm_fixture_missing_time_export.dll') + [frontLibrary]: path.join(buildDir, 'front_algorithm_fixture_missing_time_export' + nativeExtension) }) assert.equal(error.code, 'FRONT_ALGORITHM_DLL_MISSING_EXPORT') assert.match(error.message, /FrontAlgorithm_ComputeTimeDelta/) @@ -87,7 +92,7 @@ test('reports a stable error when the required Time Delta DLL export is missing' test('reports a stable error when the required batch unit conversion DLL export is missing', () => { const error = runIsolated({ - 'front-algorithm.dll': path.join(buildDir, 'front_algorithm_fixture_missing_convert_units_export.dll') + [frontLibrary]: path.join(buildDir, 'front_algorithm_fixture_missing_convert_units_export' + nativeExtension) }) assert.equal(error.code, 'FRONT_ALGORITHM_DLL_MISSING_EXPORT') assert.match(error.message, /FrontAlgorithm_ConvertUnits/) @@ -95,7 +100,7 @@ test('reports a stable error when the required batch unit conversion DLL export test('reports ABI mismatch with the stable loader code', () => { const error = runIsolated({ - 'front-algorithm.dll': path.join(buildDir, 'front_algorithm_fixture_abi_mismatch.dll') + [frontLibrary]: path.join(buildDir, 'front_algorithm_fixture_abi_mismatch' + nativeExtension) }) assert.equal(error.code, 'FRONT_ALGORITHM_ABI_MISMATCH') assert.equal(error.status, undefined) @@ -109,7 +114,7 @@ for (const [targetValue, code, status, message] of [ ]) { test(`maps DLL status ${status} to ${code} with the complete thread error`, () => { const error = runIsolated({ - 'front-algorithm.dll': path.join(buildDir, 'front_algorithm_fixture_statuses.dll') + [frontLibrary]: path.join(buildDir, 'front_algorithm_fixture_statuses' + nativeExtension) }, `addon.interpolatePoints( new Float64Array([0]), new Float64Array([0]), new Float64Array([${targetValue}]))`) assert.equal(error.code, code) @@ -120,7 +125,7 @@ for (const [targetValue, code, status, message] of [ test('rejects an invalid output_count returned by the DLL', () => { const error = runIsolated({ - 'front-algorithm.dll': path.join(buildDir, 'front_algorithm_fixture_statuses.dll') + [frontLibrary]: path.join(buildDir, 'front_algorithm_fixture_statuses' + nativeExtension) }, 'addon.lttbDownsample(new Float64Array([0, 1, 2]), new Float64Array([0, 1, 0]), 3)') assert.equal(error.code, 'FRONT_ALGORITHM_INVALID_RESULT') assert.equal(error.status, undefined) @@ -128,7 +133,7 @@ test('rejects an invalid output_count returned by the DLL', () => { test('rejects Generator Preview query counts that exceed the DLL contract maximums', () => { const error = runIsolated({ - 'front-algorithm.dll': path.join(buildDir, 'front_algorithm_fixture_statuses.dll') + [frontLibrary]: path.join(buildDir, 'front_algorithm_fixture_statuses' + nativeExtension) }, `addon.generatorPreview({ waveform: 0, sampleRateHz: 48000, diff --git a/apps/desktop/src/config/algorithm-libraries.js b/apps/desktop/src/config/algorithm-libraries.js index 1393f93e..13dbc2bf 100644 --- a/apps/desktop/src/config/algorithm-libraries.js +++ b/apps/desktop/src/config/algorithm-libraries.js @@ -2,8 +2,7 @@ const libraries = Object.freeze({ win32: ['front-algorithm.dll', 'CRYUnitConversion.dll', 'cry_analyst.dll', 'fftc3.dll', 'libgcc_s_seh-1.dll', 'libstdc++-6.dll', 'libwinpthread-1.dll'], darwin: ['libfront-algorithm.dylib', 'libCRYUnitConversion.dylib', 'libcry_analyst.dylib', - 'libfftw3.3.6.9.dylib', 'libfftw3.3.dylib', 'libfftw3_threads.3.6.9.dylib', - 'libfftw3_threads.3.dylib', 'libfftw3f.3.6.9.dylib', 'libfftw3f.3.dylib'], + 'libfftc3.dylib'], linux: ['libfront-algorithm.so', 'libCRYUnitConversion.so', 'libcry_analyst.so', 'libfftw3.so.3', 'libfftw3_threads.so.3'] }) diff --git a/apps/desktop/src/config/native-platform.js b/apps/desktop/src/config/native-platform.js index cb4fe6ad..5ac42ead 100644 --- a/apps/desktop/src/config/native-platform.js +++ b/apps/desktop/src/config/native-platform.js @@ -4,7 +4,7 @@ const fs = require('node:fs') const platforms = { 'windows-amd64': { nodePlatform: 'win32', nodeArch: 'x64', analystLibrary: 'cry_analyst.dll', licenseRequired: true }, 'linux-amd64': { nodePlatform: 'linux', nodeArch: 'x64', analystLibrary: 'libcry_analyst.so', licenseRequired: false }, - 'macos-arm64': { nodePlatform: 'darwin', nodeArch: 'arm64', analystLibrary: 'libcry_analyst.dylib', licenseRequired: false } + 'macos-arm64': { nodePlatform: 'darwin', nodeArch: 'arm64', analystLibrary: 'libcry_analyst.dylib', licenseRequired: true } } function resolveNativePlatform({ platform = process.platform, arch = process.arch } = {}) { @@ -21,8 +21,8 @@ function nativePlatformSettings(nativePlatform = 'windows-amd64') { function resolveNativeMaterials(resourcesRoot, nativePlatform = resolveNativePlatform()) { nativePlatformSettings(nativePlatform) const backendNative = path.join(resourcesRoot, 'native', nativePlatform) - // Windows ships one production algorithm and its paired license in the platform root. - const backendNativeOverrides = nativePlatform === 'windows-amd64' ? backendNative : path.join(backendNative, 'prd') + // Windows and macOS ship one production algorithm and its paired license in the platform root. + const backendNativeOverrides = ['windows-amd64', 'macos-arm64'].includes(nativePlatform) ? backendNative : path.join(backendNative, 'prd') return { nativePlatform, backendNative, backendNativeOverrides } } diff --git a/apps/native/src/tools/logcode.h b/apps/native/src/tools/logcode.h index 493f1605..525a40d5 100644 --- a/apps/native/src/tools/logcode.h +++ b/apps/native/src/tools/logcode.h @@ -257,31 +257,31 @@ enum class ErrorCode ALGORITHM_OUT_OF_MEMORY = 13200016, // Algorithm memory allocation failed. // Stimulus start/stop frequency must be below sampleRate / 2. ALGORITHM_FREQUENCY_EXCEEDS_NYQUIST = 13200017, - ALGORITHM_BK_FFT_INVALID_ARGUMENT = 13200018, - ALGORITHM_BK_FFT_GEOMETRY_ERROR = 13200019, - ALGORITHM_BK_FFT_ALLOCATION_ERROR = 13200020, - ALGORITHM_BK_FFT_ANALYSIS_ERROR = 13200021, - ALGORITHM_BK_FFT_STATE_ERROR = 13200022, - ALGORITHM_BK_FFT_CAPACITY_ERROR = 13200023, - ALGORITHM_BK_FFT_UNSUPPORTED = 13200024, - ALGORITHM_BK_FFT_FRAME_LENGTH_ERROR = 13200025, - ALGORITHM_BK_TRIGGER_INVALID_ARGUMENT = 13200026, - ALGORITHM_BK_TRIGGER_INVALID_MODE = 13200027, - ALGORITHM_BK_TRIGGER_INVALID_EDGE = 13200028, - ALGORITHM_BK_TRIGGER_NO_TRIGGER = 13200029, - ALGORITHM_BK_TRIGGER_INSUFFICIENT_PRETRIGGER = 13200030, - ALGORITHM_BK_TRIGGER_NO_COMPLETE_RECORD = 13200031, - ALGORITHM_BK_TRIGGER_CAPACITY_ERROR = 13200032, - ALGORITHM_BK_TRIGGER_STATE_ERROR = 13200033, - ALGORITHM_BK_TRIGGER_ALLOCATION_ERROR = 13200034, - ALGORITHM_BK_TRIGGER_UNSUPPORTED = 13200035, - ALGORITHM_BK_CPB_INVALID_ARGUMENT = 13200036, - ALGORITHM_BK_CPB_GEOMETRY_ERROR = 13200037, - ALGORITHM_BK_CPB_ALLOCATION_ERROR = 13200038, - ALGORITHM_BK_CPB_ANALYSIS_ERROR = 13200039, - ALGORITHM_BK_CPB_STATE_ERROR = 13200040, - ALGORITHM_BK_CPB_CAPACITY_ERROR = 13200041, - ALGORITHM_BK_CPB_UNSUPPORTED = 13200042, + ALGORITHM_ADVANCED_FFT_INVALID_ARGUMENT = 13200018, + ALGORITHM_ADVANCED_FFT_GEOMETRY_ERROR = 13200019, + ALGORITHM_ADVANCED_FFT_ALLOCATION_ERROR = 13200020, + ALGORITHM_ADVANCED_FFT_ANALYSIS_ERROR = 13200021, + ALGORITHM_ADVANCED_FFT_STATE_ERROR = 13200022, + ALGORITHM_ADVANCED_FFT_CAPACITY_ERROR = 13200023, + ALGORITHM_ADVANCED_FFT_UNSUPPORTED = 13200024, + ALGORITHM_ADVANCED_FFT_FRAME_LENGTH_ERROR = 13200025, + ALGORITHM_SIGNAL_TRIGGER_INVALID_ARGUMENT = 13200026, + ALGORITHM_SIGNAL_TRIGGER_INVALID_MODE = 13200027, + ALGORITHM_SIGNAL_TRIGGER_INVALID_EDGE = 13200028, + ALGORITHM_SIGNAL_TRIGGER_NO_TRIGGER = 13200029, + ALGORITHM_SIGNAL_TRIGGER_INSUFFICIENT_PRETRIGGER = 13200030, + ALGORITHM_SIGNAL_TRIGGER_NO_COMPLETE_RECORD = 13200031, + ALGORITHM_SIGNAL_TRIGGER_CAPACITY_ERROR = 13200032, + ALGORITHM_SIGNAL_TRIGGER_STATE_ERROR = 13200033, + ALGORITHM_SIGNAL_TRIGGER_ALLOCATION_ERROR = 13200034, + ALGORITHM_SIGNAL_TRIGGER_UNSUPPORTED = 13200035, + ALGORITHM_PRECISION_OCTAVE_INVALID_ARGUMENT = 13200036, + ALGORITHM_PRECISION_OCTAVE_GEOMETRY_ERROR = 13200037, + ALGORITHM_PRECISION_OCTAVE_ALLOCATION_ERROR = 13200038, + ALGORITHM_PRECISION_OCTAVE_ANALYSIS_ERROR = 13200039, + ALGORITHM_PRECISION_OCTAVE_STATE_ERROR = 13200040, + ALGORITHM_PRECISION_OCTAVE_CAPACITY_ERROR = 13200041, + ALGORITHM_PRECISION_OCTAVE_UNSUPPORTED = 13200042, ALGORITHM_RT60_INVALID_PARAMETER = 13200043, ALGORITHM_RT60_INSUFFICIENT_DATA = 13200044, ALGORITHM_RT60_SNR_LOW = 13200045, @@ -347,13 +347,13 @@ enum class ErrorCode ALGORITHM_AMPLITUDESWEEPGETCHART_FAILED = 13200105, // AMPLITUDESWEEPGETCHART_FAILED ALGORITHM_BANDRMSSPECTRUM_FAILED = 13200106, // BANDRMSSPECTRUM_FAILED ALGORITHM_BANDRMSWAVEFORM_FAILED = 13200107, // BANDRMSWAVEFORM_FAILED - ALGORITHM_BKCPB_FAILED = 13200108, // BKCPB_FAILED - ALGORITHM_BKCPBPUSHTASK_FAILED = 13200109, // BKCPBPUSHTASK_FAILED - ALGORITHM_BKFFT_FAILED = 13200110, // BKFFT_FAILED - ALGORITHM_BKFFTPUSHTASK_FAILED = 13200111, // BKFFTPUSHTASK_FAILED - ALGORITHM_BKFRF_FAILED = 13200112, // BKFRF_FAILED - ALGORITHM_BKFRFPUSHTASK_FAILED = 13200113, // BKFRFPUSHTASK_FAILED - ALGORITHM_BKTRIGGER_FAILED = 13200114, // BKTRIGGER_FAILED + ALGORITHM_PRECISION_OCTAVE_FAILED = 13200108, // BKCPB_FAILED + ALGORITHM_PRECISION_OCTAVE_PUSH_TASK_FAILED = 13200109, // BKCPBPUSHTASK_FAILED + ALGORITHM_ADVANCED_FFT_FAILED = 13200110, // BKFFT_FAILED + ALGORITHM_ADVANCED_FFT_PUSH_TASK_FAILED = 13200111, // BKFFTPUSHTASK_FAILED + ALGORITHM_ADVANCED_FREQUENCY_RESPONSE_FAILED = 13200112, // BKFRF_FAILED + ALGORITHM_ADVANCED_FREQUENCY_RESPONSE_PUSH_TASK_FAILED = 13200113, // BKFRFPUSHTASK_FAILED + ALGORITHM_SIGNAL_TRIGGER_FAILED = 13200114, // BKTRIGGER_FAILED ALGORITHM_CALCULATEFFTDATA_FAILED = 13200115, // CALCULATEFFTDATA_FAILED ALGORITHM_CALCULATELAEQ_FAILED = 13200116, // CALCULATELAEQ_FAILED ALGORITHM_CALCULATEMETER_FAILED = 13200117, // CALCULATEMETER_FAILED @@ -856,55 +856,55 @@ inline string GetErrorMsg(int code) return "Algorithm Out Of Memory"; case ErrorCode::ALGORITHM_FREQUENCY_EXCEEDS_NYQUIST: return "Algorithm Frequency Exceeds Nyquist"; - case ErrorCode::ALGORITHM_BK_FFT_INVALID_ARGUMENT: + case ErrorCode::ALGORITHM_ADVANCED_FFT_INVALID_ARGUMENT: return "Algorithm BK FFT Invalid Argument"; - case ErrorCode::ALGORITHM_BK_FFT_GEOMETRY_ERROR: + case ErrorCode::ALGORITHM_ADVANCED_FFT_GEOMETRY_ERROR: return "Algorithm BK FFT Geometry Error"; - case ErrorCode::ALGORITHM_BK_FFT_ALLOCATION_ERROR: + case ErrorCode::ALGORITHM_ADVANCED_FFT_ALLOCATION_ERROR: return "Algorithm BK FFT Allocation Error"; - case ErrorCode::ALGORITHM_BK_FFT_ANALYSIS_ERROR: + case ErrorCode::ALGORITHM_ADVANCED_FFT_ANALYSIS_ERROR: return "Algorithm BK FFT Analysis Error"; - case ErrorCode::ALGORITHM_BK_FFT_STATE_ERROR: + case ErrorCode::ALGORITHM_ADVANCED_FFT_STATE_ERROR: return "Algorithm BK FFT State Error"; - case ErrorCode::ALGORITHM_BK_FFT_CAPACITY_ERROR: + case ErrorCode::ALGORITHM_ADVANCED_FFT_CAPACITY_ERROR: return "Algorithm BK FFT Capacity Error"; - case ErrorCode::ALGORITHM_BK_FFT_UNSUPPORTED: + case ErrorCode::ALGORITHM_ADVANCED_FFT_UNSUPPORTED: return "Algorithm BK FFT Unsupported"; - case ErrorCode::ALGORITHM_BK_FFT_FRAME_LENGTH_ERROR: + case ErrorCode::ALGORITHM_ADVANCED_FFT_FRAME_LENGTH_ERROR: return "Algorithm BK FFT Frame Length Error"; - case ErrorCode::ALGORITHM_BK_TRIGGER_INVALID_ARGUMENT: + case ErrorCode::ALGORITHM_SIGNAL_TRIGGER_INVALID_ARGUMENT: return "Algorithm BK Trigger Invalid Argument"; - case ErrorCode::ALGORITHM_BK_TRIGGER_INVALID_MODE: + case ErrorCode::ALGORITHM_SIGNAL_TRIGGER_INVALID_MODE: return "Algorithm BK Trigger Invalid Mode"; - case ErrorCode::ALGORITHM_BK_TRIGGER_INVALID_EDGE: + case ErrorCode::ALGORITHM_SIGNAL_TRIGGER_INVALID_EDGE: return "Algorithm BK Trigger Invalid Edge"; - case ErrorCode::ALGORITHM_BK_TRIGGER_NO_TRIGGER: + case ErrorCode::ALGORITHM_SIGNAL_TRIGGER_NO_TRIGGER: return "Algorithm BK Trigger No Trigger"; - case ErrorCode::ALGORITHM_BK_TRIGGER_INSUFFICIENT_PRETRIGGER: + case ErrorCode::ALGORITHM_SIGNAL_TRIGGER_INSUFFICIENT_PRETRIGGER: return "Algorithm BK Trigger Insufficient Pretrigger"; - case ErrorCode::ALGORITHM_BK_TRIGGER_NO_COMPLETE_RECORD: + case ErrorCode::ALGORITHM_SIGNAL_TRIGGER_NO_COMPLETE_RECORD: return "Algorithm BK Trigger No Complete Record"; - case ErrorCode::ALGORITHM_BK_TRIGGER_CAPACITY_ERROR: + case ErrorCode::ALGORITHM_SIGNAL_TRIGGER_CAPACITY_ERROR: return "Algorithm BK Trigger Capacity Error"; - case ErrorCode::ALGORITHM_BK_TRIGGER_STATE_ERROR: + case ErrorCode::ALGORITHM_SIGNAL_TRIGGER_STATE_ERROR: return "Algorithm BK Trigger State Error"; - case ErrorCode::ALGORITHM_BK_TRIGGER_ALLOCATION_ERROR: + case ErrorCode::ALGORITHM_SIGNAL_TRIGGER_ALLOCATION_ERROR: return "Algorithm BK Trigger Allocation Error"; - case ErrorCode::ALGORITHM_BK_TRIGGER_UNSUPPORTED: + case ErrorCode::ALGORITHM_SIGNAL_TRIGGER_UNSUPPORTED: return "Algorithm BK Trigger Unsupported"; - case ErrorCode::ALGORITHM_BK_CPB_INVALID_ARGUMENT: + case ErrorCode::ALGORITHM_PRECISION_OCTAVE_INVALID_ARGUMENT: return "Algorithm BK CPB Invalid Argument"; - case ErrorCode::ALGORITHM_BK_CPB_GEOMETRY_ERROR: + case ErrorCode::ALGORITHM_PRECISION_OCTAVE_GEOMETRY_ERROR: return "Algorithm BK CPB Geometry Error"; - case ErrorCode::ALGORITHM_BK_CPB_ALLOCATION_ERROR: + case ErrorCode::ALGORITHM_PRECISION_OCTAVE_ALLOCATION_ERROR: return "Algorithm BK CPB Allocation Error"; - case ErrorCode::ALGORITHM_BK_CPB_ANALYSIS_ERROR: + case ErrorCode::ALGORITHM_PRECISION_OCTAVE_ANALYSIS_ERROR: return "Algorithm BK CPB Analysis Error"; - case ErrorCode::ALGORITHM_BK_CPB_STATE_ERROR: + case ErrorCode::ALGORITHM_PRECISION_OCTAVE_STATE_ERROR: return "Algorithm BK CPB State Error"; - case ErrorCode::ALGORITHM_BK_CPB_CAPACITY_ERROR: + case ErrorCode::ALGORITHM_PRECISION_OCTAVE_CAPACITY_ERROR: return "Algorithm BK CPB Capacity Error"; - case ErrorCode::ALGORITHM_BK_CPB_UNSUPPORTED: + case ErrorCode::ALGORITHM_PRECISION_OCTAVE_UNSUPPORTED: return "Algorithm BK CPB Unsupported"; case ErrorCode::ALGORITHM_RT60_INVALID_PARAMETER: return "Algorithm RT60 Invalid Parameter"; @@ -1035,19 +1035,19 @@ inline string GetErrorMsg(int code) return "ALGORITHM_BANDRMSSPECTRUM_FAILED"; case ErrorCode::ALGORITHM_BANDRMSWAVEFORM_FAILED: return "ALGORITHM_BANDRMSWAVEFORM_FAILED"; - case ErrorCode::ALGORITHM_BKCPB_FAILED: + case ErrorCode::ALGORITHM_PRECISION_OCTAVE_FAILED: return "ALGORITHM_BKCPB_FAILED"; - case ErrorCode::ALGORITHM_BKCPBPUSHTASK_FAILED: + case ErrorCode::ALGORITHM_PRECISION_OCTAVE_PUSH_TASK_FAILED: return "ALGORITHM_BKCPBPUSHTASK_FAILED"; - case ErrorCode::ALGORITHM_BKFFT_FAILED: + case ErrorCode::ALGORITHM_ADVANCED_FFT_FAILED: return "ALGORITHM_BKFFT_FAILED"; - case ErrorCode::ALGORITHM_BKFFTPUSHTASK_FAILED: + case ErrorCode::ALGORITHM_ADVANCED_FFT_PUSH_TASK_FAILED: return "ALGORITHM_BKFFTPUSHTASK_FAILED"; - case ErrorCode::ALGORITHM_BKFRF_FAILED: + case ErrorCode::ALGORITHM_ADVANCED_FREQUENCY_RESPONSE_FAILED: return "ALGORITHM_BKFRF_FAILED"; - case ErrorCode::ALGORITHM_BKFRFPUSHTASK_FAILED: + case ErrorCode::ALGORITHM_ADVANCED_FREQUENCY_RESPONSE_PUSH_TASK_FAILED: return "ALGORITHM_BKFRFPUSHTASK_FAILED"; - case ErrorCode::ALGORITHM_BKTRIGGER_FAILED: + case ErrorCode::ALGORITHM_SIGNAL_TRIGGER_FAILED: return "ALGORITHM_BKTRIGGER_FAILED"; case ErrorCode::ALGORITHM_CALCULATEFFTDATA_FAILED: return "ALGORITHM_CALCULATEFFTDATA_FAILED"; diff --git a/tools/__tests__/backend-native-license.test.mjs b/tools/__tests__/backend-native-license.test.mjs index 1e89972b..1c738903 100644 --- a/tools/__tests__/backend-native-license.test.mjs +++ b/tools/__tests__/backend-native-license.test.mjs @@ -8,7 +8,7 @@ import path from 'node:path' import { fileURLToPath } from 'node:url' const { assertBackendNativeInputs, resolveBackendLicense } = createRequire(import.meta.url)('../../apps/desktop/src/service/backend-launch.js') -const { resolveNativePlatform } = createRequire(import.meta.url)('../../apps/desktop/src/config/native-platform.js') +const { resolveNativePlatform, nativePlatformSettings } = createRequire(import.meta.url)('../../apps/desktop/src/config/native-platform.js') function fixture(t) { const root = mkdtempSync(path.join(os.tmpdir(), 'opentest-native-license-')) @@ -74,7 +74,7 @@ for (const missingLicense of [false, true]) { }) assert.equal(result.status, 1, result.stderr) assert.match(result.stdout, /test/) - assert.match(result.stderr, missingLicense && resolveNativePlatform() === 'windows-amd64' ? /许可证/ : /缺少前端构建产物/) + assert.match(result.stderr, missingLicense && nativePlatformSettings(resolveNativePlatform()).licenseRequired ? /许可证/ : /缺少前端构建产物/) if (missingLicense) assert.equal(existsSync(license), false) else assert.equal(readFileSync(license, 'utf8'), 'custom paired license') assert.equal(existsSync(path.join(root, 'runtime/logs/backend/backend-console.log')), false) diff --git a/tools/__tests__/fixtures/macos-native/MacJniSmoke.java b/tools/__tests__/fixtures/macos-native/MacJniSmoke.java new file mode 100644 index 00000000..f9d1aa99 --- /dev/null +++ b/tools/__tests__/fixtures/macos-native/MacJniSmoke.java @@ -0,0 +1,37 @@ +import com.opentest.core.jni.AlgorithmLibJNIBridge; +import com.opentest.core.jni.LicenseJNIBridge; +import com.opentest.algorithm.runtime.JniNamedDoubleResultCollector; +import java.util.HashMap; +public class MacJniSmoke { + static void ok(int code, String operation) { if (code != 0) throw new AssertionError(operation + ": " + code); } + public static void main(String[] args) { + System.load(args[0] + "/libCRYAlgorithmLib.dylib"); + System.load(args[0] + "/libCRYJNIAudioProtocol.dylib"); + ok(new LicenseJNIBridge().initialize(), "license initialize"); + try { + var bridge = new AlgorithmLibJNIBridge(); + ok(bridge.initialize(), "initialize"); + ok(bridge.authorizeAlgorithm(args[1]), "authorize"); + String id = "mac-jni-smoke"; + int created = bridge.createBkFftTask(id, 48000, 0, 10000, 1600, 5000, 1, 0, 0, 1, 0, 0, 1, 0, 0.1, 1, 1, 0, 0, 1, 0, 0, 0, 1); + if (args.length > 2 && args[2].equals("--default-license")) { + if (created != 13300010) throw new AssertionError("default license feature result: " + created); + System.out.println("Default license imported; unlicensed FFT feature rejected as expected"); + return; + } + ok(created, "create FFT"); + double[] samples = new double[48000]; + for (int i=0; i()), "read FFT"); + var result = collector.finish(); + if (result.isEmpty()) throw new AssertionError("empty FFT results"); + ok(bridge.disposeBkFftTask(id), "dispose FFT"); + System.out.println("JNI FFT lifecycle passed; result arrays=" + result.size()); + } finally { + ok(new LicenseJNIBridge().release(), "license release"); + } + } +} diff --git a/tools/__tests__/packaging-platforms.test.mjs b/tools/__tests__/packaging-platforms.test.mjs index 03526cbe..a32287f2 100644 --- a/tools/__tests__/packaging-platforms.test.mjs +++ b/tools/__tests__/packaging-platforms.test.mjs @@ -133,16 +133,17 @@ function nativeMaterials(root, platform) { const target = resolvePackagingPlatform(platform), native = path.join(root, 'materials', target.nativePlatform) const extension = platform === 'mac' ? '.dylib' : '.so' for (const name of algorithmLibraries(target.nodePlatform)) put(path.join(native, name), `test ${name}`) - put(path.join(native, 'prd', platform === 'mac' ? 'libcry_analyst.dylib' : 'libcry_analyst.so'), 'production analyst') + put(path.join(native, platform === 'mac' ? '' : 'prd', platform === 'mac' ? 'libcry_analyst.dylib' : 'libcry_analyst.so'), 'production analyst') + if (platform === 'mac') put(path.join(native, 'License.dat'), 'production license') for (const name of ['CRYAlgorithmLib', 'CRYJNIAudioProtocol', 'CRYSequenceLib']) { put(path.join(native, `lib${name}${extension}`), 'Java_com_opentest_core_jni_current') } put(path.join(native, `libCRYJNIAudioProtocol${extension}`), 'Java_com_opentest_core_jni_AudioDevicePluginJNIBridge_prepareManagedRuntime') put(path.join(native, 'OptDevHost'), 'prebuilt host') put(path.join(native, 'native-libs-load-order.txt'), `libcry_analyst${extension}\n`) - for (const mode of ['test', 'production']) if (platform === 'mac') { - const library = path.join(native, mode === 'production' ? 'prd' : '', 'libcry_analyst.dylib') - put(path.join(native, mode === 'production' ? 'production-algorithm-build-info.json' : 'algorithm-build-info.json'), JSON.stringify({ + for (const mode of ['production']) if (platform === 'mac') { + const library = path.join(native, 'libcry_analyst.dylib') + put(path.join(native, 'algorithm-build-info.json'), JSON.stringify({ authorizationVariant: mode, platform: 'darwin', architecture: 'arm64', librarySha256: createHash('sha256').update(readFileSync(library)).digest('hex') })) @@ -154,17 +155,17 @@ function desktopRoot(root) { return path.join(root, 'host/apps/desktop') } -for (const platform of ['mac', 'linux']) for (const mode of ['test', 'production']) { +for (const platform of ['mac', 'linux']) for (const mode of (platform === 'mac' ? ['production'] : ['test', 'production'])) { test(`${platform}/${mode} stages prebuilt JNI, Host and algorithms without JNI sources or default device plugins`, t => { const root = fixture(t) desktopRoot(root) const { native, target, extension } = nativeMaterials(root, platform) - put(path.join(native, 'License.dat'), 'test license') - put(path.join(native, 'prd/License.dat'), 'production license') + put(path.join(native, 'License.dat'), platform === 'mac' ? 'production license' : 'test license') + if (platform !== 'mac') put(path.join(native, 'prd/License.dat'), 'production license') put(path.join(native, 'device-data.json'), '{"keep":true}') for (const name of ['ot-plugin-manager', 'ot-plugin-status', 'qt/Qt5.so', 'qt.conf', 'PLUGIN-MANAGER.md', 'PLUGIN-STATUS.md', 'plugins/devices/optional.so', 'Plugs/devices/optional.so']) put(path.join(native, name), 'private tool or optional plugin') const config = preparePosixNative({ nativePlatform: target.nativePlatform, platform, mode, backendNative: native, - backendNativeOverrides: path.join(native, 'prd') }, path.join(root, 'stage')) + backendNativeOverrides: platform === 'mac' ? native : path.join(native, 'prd') }, path.join(root, 'stage')) assert.equal(readFileSync(path.join(config.backendNative, 'OptDevHost'), 'utf8'), 'prebuilt host') assert.equal(readFileSync(path.join(config.backendNative, `libCRYAlgorithmLib${extension}`), 'utf8'), 'Java_com_opentest_core_jni_current') assert.equal(readFileSync(path.join(config.backendNative, `libcry_analyst${extension}`), 'utf8'), mode === 'production' ? 'production analyst' : `test libcry_analyst${extension}`) @@ -177,7 +178,8 @@ for (const platform of ['mac', 'linux']) for (const mode of ['test', 'production const desktopInputs = resolveInputs({ projectRoot: path.join(root, 'host/apps/desktop'), platform: target.nodePlatform, arch: target.arch, env: { OPENTEST_PACKAGING_NATIVE: config.backendNative, OPENTEST_ALGORITHM_VARIANT: mode } }) assert.deepEqual(readFileSync(desktopInputs.library), readFileSync(path.join(config.backendNative, `libcry_analyst${extension}`))) - assert.equal(readFileSync(path.join(native, `libcry_analyst${extension}`), 'utf8'), `test libcry_analyst${extension}`) + assert.equal(readFileSync(path.join(native, `libcry_analyst${extension}`), 'utf8'), platform === 'mac' ? 'production analyst' : `test libcry_analyst${extension}`) + if (platform === 'mac') assert.equal(existsSync(path.join(config.backendNative, 'prd')), false) assert.equal(readFileSync(path.join(config.backendNative, 'device-data.json'), 'utf8'), '{"keep":true}') for (const name of ['ot-plugin-manager', 'ot-plugin-status', 'qt', 'qt.conf', 'PLUGIN-MANAGER.md', 'PLUGIN-STATUS.md', 'plugins/devices', 'Plugs/devices']) assert.equal(existsSync(path.join(config.backendNative, name)), false, name) }) @@ -188,7 +190,8 @@ for (const platform of ['mac', 'linux']) { const root = fixture(t) desktopRoot(root) const { native, target, extension } = nativeMaterials(root, platform) - const config = { nativePlatform: target.nativePlatform, mode: 'test', backendNative: native } + const config = { nativePlatform: target.nativePlatform, mode: platform === 'mac' ? 'production' : 'test', backendNative: native, + ...(platform === 'mac' ? { backendNativeOverrides: native } : {}) } let attempt = 0 const prepare = () => preparePosixNative(config, path.join(root, `stage-${attempt++}`)) for (const name of ['OptDevHost', `libfront-algorithm${extension}`, `libCRYUnitConversion${extension}`, `libCRYSequenceLib${extension}`]) { @@ -215,8 +218,8 @@ for (const platform of ['mac', 'linux']) { const { native, target } = nativeMaterials(root, platform) const platformKey = platform === 'mac' ? 'OPENTEST_MAC_NATIVE' : 'OPENTEST_LINUX_NATIVE' const resolve = env => resolveInputs({ projectRoot, platform: target.nodePlatform, arch: target.arch, env }) - for (const variant of ['test', 'production']) { - const selected = variant === 'production' ? 'prd' : '' + for (const variant of (platform === 'mac' ? ['production'] : ['test', 'production'])) { + const selected = variant === 'production' && platform !== 'mac' ? 'prd' : '' const inputs = resolve({ OPENTEST_PACKAGING_NATIVE: native, [platformKey]: '/missing/lower-priority', OPENTEST_ALGORITHM_VARIANT: variant }) assert.equal(inputs.vendorDir, native) assert.equal(inputs.library, path.join(native, selected, platform === 'mac' ? 'libcry_analyst.dylib' : 'libcry_analyst.so')) @@ -242,9 +245,9 @@ for (const platform of ['mac', 'linux']) { rmSync(file, { recursive: true }) put(file, original) } - const productionLibrary = path.join(native, 'prd', platform === 'mac' ? 'libcry_analyst.dylib' : 'libcry_analyst.so') + const productionLibrary = path.join(native, platform === 'mac' ? '' : 'prd', platform === 'mac' ? 'libcry_analyst.dylib' : 'libcry_analyst.so') rmSync(productionLibrary) - assert.throws(() => resolve({ OPENTEST_PACKAGING_NATIVE: native, OPENTEST_ALGORITHM_VARIANT: 'production' }), /prd/) + assert.throws(() => resolve({ OPENTEST_PACKAGING_NATIVE: native, OPENTEST_ALGORITHM_VARIANT: 'production' }), /prebuilt native algorithm input/) }) } @@ -252,7 +255,7 @@ test('macOS keeps variant, platform, architecture and checksum validation for pr const root = fixture(t), { native } = nativeMaterials(root, 'mac') const metadata = path.join(native, 'algorithm-build-info.json'), original = JSON.parse(readFileSync(metadata)) const resolve = () => resolveInputs({ projectRoot: path.join(root, 'host/apps/desktop'), platform: 'darwin', arch: 'arm64', env: { OPENTEST_PACKAGING_NATIVE: native } }) - for (const [key, value] of Object.entries({ authorizationVariant: 'production', platform: 'linux', architecture: 'x64', librarySha256: 'old' })) { + for (const [key, value] of Object.entries({ authorizationVariant: 'test', platform: 'linux', architecture: 'x64', librarySha256: 'old' })) { put(metadata, JSON.stringify({ ...original, [key]: value })) assert.throws(resolve, /variant\/platform\/checksum mismatch/) } @@ -299,7 +302,7 @@ function prebuiltAddon(t, platform, variant) { return { addon, native, calls, target, build: load(variant), load } } -for (const platform of ['mac', 'linux']) for (const variant of ['test', 'production']) { +for (const platform of ['mac', 'linux']) for (const variant of (platform === 'mac' ? ['production'] : ['test', 'production'])) { test(`${platform}/${variant} addon builds only repository code and stages selected runtime bytes`, t => { const { addon, native, calls, target, build, load } = prebuiltAddon(t, platform, variant) assert.equal(build.isBuilt(), false) @@ -311,9 +314,10 @@ for (const platform of ['mac', 'linux']) for (const variant of ['test', 'product assert.equal(load(variant).isBuilt(), true) const analyst = platform === 'mac' ? 'libcry_analyst.dylib' : 'libcry_analyst.so' for (const name of algorithmLibraries(target.nodePlatform)) { - assert.deepEqual(readFileSync(path.join(addon, 'dist/algorithm-bridge', name)), readFileSync(path.join(native, variant === 'production' && name === analyst ? 'prd' : '', name))) + assert.deepEqual(readFileSync(path.join(addon, 'dist/algorithm-bridge', name)), readFileSync(path.join(native, variant === 'production' && platform !== 'mac' && name === analyst ? 'prd' : '', name))) } - assert.equal(load(variant === 'test' ? 'production' : 'test').isBuilt(), false) + if (platform === 'mac') assert.throws(() => load('test'), /requires the production algorithm/) + else assert.equal(load(variant === 'test' ? 'production' : 'test').isBuilt(), false) put(path.join(native, platform === 'mac' ? 'libCRYUnitConversion.dylib' : 'libCRYUnitConversion.so'), 'updated prebuilt conversion') assert.equal(load(variant).isBuilt(), false) }) @@ -348,3 +352,28 @@ test('missing prebuilt algorithms fail without a source-build fallback', t => { } }), /prebuilt native algorithm input.*libfront-algorithm/) assert.throws(() => preparePosixNative({ nativePlatform: 'linux-amd64', mode: 'test', backendNative: native }, path.join(root, 'stage')), /算法预编译材料.*libfront-algorithm/) }) + + +test('macOS packaging rejects non-production modes before staging and requires a nonempty root license', t => { + const root = fixture(t) + const { native, target } = nativeMaterials(root, 'mac') + let attempt = 0 + const prepare = mode => preparePosixNative({ nativePlatform: target.nativePlatform, mode, backendNative: native, backendNativeOverrides: native }, + path.join(root, `stage-license-${attempt++}`)) + for (const mode of ['test', undefined, 'invalid']) { + assert.throws(() => prepare(mode), /macOS application runtime requires the production algorithm/) + } + const license = path.join(native, 'License.dat') + rmSync(license) + assert.throws(() => prepare('production'), /license\.dat/i) + put(license, '') + assert.throws(() => prepare('production'), /license\.dat/i) + rmSync(license) + mkdirSync(license) + assert.throws(() => prepare('production'), /license\.dat/i) + rmSync(license, { recursive: true }) + put(license, 'production license') + const result = prepare('production') + assert.equal(readFileSync(path.join(result.backendNative, 'License.dat'), 'utf8'), 'production license') + assert.equal(existsSync(path.join(result.backendNative, 'prd')), false) +}) diff --git a/tools/__tests__/test_verify_macos_native.py b/tools/__tests__/test_verify_macos_native.py new file mode 100644 index 00000000..9f7dc41c --- /dev/null +++ b/tools/__tests__/test_verify_macos_native.py @@ -0,0 +1,59 @@ +"""Regression checks for JNI declaration discovery; requires the configured JDK.""" +import importlib.util +from pathlib import Path +import tempfile +import unittest + + +spec = importlib.util.spec_from_file_location( + 'verify_macos_native', Path(__file__).resolve().parents[1] / 'verify-macos-native.py') +verifier = importlib.util.module_from_spec(spec) +spec.loader.exec_module(verifier) + + +class JniHeaderGenerationTest(unittest.TestCase): + def test_javac_handles_multiline_generics_arrays_overloads_and_underscores(self): + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + sources = root / 'apps/backend/fixture' + sources.mkdir(parents=True) + (sources / 'AlgorithmLibJNIBridge.java').write_text(''' + package com.opentest.core.jni; + public class AlgorithmLibJNIBridge { public native int initialize(); } + ''') + (sources / 'Thing_BridgeJNIBridge.java').write_text(''' + package demo_pkg; + public class Thing_BridgeJNIBridge { + public native T + echo(T value); + public native void under_score(); + public native void invoke(int[] values); + public native void invoke(String[] values); + } + ''') + output = root / 'output' + output.mkdir() + actual, algorithm, _ = verifier.generate_jni_headers(root, '.', output) + self.assertEqual(actual, { + 'Java_com_opentest_core_jni_AlgorithmLibJNIBridge_initialize', + 'Java_demo_1pkg_Thing_1BridgeJNIBridge_echo', + 'Java_demo_1pkg_Thing_1BridgeJNIBridge_under_1score', + 'Java_demo_1pkg_Thing_1BridgeJNIBridge_invoke___3I', + 'Java_demo_1pkg_Thing_1BridgeJNIBridge_invoke___3Ljava_lang_String_2', + }) + self.assertEqual(algorithm, { + 'Java_com_opentest_core_jni_AlgorithmLibJNIBridge_initialize'}) + + def test_missing_package_reports_the_source_instead_of_a_regex_type_error(self): + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + sources = root / 'apps/backend/fixture' + sources.mkdir(parents=True) + (sources / 'NoPackageJNIBridge.java').write_text( + 'public class NoPackageJNIBridge { public native void run(); }') + with self.assertRaisesRegex(ValueError, r'Missing Java package declaration: .*NoPackageJNIBridge'): + verifier.generate_jni_headers(root, '.', root) + + +if __name__ == '__main__': + unittest.main() diff --git a/tools/package-posix-native.mjs b/tools/package-posix-native.mjs index 33885c08..f6106ca1 100644 --- a/tools/package-posix-native.mjs +++ b/tools/package-posix-native.mjs @@ -9,6 +9,7 @@ const { algorithmLibraries } = require('../apps/desktop/src/config/algorithm-lib export function preparePosixNative(config, stage) { const { nodePlatform } = nativePlatformSettings(config.nativePlatform) if (!['darwin', 'linux'].includes(nodePlatform)) throw new Error(`不支持的 POSIX 材料平台:${config.nativePlatform}`) + if (nodePlatform === 'darwin' && config.mode !== 'production') throw new Error('macOS application runtime requires the production algorithm') const extension = nodePlatform === 'darwin' ? '.dylib' : '.so' const native = path.join(stage, 'native-posix') stageBackendNative(config, native) @@ -21,8 +22,9 @@ export function preparePosixNative(config, stage) { if (!protocol.includes(Buffer.from('Java_com_opentest_core_jni_AudioDevicePluginJNIBridge_prepareManagedRuntime'))) throw new Error(`POSIX JNI 预编译材料过时,缺少 prepareManagedRuntime 受管运行接口:${path.join(native, `libCRYJNIAudioProtocol${extension}`)};请提供匹配当前宿主的运行材料`) for (const name of algorithmLibraries(nodePlatform)) assertFile(path.join(native, name), 'POSIX 算法预编译材料') assertFile(path.join(native, 'OptDevHost'), 'POSIX 设备 Host 预编译材料') - const overrides = path.join(native, 'prd') - if (config.mode === 'production') { + if (nodePlatform === 'darwin') assertFile(path.join(native, 'License.dat'), 'macOS production license') + const overrides = nodePlatform === 'darwin' ? native : path.join(native, 'prd') + if (config.mode === 'production' && nodePlatform !== 'darwin') { mkdirSync(overrides, { recursive: true }) cpSync(path.join(native, `libcry_analyst${extension}`), path.join(overrides, `libcry_analyst${extension}`)) const license = path.join(native, 'License.dat') diff --git a/tools/verify-macos-native.py b/tools/verify-macos-native.py new file mode 100644 index 00000000..0ea4ca92 --- /dev/null +++ b/tools/verify-macos-native.py @@ -0,0 +1,141 @@ +"""Verify the macOS payload and JNI exports using headers generated by javac.""" +import argparse +import ctypes +import hashlib +import json +import os +from pathlib import Path +import re +import subprocess +import tempfile + + +def jdk_tool(name): + home = os.environ.get('JAVA_HOME') + return str(Path(home) / 'bin' / name) if home else name + + +def generate_jni_headers(repo, class_path, output): + sources = [] + for source in sorted((repo / 'apps/backend').rglob('*JNIBridge.java')): + text = source.read_text() + if not re.search(r'\bnative\s+', text): + continue + if not re.search(r'^\s*package\s+[\w.]+\s*;', text, re.MULTILINE): + raise ValueError(f'Missing Java package declaration: {source}') + sources.append(str(source)) + classes = output / 'classes' + headers = output / 'headers' + classes.mkdir() + headers.mkdir() + # javac handles generic/multiline declarations, JNI escaping and overloads. + command = [jdk_tool('javac'), '-proc:none', '-encoding', 'UTF-8', + '-cp', class_path, '-d', str(classes), '-h', str(headers), *sources] + result = subprocess.run(command, text=True, capture_output=True) + if result.returncode: + raise ValueError('JNI header generation failed; build backend classes and provide ' + f'their dependency classpath with --class-path:\n{result.stderr}') + symbols = set() + algorithm_symbols = set() + for header in headers.glob('*.h'): + declared = set(re.findall(r'JNICALL\s+(Java_\w+)\s*\(', header.read_text())) + symbols.update(declared) + if header.stem == 'com_opentest_core_jni_AlgorithmLibJNIBridge': + algorithm_symbols.update(declared) + if not symbols or not algorithm_symbols: + raise ValueError('javac produced no expected JNI declarations') + return symbols, algorithm_symbols, classes + + +def windows_exports(repo, root): + if not root.is_dir(): + raise ValueError(f'Windows payload not found: {root}') + script = """ +import fs from 'node:fs'; +import path from 'node:path'; +import {pathToFileURL} from 'node:url'; +const {readPeExportNames} = await import(pathToFileURL(process.argv[1]).href); +const root = process.argv[2]; +const names = new Set(); +for (const name of fs.readdirSync(root).filter(name => name.endsWith('.dll'))) { + for (const symbol of readPeExportNames(fs.readFileSync(path.join(root, name)))) names.add(symbol); +} +console.log(JSON.stringify([...names])); +""" + return set(json.loads(subprocess.check_output( + ['node', '--input-type=module', '-e', script, + str(repo / 'tools/native-algorithm-bindings.mjs'), str(root)], text=True))) + + +def verify_payload(root): + if (root / 'prd').exists() or list(root.glob('libfftw*')): + raise ValueError('Expected flat production FFTC runtime') + libraries = sorted(root.glob('*.dylib')) + if len(libraries) != 8: + raise ValueError(f'Expected eight core dylibs, found {len(libraries)}') + required = {library.name for library in libraries} | {'OptDevHost', 'License.dat'} + covered = set() + for line in (root / 'SHA256SUMS.txt').read_text().splitlines(): + expected, name = line.split(' ', 1) + relative = Path(name) + if relative.is_absolute() or '..' in relative.parts or name in covered: + raise ValueError('Unsafe or duplicate checksum path: ' + name) + if hashlib.sha256((root / relative).read_bytes()).hexdigest() != expected: + raise ValueError('Checksum mismatch: ' + name) + covered.add(name) + if covered != required: + raise ValueError('Checksums must cover exactly the runtime binaries and License.dat') + info = json.loads((root / 'algorithm-build-info.json').read_text()) + if (info['authorizationVariant'], info['platform'], info['architecture'], info['fftBackend']) != ( + 'production', 'darwin', 'arm64', 'FFTC'): + raise ValueError('Incorrect algorithm variant/platform/FFT metadata') + if hashlib.sha256((root / 'libcry_analyst.dylib').read_bytes()).hexdigest() != info['librarySha256']: + raise ValueError('Algorithm metadata checksum mismatch') + if not (root / 'License.dat').stat().st_size: + raise ValueError('Empty default license') + symbols = set() + for binary in libraries + [root / 'OptDevHost']: + if subprocess.check_output(['lipo', '-archs', str(binary)], text=True).strip() != 'arm64': + raise ValueError('Not ARM64: ' + binary.name) + if re.search(rb'/Users/|/home/|[A-Za-z]:\\Users\\', binary.read_bytes()): + raise ValueError('Developer path in core binary: ' + binary.name) + if binary.suffix == '.dylib': + symbols.update(symbol.removeprefix('_') for symbol in subprocess.check_output( + ['nm', '-gjU', str(binary)], text=True).splitlines()) + ctypes.CDLL(str(binary)) + return symbols + + +def require_exports(expected, actual, platform): + missing = sorted(expected - actual) + if missing: + raise ValueError(f'Missing {platform} JNI exports:\n' + '\n'.join(missing)) + + +def main(): + repo = Path(__file__).resolve().parents[1] + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--native', type=Path, default=repo / 'apps/backend/crydaq-server/src/main/resources/native/macos-arm64') + parser.add_argument('--class-path', required=True, help='Compiled backend classes and dependencies (JDK 21+)') + parser.add_argument('--windows-native', type=Path, help='Also check unchanged Windows algorithm JNI exports') + parser.add_argument('--smoke', action='store_true', help='Run real JVM initialization/default-license checks') + args = parser.parse_args() + root = args.native.resolve() + actual = verify_payload(root) + with tempfile.TemporaryDirectory(prefix='opentest-macos-jni-') as directory: + expected, algorithm, classes = generate_jni_headers(repo, args.class_path, Path(directory)) + require_exports(expected, actual, 'macOS') + print(f'8 ARM64 libraries load; {len(expected)} javac-generated JNI exports match; runtime hashes and path scan pass') + if args.windows_native: + require_exports(algorithm, windows_exports(repo, args.windows_native.resolve()), 'Windows algorithm') + print(f'{len(algorithm)} Windows algorithm JNI exports match (static PE check; not Windows execution)') + if args.smoke: + class_path = str(classes) + os.pathsep + args.class_path + subprocess.run([jdk_tool('javac'), '-proc:none', '-cp', class_path, '-d', str(classes), + str(repo / 'tools/__tests__/fixtures/macos-native/MacJniSmoke.java')], check=True) + subprocess.run([jdk_tool('java'), '-Xcheck:jni', '-cp', class_path, 'MacJniSmoke', + str(root), str(root / 'License.dat'), '--default-license'], check=True) + + +if __name__ == '__main__': + main()