JavaSound.java
package sidplay.audio;
import libsidplay.common.CPUClock;
import libsidplay.common.EventScheduler;
import libsidplay.config.IAudioSection;
import javax.sound.sampled.*;
import javax.sound.sampled.Mixer.Info;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import static javax.sound.sampled.AudioSystem.getMixerInfo;
import static javax.sound.sampled.AudioSystem.getSourceDataLine;
public class JavaSound implements AudioDriver {
private AudioConfig cfg;
private AudioFormat audioFormat;
private SourceDataLine dataLine;
private ByteBuffer sampleBuffer;
private boolean warp;
@Override
public boolean supportsWarp() {
return true;
}
@Override
public void setWarp(boolean enabled) {
if (warp == enabled) {
return;
}
warp = enabled;
if (dataLine != null) {
dataLine.stop();
dataLine.flush();
}
}
@Override
public void open(IAudioSection audioSection, String recordingFilename, CPUClock cpuClock, EventScheduler context)
throws IOException, LineUnavailableException, InterruptedException {
open(new AudioConfig(audioSection), getDeviceInfo(audioSection));
}
/**
* Open() may manipulate the audio parameters.
*
* @param cfg audio configuration
* @param info mixer info
* @throws LineUnavailableException line is unavailable
*/
public void open(final AudioConfig cfg, final Info info) throws LineUnavailableException {
warp = false;
this.cfg = cfg;
boolean signed = true;
boolean bigEndian = false;
audioFormat = new AudioFormat(cfg.getFrameRate(), Short.SIZE, cfg.getChannels(), signed, bigEndian);
setAudioDevice(info);
}
public void setAudioDevice(final Info info) throws LineUnavailableException {
try {
// first close the previous dataLine when it is already present
close();
dataLine = getSourceDataLine(audioFormat, info);
dataLine.open(dataLine.getFormat(), cfg.getBufferFrames() * Short.BYTES * cfg.getChannels());
dataLine.start();
// The actual buffer size for the open line may differ from the
// requested buffer size, therefore
cfg.setBufferFrames(dataLine.getBufferSize() / Short.BYTES / cfg.getChannels());
} catch (IllegalArgumentException e) {
// mixer isn't supported? No sound! Hardware-based SIDBuilders can still be used.
System.err.println(e.getMessage());
}
sampleBuffer = ByteBuffer.allocate(cfg.getChunkFrames() * Short.BYTES * cfg.getChannels())
.order(ByteOrder.LITTLE_ENDIAN);
}
@Override
public void write() throws InterruptedException {
if (warp || dataLine == null) {
return;
}
// in pause mode the next call to write continues
if (!dataLine.isActive()) {
dataLine.start();
}
dataLine.write(sampleBuffer.array(), 0, sampleBuffer.position());
}
@Override
public long getPlayedFrames() {
return dataLine == null ? -1 : dataLine.getLongFramePosition();
}
@Override
public int getPlaybackBufferFrames() {
return dataLine == null ? 0 : dataLine.getBufferSize() / (Short.BYTES * cfg.getChannels());
}
/**
* Estimate the length of audio data before we run out.
*
* @return playback time in ms
*/
public int getRemainingPlayTime() {
if (dataLine == null) {
return 0;
}
int bytesPerFrame = dataLine.getFormat().getChannels() * Short.BYTES;
int framesAvailable = dataLine.available() / bytesPerFrame;
int framesTotal = dataLine.getBufferSize() / bytesPerFrame;
int framesNotYetPlayed = Math.max(0, framesTotal - framesAvailable);
return (int) (framesNotYetPlayed * 1000L / dataLine.getFormat().getFrameRate());
}
@Override
public void pause() {
if (dataLine != null && dataLine.isActive()) {
dataLine.stop();
}
}
public void flush() {
if (dataLine != null && dataLine.isOpen()) {
dataLine.flush();
}
}
@Override
public void close() {
if (dataLine == null) {
return;
}
if (dataLine.isActive()) {
if (dataLine.isRunning()) {
dataLine.drain();
}
dataLine.stop();
dataLine.flush();
}
if (dataLine.isOpen()) {
dataLine.close();
}
}
@Override
public ByteBuffer buffer() {
return sampleBuffer;
}
@Override
public boolean isRecording() {
return false;
}
public static Info getDeviceInfo(IAudioSection audioSection) {
List<Info> devices = getDeviceInfos();
return IntStream.range(0, devices.size()).filter(i -> i == audioSection.getDevice()).mapToObj(devices::get)
.findFirst().orElse(null);
}
public static List<Info> getDeviceInfos() {
return Arrays.stream(getMixerInfo()).map(AudioSystem::getMixer)
.filter(mixer -> mixer.isLineSupported(new Line.Info(SourceDataLine.class))).map(Mixer::getMixerInfo)
.collect(Collectors.toList());
}
}