 
 /**
 * @author www.google.com/search AI Mode and
 * Microsoft AI mode (www.bing.com/copilotsearch and
 * www.bing.com/search) and Peter Adolfsson.
 */
 
import javafx.animation.AnimationTimer;
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
import javax.sound.sampled.*;
import java.util.concurrent.atomic.AtomicBoolean;

public class RF_Vision extends Application {

    // Audio configuration: 44.1kHz, 16-bit, Stereo, Signed, Little-Endian
    private static final float SAMPLE_RATE = 44100.0f;
    private static final int BUFFER_SAMPLES = 2048; // Samples per channel per read
    private static final int BYTES_PER_FRAME = 4;   // 2 bytes left + 2 bytes right

    // Pre-allocated buffers to avoid per-frame GC pressure
    private final byte[] rawAudioBuffer = new byte[BUFFER_SAMPLES * BYTES_PER_FRAME];
    private final double[] leftWrite = new double[BUFFER_SAMPLES];
    private final double[] rightWrite = new double[BUFFER_SAMPLES];
    
    // Double-buffered arrays shared with the UI thread
    private volatile double[] leftRead = new double[BUFFER_SAMPLES];
    private volatile double[] rightRead = new double[BUFFER_SAMPLES];

    private final AtomicBoolean syncRequested = new AtomicBoolean(false);
    private volatile boolean running = true;
    private int syncOffset = 0;

    private Canvas canvas;
    private Label statusLabel;

    @Override
    public void start(Stage primaryStage) {
        canvas = new Canvas(800, 600);
        Button syncButton = new Button("Synchronize");
        statusLabel = new Label("Status: Running (Offset: 0)");

        syncButton.setOnAction(e -> syncRequested.set(true));

        HBox controls = new HBox(15, syncButton, statusLabel);
        controls.setPadding(new Insets(10));
        controls.setStyle("-fx-background-color: #1e1e1e;");
        statusLabel.setTextFill(Color.LIGHTGRAY);

        BorderPane root = new BorderPane();
        root.setCenter(canvas);
        root.setBottom(controls);

        // Bind canvas size to window resizing
        canvas.widthProperty().bind(root.widthProperty());
        canvas.heightProperty().bind(root.heightProperty().subtract(controls.heightProperty()));

        Scene scene = new Scene(root, 800, 600);
        primaryStage.setTitle("RF_Vision - Sound Card Signal Plotter");
        primaryStage.setScene(scene);
        primaryStage.setOnCloseRequest(e -> running = false);
        primaryStage.show();

        startAudioThread();
        startRenderLoop();
    }

    private void startAudioThread() {
        Thread audioThread = new Thread(() -> {
            AudioFormat format = new AudioFormat(SAMPLE_RATE, 16, 2, true, false);
            DataLine.Info info = new DataLine.Info(TargetDataLine.class, format);

            try (TargetDataLine line = (TargetDataLine) AudioSystem.getLine(info)) {
                line.open(format, rawAudioBuffer.length * 2);
                line.start();

                while (running) {
                    int bytesRead = line.read(rawAudioBuffer, 0, rawAudioBuffer.length);
                    int samplesRead = bytesRead / BYTES_PER_FRAME;

                    // Decode interleaved 16-bit little-endian stereo PCM
                    for (int i = 0; i < samplesRead; i++) {
                        int byteIdx = i * 4;
                        short leftSample = (short) ((rawAudioBuffer[byteIdx + 1] << 8) | (rawAudioBuffer[byteIdx] & 0xFF));
                        short rightSample = (short) ((rawAudioBuffer[byteIdx + 3] << 8) | (rawAudioBuffer[byteIdx + 2] & 0xFF));

                        // Normalize to [-1.0, 1.0]
                        leftWrite[i] = leftSample / 32768.0;
                        rightWrite[i] = rightSample / 32768.0;
                    }

                    // Swap buffers without allocating new memory
                    double[] tempL = leftRead;
                    double[] tempR = rightRead;
                    leftRead = leftWrite;
                    rightRead = rightWrite;
                    System.arraycopy(tempL, 0, leftWrite, 0, BUFFER_SAMPLES);
                    System.arraycopy(tempR, 0, rightWrite, 0, BUFFER_SAMPLES);
                }
            } catch (LineUnavailableException e) {
                e.printStackTrace();
            }
        }, "Audio-Capture-Thread");

        audioThread.setDaemon(true);
        audioThread.start();
    }

    private void startRenderLoop() {
        GraphicsContext gc = canvas.getGraphicsContext2D();

        AnimationTimer timer = new AnimationTimer() {
            @Override
            public void handle(long now) {
                double width = canvas.getWidth();
                double height = canvas.getHeight();
                if (width <= 0 || height <= 0) return;

                double[] currentLeft = leftRead;
                double[] currentRight = rightRead;

                // O(n) Ramp Detection when Synchronize is pressed
                if (syncRequested.getAndSet(false)) {
                    syncOffset = detectRampStart(currentLeft);
                    statusLabel.setText("Status: Synchronized (Offset: " + syncOffset + ")");
                }

                // Clear background
                gc.setFill(Color.BLACK);
                gc.fillRect(0, 0, width, height);

                // Draw center vertical reference axis (0 amplitude)
                double centerX = width / 2.0;
                gc.setStroke(Color.DARKSLATEGRAY);
                gc.strokeLine(centerX, 0, centerX, height);

                // Plot Right Channel Vertically: Time (Y) -> Amplitude (X)
                gc.setFill(Color.LIMEGREEN);
                int pointsToPlot = BUFFER_SAMPLES - syncOffset;
                double yStep = height / (double) pointsToPlot;

                for (int i = 0; i < pointsToPlot; i++) {
                    int sampleIdx = (syncOffset + i) % BUFFER_SAMPLES;
                    double amplitude = currentRight[sampleIdx];

                    // Map amplitude [-1.0, 1.0] to X, time index to Y
                    double x = centerX + (amplitude * (width * 0.45));
                    double y = i * yStep;

                    // Plot individual point (2x2 pixel dot for visibility)
                    gc.fillRect(x, y, 2, 2);
                }
            }
        };
        timer.start();
    }

    /**
     * Scans the left channel for the largest positive slope (O(n)).
     * Returns the index marking the start of the ramp period.
     */
    private int detectRampStart(double[] leftChannel) {
        double maxSlope = -Double.MAX_VALUE;
        int bestIndex = 0;

        for (int i = 1; i < leftChannel.length; i++) {
            double slope = leftChannel[i] - leftChannel[i - 1];
            if (slope > maxSlope) {
                maxSlope = slope;
                bestIndex = i;
            }
        }
        return bestIndex;
    }

    public static void main(String[] args) {
        launch(args);
    }
}