// 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/>.

import java.io.IOException;
import java.nio.ByteBuffer;
import net.avadeaux.klipspringer.codec.*;
import javax.sound.sampled.*;

/** Demonstration of Klipspringer FLAC decoding interface that reads a FLAC file and plays it using
  * the standard Java audio system. Compile and run example:
  * <pre>
  *     javac -cp lib/klipcodec.jar examples/FlacPlayFile.java
  *     java -cp examples:lib/klipcodec.jar --enable-native-access=ALL-UNNAMED -Djava.library.path=lib FlacPlayFile some_audio_file.flac
  * </pre>
  */
public class FlacPlayFile {
    public static void main(String[] args) throws IOException {
        if (args.length != 1) {
            System.err.println("Expecting FLAC file argument");
            System.exit(1);
        }

        FlacDecoder decoder = new FlacDecoder(args[0], new FlacDecoder.Target() {
                private Device.Player player = null;

                public synchronized void metadata(PcmFormat format, long totalSamples) throws IOException {
                    try {
                        SourceDataLine line = AudioSystem.getSourceDataLine(format);
                        player = new LinePlayer(line, false);
                    } catch (LineUnavailableException ex) {
                        throw new IOException(ex);
                    }
                }

                public synchronized boolean write(ByteBuffer data) throws IOException {
                    return player.write(data);
                }

                public void close() throws IOException {
                    if (player != null) {
                        player.drain();
                        player.close();
                    }
                }
            });
        decoder.decodeAll(0);
        decoder.close();
    }
}
