// Copyright 2014-2025 Jesper Larsson
//
// This file is part of Klipspringer, <https://klipspringer.avadeaux.net/>
//
// Klipspringer is free software: you can redistribute it and/or modify it under the terms of the
// GNU General Public License as published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// Klipspringer is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
// even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// General Public License for more details.
//
// You should have received a copy of the GNU General Public License along with Klipspringer. If
// not, see <https://www.gnu.org/licenses/>.

package net.avadeaux.klipspringer.codec;

import java.io.IOException;
import java.nio.ByteBuffer;
import javax.sound.sampled.*;

/** Audio input adapter for reading from a {@link TargetDataLine}. */
public class LineTuner implements Device.Tuner {
    private final TargetDataLine line;
    private final PcmFormat format;
    private final ByteTransfer.ArrayReader lineReader;

    /** Constructs a tuner (input) for the given line. */
    public LineTuner(TargetDataLine line) throws UnsupportedFormatException {
        this.line = line;
        this.format = PcmFormat.of(line.getFormat());
        lineReader = ByteTransfer.ArrayReader.of(line);
    }

    public PcmFormat format() { return format; }

    public boolean read(ByteBuffer buffer) throws IOException {
        return ByteTransfer.read(buffer, lineReader, format.fs());
    }

    public void close() { line.close(); }
}
