Skip to content

Commit

Permalink
24-Bit PCM support
Browse files Browse the repository at this point in the history
  • Loading branch information
RaphiMC committed Dec 12, 2024
1 parent d029c22 commit 2f9574a
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 12 deletions.
37 changes: 25 additions & 12 deletions src/main/java/net/raphimc/audiomixer/util/io/SampleInputStream.java
Original file line number Diff line number Diff line change
Expand Up @@ -64,24 +64,25 @@ public void close() throws IOException {
}

public int readSample() throws IOException {
switch (this.audioFormat.getSampleSizeInBits()) {
case 8:
final int b1 = this.read();
if (b1 == -1) throw new EOFException();
return (byte) b1;
case 16:
return this.read16Bit();
case 32:
return this.read32Bit();
default:
throw new UnsupportedOperationException("Unsupported sample size: " + this.audioFormat.getSampleSizeInBits());
}
return switch (this.audioFormat.getSampleSizeInBits()) {
case 8 -> this.read8Bit();
case 16 -> this.read16Bit();
case 24 -> this.read24Bit();
case 32 -> this.read32Bit();
default -> throw new UnsupportedOperationException("Unsupported sample size: " + this.audioFormat.getSampleSizeInBits());
};
}

public AudioFormat getAudioFormat() {
return this.audioFormat;
}

private byte read8Bit() throws IOException {
final int b1 = this.read();
if (b1 == -1) throw new EOFException();
return (byte) b1;
}

private short read16Bit() throws IOException {
final int b1 = this.read();
final int b2 = this.read();
Expand All @@ -93,6 +94,18 @@ private short read16Bit() throws IOException {
}
}

private int read24Bit() throws IOException {
final int b1 = this.read();
final int b2 = this.read();
final int b3 = this.read();
if (b1 == -1 || b2 == -1 || b3 == -1) throw new EOFException();
if (this.audioFormat.isBigEndian()) {
return (b1 << 16) | (b2 << 8) | b3;
} else {
return (b3 << 16) | (b2 << 8) | b1;
}
}

private int read32Bit() throws IOException {
final int b1 = this.read();
final int b2 = this.read();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,9 @@ public void writeSample(final int sample) throws IOException {
case 16:
this.write16Bit(sample);
break;
case 24:
this.write24Bit(sample);
break;
case 32:
this.write32Bit(sample);
break;
Expand All @@ -71,6 +74,18 @@ private void write16Bit(final int sample) throws IOException {
}
}

private void write24Bit(final int sample) throws IOException {
if (this.audioFormat.isBigEndian()) {
this.write((sample >> 16) & 0xFF);
this.write((sample >> 8) & 0xFF);
this.write(sample & 0xFF);
} else {
this.write(sample & 0xFF);
this.write((sample >> 8) & 0xFF);
this.write((sample >> 16) & 0xFF);
}
}

private void write32Bit(final int sample) throws IOException {
if (this.audioFormat.isBigEndian()) {
this.write((sample >> 24) & 0xFF);
Expand Down

0 comments on commit 2f9574a

Please sign in to comment.