Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,7 @@ public static ProcessorPipelineBuilder build(DashboardPipelineContext<FftDashboa
@Override protected void onStart() { frames = new BkResultFrames(run, channel,
context().requireCapability(PlatformYUnitConverter.class)); }
@Override public void onFrame(BkSpectrumProcessor.Frame frame) {
frames.publish(frame.results(), frame.publishedResults(), false, frame.taskTimeMs(), frame.sampleCount(), context()::emit);
frames.publish(frame.results(), frame.publishedResults(), false, frame.taskTimeMs(), frame.sampleCount(), frame.sourceTime(), context()::emit);
}
};
builder.addProcessor("bk-spectrum-" + id, spectrum).addProcessor("bk-spectrum-output-" + id, publication)
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
package com.opentest.plugins.fft.bk;

import java.time.Instant;
import java.util.Arrays;
import java.util.Optional;
import java.util.function.Consumer;
import com.opentest.dashboard.api.frame.ChannelFrame;
import com.opentest.plugins.fft.measurement.FftWindowBuffer;

/** Builds source-clocked complete windows while retaining already weighted overlap samples. */
final class BkFftWindowInput {
Expand All @@ -11,7 +14,7 @@ record Time(long taskOriginSample, double taskRelativeStartSample, double taskRe
Key key() { return new Key(taskOriginSample, taskRelativeStartSample, taskRelativeEndSample, sourceSampleRate); }
}
record Key(long taskOriginSample, double startSample, double endSample, double sourceSampleRate) { }
record Window(double[] rawSamples, double[] weightedSamples, Time time) {
record Window(double[] rawSamples, double[] weightedSamples, Time time, Optional<Instant> sourceTime) {
double[] nativeInput(int hopLength, boolean completeWindow) {
int offset = completeWindow ? 0 : weightedSamples.length - hopLength;
return Arrays.copyOfRange(weightedSamples, offset, weightedSamples.length);
Expand Down Expand Up @@ -65,7 +68,7 @@ void accept(ChannelFrame frame, double[] raw, double[] weighted, Runnable discon
offset += copied;
if (used == rawSamples.length) {
var time = new Time(taskOriginSample, sourceBoundaries[0], sourceBoundaries[rawSamples.length], sourceSampleRate);
try { output.accept(new Window(rawSamples.clone(), weightedSamples.clone(), time)); }
try { output.accept(new Window(rawSamples.clone(), weightedSamples.clone(), time, FftWindowBuffer.sourceTimeAtBoundary(frame, offset))); }
finally {
used = rawSamples.length - hopLength;
System.arraycopy(rawSamples, hopLength, rawSamples, 0, used);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,11 @@ public BkResultFrames(DashboardPipelineContext<FftDashboardConfig,?> run, Channe

public void publish(Map<String,BkFftResults.Result> values, Set<String> planned, boolean paired,
double taskTimeMs, int sampleCount, Consumer<ResultFrame> output) {
publish(values, planned, paired, taskTimeMs, sampleCount, Optional.empty(), output);
}

public void publish(Map<String,BkFftResults.Result> values, Set<String> planned, boolean paired,
double taskTimeMs, int sampleCount, Optional<Instant> sourceTime, Consumer<ResultFrame> output) {
if (values.isEmpty()) return;
Instant publication = Instant.now();
var emitted = new HashSet<String>();
Expand Down Expand Up @@ -107,13 +112,15 @@ else if (custom) y = FftCustomUnits.linearValues(code,
value == null ? new double[0] : value.x().clone(), y, taskTimeMs, frameStep, rms);
ResultFrame targeted = FftResultFrames.target(original, requirement.dashboardResultId());
ResultFrame published;
try { published = targeted.withOutputMetadata(new ResultOutputMetadata(true, outputStep, Optional.of(publication))
boolean sourceTimed = "FFT Spectrogram".equals(code) && sourceTime.isPresent();
try { published = targeted.withOutputMetadata(new ResultOutputMetadata(!sourceTimed, outputStep,
sourceTimed ? Optional.empty() : Optional.of(publication))
.withPersistedIndexSampleCount((long) Math.max(1, sampleCount))); }
finally { targeted.release(); }
if (custom) published = FftCustomUnits.mark(published, FftCustomUnits.unit(code, declaration.unitX(),
FftCustomUnits.custom(channel) ? channel.waveformUnit() : "FS",
FftCustomUnits.custom(reference) ? reference.waveformUnit() : "FS").resultUnitIdentityY());
output.accept(published);
output.accept(sourceTimed ? FftResultFrames.stampSourceTime(published, sourceTime) : published);
} catch (UnitConversionException unavailable) {
// One unavailable Math/display variant does not suppress other selected results.
if (!channel.legacyMathSamples() && !custom) throw unavailable;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package com.opentest.plugins.fft.bk;

import java.time.Instant;
import java.util.Optional;
import java.util.Collection;
import java.util.List;
import java.util.Map;
Expand All @@ -19,7 +21,7 @@

/** Stateful BK tasks consume filtered advances, without repeating overlapping samples. */
public final class BkSpectrumProcessor extends Processor<ChannelFrame, BkSpectrumProcessor.Frame> {
public record Frame(Map<String, BkFftResults.Result> results, Set<String> publishedResults, double taskTimeMs, int sampleCount) { }
public record Frame(Map<String, BkFftResults.Result> results, Set<String> publishedResults, double taskTimeMs, int sampleCount, Optional<Instant> sourceTime) { }

private final FftParameters config;
private final ChannelMetadata channel;
Expand Down Expand Up @@ -60,7 +62,7 @@ private void calculate(BkFftWindowInput.Window window) {
var completed = tasks.push(samples, readWeighting, Boolean.TRUE.equals(config.fftRmsEnable()));
nativePrimed = completed.accepted();
if (!completed.publishedResults().isEmpty())
context().emit(new Frame(completed.results(), completed.publishedResults(), window.time().taskTimeMs(), completed.sampleCount()));
context().emit(new Frame(completed.results(), completed.publishedResults(), window.time().taskTimeMs(), completed.sampleCount(), window.sourceTime()));
}

private void resetNative() {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package com.opentest.plugins.fft.measurement;

import java.time.Instant;
import java.util.List;
import java.util.Optional;
import java.util.Objects;
import java.util.function.Consumer;
import com.opentest.dashboard.api.capability.UnitConversionException;
Expand Down Expand Up @@ -38,6 +40,12 @@ public static Consumer<ResultFrame> indexedOutput(long sampleCount, Consumer<Res
};
}

public static ResultFrame stampSourceTime(ResultFrame frame, Optional<Instant> sourceTime) {
if (sourceTime.isEmpty()) return frame;
try { return frame.withSourceTimestamp(sourceTime); }
finally { frame.release(); }
}

public static ResultFrame target(ResultFrame frame, Long dashboardResultId) {
if (dashboardResultId == null || dashboardResultId <= 0)
throw new IllegalArgumentException("FFT output requires a persisted dashboardResultId");
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package com.opentest.plugins.fft.measurement;

import java.time.Instant;
import java.util.Optional;
import java.util.function.BiConsumer;
import com.opentest.dashboard.api.frame.ChannelFrame;

Expand All @@ -20,7 +22,25 @@ public FftWindowBuffer(int length, double overlap) {
public int length() { return samples.length; }
public int hop() { return hop; }

public static Optional<Instant> sourceTimeAtBoundary(ChannelFrame frame, int offset) {
if (frame.sourceSampleRate() <= 0D || frame.samples().length == 0) return Optional.empty();
long span = Math.subtractExact(frame.sourceRange().endSampleExclusive(), frame.sourceRange().startSampleInclusive());
long nanos = Math.round(span * (double) offset / frame.samples().length
/ frame.sourceSampleRate() * 1_000_000_000D);
return frame.sourceTimestamp().filter(timestamp -> timestamp.isAfter(Instant.EPOCH))
.map(timestamp -> timestamp.plusNanos(nanos));
}

@FunctionalInterface
public interface TimedWindowConsumer {
void accept(double[] samples, double taskTimeMs, Optional<Instant> sourceTime);
}

public void accept(ChannelFrame frame, BiConsumer<double[], Double> consumer) {
accept(frame, (samples, time, sourceTime) -> consumer.accept(samples, time));
}

public void accept(ChannelFrame frame, TimedWindowConsumer consumer) {
if (origin != null && (origin != frame.taskOriginSample() || sourceRate != frame.sourceSampleRate()))
throw new IllegalArgumentException("FFT source time axis changed during execution");
if (origin != null && previousEnd != frame.sourceRange().startSampleInclusive()) used = 0;
Expand All @@ -34,7 +54,7 @@ public void accept(ChannelFrame frame, BiConsumer<double[], Double> consumer) {
double end = frame.sourceRange().startSampleInclusive()
+ (frame.sourceRange().endSampleExclusive() - frame.sourceRange().startSampleInclusive())
* (double) offset / frame.samples().length;
try { consumer.accept(samples.clone(), (end - origin) * 1000D / sourceRate); }
try { consumer.accept(samples.clone(), (end - origin) * 1000D / sourceRate, sourceTimeAtBoundary(frame, offset)); }
finally {
used = samples.length - hop;
System.arraycopy(samples, hop, samples, 0, used);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
package com.opentest.plugins.fft.spectrum;

import java.time.Instant;
import java.util.Optional;

import com.opentest.algorithm.api.AlgorithmService;
import com.opentest.algorithm.api.OrdinaryFftOptions;
import com.opentest.dashboard.api.channel.ChannelMetadata;
Expand Down Expand Up @@ -49,7 +52,7 @@ public FftSpectrumProcessor(DashboardPipelineContext<FftDashboardConfig, FftRunP
@Override protected void onStart() { accumulator.start(); }
@Override public void close() { accumulator.close(); }

private void calculate(double[] samples, double time) {
private void calculate(double[] samples, double time, Optional<Instant> sourceTime) {
if (!"AUTO".equals(config.timeMode()) && config.splitNum() != null && accumulator.count() >= config.splitNum()) return;
var calculated = algorithms.calculateFft(weighting.apply(samples), options);
if (calculated.isEmpty()) return;
Expand All @@ -65,7 +68,8 @@ private void calculate(double[] samples, double time) {
var output = FftResultFrames.indexedOutput(sampleCount, context()::emit);
double step = windows.hop() * 1000D / channel.sampleRate();
results.spectrum("FFT Spectrum", "FS", x, current.spectrum(), time, step, output);
results.spectrum("FFT Spectrogram", "FS", x, spectrogram, time, step, output);
results.spectrum("FFT Spectrogram", "FS", x, spectrogram, time, step,
frame -> output.accept(FftResultFrames.stampSourceTime(frame, sourceTime)));
results.spectrum("Amplitude Spectral Density", "dBFS/√(Hz)", x, current.amplitudeSpectralDensity(), time, step, output);
results.spectrum("Power Spectral Density", "dB(FS²/Hz)", x, current.powerSpectralDensity(), time, step, output);
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
package com.opentest.plugins.fft.measurement;

import com.fasterxml.jackson.databind.ObjectMapper;
import java.time.Instant;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
Expand Down Expand Up @@ -86,6 +88,29 @@ void explicitAndSharedOperandFilesBindToTheirFrozenOwners(ExecutionInputPurpose
fixture.rejectUnrelatedTargets();
}

@Test void spectrogramUsesTheSourceClockWhileSpectrumRetainsPublicationTime() {
var fixture = new Fixture("BASEBAND_PRECISION", ExecutionInputPurpose.CAPTURE_STREAM, false, SignalType.AUDIO, false);
fixture.add("FFT Spectrogram", null);
fixture.add("FFT Spectrum", null);
var stamp = Instant.ofEpochSecond(1_794_312_000L, 123_000_001L);
var results = new BkFftResults.Result(new double[]{100, 200}, new double[]{.25, .5}, null, 0);
var values = Map.of("FFT Spectrogram", results, "FFT Spectrum", results);
var observed = new HashMap<String, Optional<Instant>>();
new BkResultFrames(fixture.run(), fixture.channel).publish(values, values.keySet(), false, 50, 2400,
Optional.of(stamp), frame -> {
try {
observed.put(frame.resultCode(), frame.sourceTimestamp());
if ("FFT Spectrogram".equals(frame.resultCode())) {
assertFalse(frame.outputMetadata().omitRealtimeTaskRelativeTime());
assertTrue(frame.outputMetadata().publicationTimestamp().isEmpty());
} else {
assertTrue(frame.outputMetadata().publicationTimestamp().isPresent());
}
} finally { frame.release(); }
});
assertEquals(Map.of("FFT Spectrogram", Optional.of(stamp), "FFT Spectrum", Optional.empty()), observed);
}

@Test void rawPairedFramesWithoutGraphicsAreAlsoDeclared() {
var fixture = new Fixture("BASEBAND_PRECISION", ExecutionInputPurpose.CAPTURE_STREAM, false, SignalType.AUDIO, false);
fixture.add("Auto Spectrum", null);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ function setup(history = false) {
const graphConfigRef = ref({ edit: vi.fn().mockResolvedValue({ affectedGraphicConfigIds: ['graphic-1', 'graphic-2'] }) })
const hook = useGraphicOperation({ graphConfigRef, requestId: ref(history ? 'saved-1' : null), dashboardId: ref('dashboard-1'),
refreshPage, refreshSingleGraphicFromList, updateSingleGraphicConfig: vi.fn(), deleteGraphicConfig: vi.fn() })
return { hook, refreshPage, refreshSingleGraphicFromList }
return { hook, refreshPage, refreshSingleGraphicFromList, edit: graphConfigRef.value.edit }
}

it('refreshes the current workspace after a Y-axis save reports associated graphics', async () => {
Expand Down Expand Up @@ -50,3 +50,12 @@ it('forwards the actual workspace context through its runtime lock guard', () =>
locked.value = true; handle(config, true, context)
expect(base).toHaveBeenCalledOnce()
})


it('forwards the mounted chart context to the managed settings editor', async () => {
const value = setup(true)
const config = { id: 'graphic-1', graphicType: 7 }
const chartInstance = { timeOriginNs: 1795071049939000000n }
await value.hook.handleEditGraphic(config, chartInstance)
expect(value.edit).toHaveBeenCalledWith(7, { config, chartInstance })
})
Original file line number Diff line number Diff line change
Expand Up @@ -35,10 +35,10 @@ export default function useGraphicOperation({
/**
* 编辑图谱
*/
const handleEditGraphic = async config => {
const handleEditGraphic = async (config, chartInstance = undefined) => {
if (!graphConfigRef.value) return
try {
const result = await graphConfigRef.value.edit(config.graphicType, { config }) as GraphicEditResult | null
const result = await graphConfigRef.value.edit(config.graphicType, { config, ...(chartInstance ? { chartInstance } : {}) }) as GraphicEditResult | null
const recalculationTaskId = typeof result?.recalculationTaskId === 'string'
? result.recalculationTaskId.trim()
: ''
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,7 @@
:recalculating="isGraphicRecalculating(waveFormGraphicConfig.config)"
:download-btns="getDownloadOptions(waveFormGraphicConfig.config, isExecuting || isRuntimeLocked)"
@download="handleExport"
@config="handleEditGraphic(waveFormGraphicConfig.config)"
@config="(config, chartInstance) => handleEditGraphic(config || waveFormGraphicConfig.config, chartInstance)"
@config-changed="
(config, needUpdate, context) => handleConfigChanged(config || waveFormGraphicConfig.config, needUpdate, context)
"
Expand Down Expand Up @@ -150,7 +150,7 @@
:recalculating="isGraphicRecalculating(data.config)"
:download-btns="getDownloadOptions(data.config, isExecuting || isRuntimeLocked)"
@download="handleExport"
@config="handleEditGraphic(data.config)"
@config="(config, chartInstance) => handleEditGraphic(config || data.config, chartInstance)"
@config-changed="(config, needUpdate, context) => handleConfigChanged(config || data.config, needUpdate, context)"
/>
</template>
Expand Down Expand Up @@ -1757,9 +1757,9 @@ const isRuntimeLocked = computed(() => {
return props.runtimeLocked
})

const handleEditGraphic = config => {
const handleEditGraphic = (config, chartInstance = undefined) => {
if (isRuntimeLocked.value) return
return handleBaseEditGraphic(config)
return handleBaseEditGraphic(config, chartInstance)
}

const handleConfigChanged = (config, needUpdate, context?) => {
Expand Down