diff --git a/core/command/CommandTest.java b/core/command/CommandTest.java index ccd806b0..a6ef87a0 100644 --- a/core/command/CommandTest.java +++ b/core/command/CommandTest.java @@ -1,6 +1,7 @@ package com.coloryr.allmusic.server.core.command; import com.coloryr.allmusic.server.core.AllMusic; +import com.coloryr.allmusic.server.core.music.api.APIMain; import com.coloryr.allmusic.server.core.objs.music.SongInfoObj; import com.coloryr.allmusic.server.core.utils.Function; @@ -28,7 +29,21 @@ public class CommandTest extends ACommand { e.printStackTrace(); } } else { - AllMusic.side.sendMessage(sender, "§d[AllMusic3]§2请输入有效的ID"); + AllMusic.side.sendMessage(sender, "§d[AllMusic3]§2正在测试解析" + args[1]); + + new Thread(() -> { + try { + SongInfoObj info = APIMain.getUrlMusic(args[1]); + AllMusic.side.runTask(() -> { + AllMusic.side.sendMessage(sender, "§d[AllMusic3]§2音乐解析类型:" + info.getMediaType() + " 音乐长度:" + info.getLength() / 1000); + }); + } catch (Exception e) { + AllMusic.side.runTask(() -> { + AllMusic.side.sendMessage(sender, "§d[AllMusic3]§2测试解析错误"); + e.printStackTrace(); + }); + } + }).start(); } } } diff --git a/core/decoder/flac/AbstractFlacLowLevelInput.java b/core/decoder/flac/AbstractFlacLowLevelInput.java new file mode 100644 index 00000000..5457b352 --- /dev/null +++ b/core/decoder/flac/AbstractFlacLowLevelInput.java @@ -0,0 +1,308 @@ +/* + * FLAC library (Java) + * Copyright (c) Project Nayuki + * https://www.nayuki.io/page/flac-library-java + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * This program 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 Lesser General Public License for more details. + * You should have received a copy of the GNU Lesser General Public License + * along with this program (see COPYING.txt and COPYING.LESSER.txt). + * If not, see . + */ + +package com.coloryr.allmusic.server.core.decoder.flac; + +import java.io.EOFException; +import java.io.IOException; +import java.util.Arrays; +import java.util.Objects; + +/** + * A basic implementation of most functionality required by FlacLowLevelInpuut. + */ +public abstract class AbstractFlacLowLevelInput implements FlacLowLevelInput { + + /*---- Fields ----*/ + + private static final int RICE_DECODING_TABLE_BITS = 13; // Configurable, must be positive + private static final int RICE_DECODING_TABLE_MASK = (1 << RICE_DECODING_TABLE_BITS) - 1; + private static final byte[][] RICE_DECODING_CONSUMED_TABLES = new byte[31][1 << RICE_DECODING_TABLE_BITS]; + private static final int[][] RICE_DECODING_VALUE_TABLES = new int[31][1 << RICE_DECODING_TABLE_BITS]; + private static final int RICE_DECODING_CHUNK = 4; // Configurable, must be positive, and RICE_DECODING_CHUNK * + private static byte[] CRC8_TABLE = new byte[256]; + private static char[] CRC16_TABLE = new char[256]; + + static { + for (int param = 0; param < RICE_DECODING_CONSUMED_TABLES.length; param++) { + byte[] consumed = RICE_DECODING_CONSUMED_TABLES[param]; + int[] values = RICE_DECODING_VALUE_TABLES[param]; + for (int i = 0; ; i++) { + int numBits = (i >>> param) + 1 + param; + if (numBits > RICE_DECODING_TABLE_BITS) break; + int bits = ((1 << param) | (i & ((1 << param) - 1))); + int shift = RICE_DECODING_TABLE_BITS - numBits; + for (int j = 0; j < (1 << shift); j++) { + consumed[(bits << shift) | j] = (byte) numBits; + values[(bits << shift) | j] = (i >>> 1) ^ -(i & 1); + } + } + if (consumed[0] != 0) throw new AssertionError(); + } + } + + static { + for (int i = 0; i < CRC8_TABLE.length; i++) { + int temp8 = i; + int temp16 = i << 8; + for (int j = 0; j < 8; j++) { + temp8 = (temp8 << 1) ^ ((temp8 >>> 7) * 0x107); + temp16 = (temp16 << 1) ^ ((temp16 >>> 15) * 0x18005); + } + CRC8_TABLE[i] = (byte) temp8; + CRC16_TABLE[i] = (char) temp16; + } + } + + /*---- Constructors ----*/ + + // Data from the underlying stream is first stored into this byte buffer before further processing. + private long byteBufferStartPos; + + /*---- Methods ----*/ + + /*-- Stream position --*/ + private byte[] byteBuffer; + private int byteBufferLen; + private int byteBufferIndex; + // The buffer of next bits to return to a reader. Note that byteBufferIndex is incremented when byte + // values are put into the bit buffer, but they might not have been consumed by the ultimate reader yet. + private long bitBuffer; // Only the bottom bitBufferLen bits are valid; the top bits are garbage. + + /*-- Reading bitwise integers --*/ + private int bitBufferLen; // Always in the range [0, 64]. + // Current state of the CRC calculations. + private int crc8; // Always a uint8 value. + private int crc16; // Always a uint16 value. + private int crcStartIndex; // In the range [0, byteBufferLen], unless byteBufferLen = -1. + + /*-- Reading bytes --*/ + + public AbstractFlacLowLevelInput() { + byteBuffer = new byte[4096]; + positionChanged(0); + } + + public long getPosition() { + return byteBufferStartPos + byteBufferIndex - (bitBufferLen + 7) / 8; + } + + public int getBitPosition() { + return (-bitBufferLen) & 7; + } + + // When a subclass handles seekTo() and didn't throw UnsupportedOperationException, + // it must call this method to flush the buffers of upcoming data. + protected void positionChanged(long pos) { + byteBufferStartPos = pos; + Arrays.fill(byteBuffer, (byte) 0); // Defensive clearing, should have no visible effect outside of debugging + byteBufferLen = 0; + byteBufferIndex = 0; + bitBuffer = 0; // Defensive clearing, should have no visible effect outside of debugging + bitBufferLen = 0; + resetCrcs(); + } + + /*-- CRC calculations --*/ + + // Either returns silently or throws an exception. + private void checkByteAligned() { + if (bitBufferLen % 8 != 0) throw new IllegalStateException("Not at a byte boundary"); + } + + public int readUint(int n) throws IOException { + if (n < 0 || n > 32) throw new IllegalArgumentException(); + while (bitBufferLen < n) { + int b = readUnderlying(); + if (b == -1) throw new EOFException(); + bitBuffer = (bitBuffer << 8) | b; + bitBufferLen += 8; + assert 0 <= bitBufferLen && bitBufferLen <= 64; + } + int result = (int) (bitBuffer >>> (bitBufferLen - n)); + if (n != 32) { + result &= (1 << n) - 1; + assert (result >>> n) == 0; + } + bitBufferLen -= n; + assert 0 <= bitBufferLen && bitBufferLen <= 64; + return result; + } + + public int readSignedInt(int n) throws IOException { + int shift = 32 - n; + return (readUint(n) << shift) >> shift; + } + + public void readRiceSignedInts(int param, long[] result, int start, int end) throws IOException { + if (param < 0 || param > 31) throw new IllegalArgumentException(); + long unaryLimit = 1L << (53 - param); + + byte[] consumeTable = RICE_DECODING_CONSUMED_TABLES[param]; + int[] valueTable = RICE_DECODING_VALUE_TABLES[param]; + while (true) { + middle: + while (start <= end - RICE_DECODING_CHUNK) { + if (bitBufferLen < RICE_DECODING_CHUNK * RICE_DECODING_TABLE_BITS) { + if (byteBufferIndex <= byteBufferLen - 8) { + fillBitBuffer(); + } else break; + } + for (int i = 0; i < RICE_DECODING_CHUNK; i++, start++) { + // Fast decoder + int extractedBits = (int) (bitBuffer >>> (bitBufferLen - RICE_DECODING_TABLE_BITS)) + & RICE_DECODING_TABLE_MASK; + int consumed = consumeTable[extractedBits]; + if (consumed == 0) break middle; + bitBufferLen -= consumed; + result[start] = valueTable[extractedBits]; + } + } + + // Slow decoder + if (start >= end) break; + long val = 0; + while (readUint(1) == 0) { + if (val >= unaryLimit) { + // At this point, the final decoded value would be so large that the result of the + // downstream restoreLpc() calculation would not fit in the output sample's bit depth - + // hence why we stop early and throw an exception. However, this check is conservative + // and doesn't catch all the cases where the post-LPC result wouldn't fit. + throw new DataFormatException("Residual value too large"); + } + val++; + } + val = (val << param) | readUint(param); // Note: Long masking unnecessary because param <= 31 + assert (val >>> 53) == 0; // Must fit a uint53 by design due to unaryLimit + val = (val >>> 1) ^ -(val & 1); // Transform uint53 to int53 according to Rice coding of signed numbers + assert (val >> 52) == 0 || (val >> 52) == -1; // Must fit a signed int53 by design + result[start] = val; + start++; + } + } + + /*-- Miscellaneous --*/ + + // Appends at least 8 bits to the bit buffer, or throws EOFException. + private void fillBitBuffer() throws IOException { + int i = byteBufferIndex; + int n = Math.min((64 - bitBufferLen) >>> 3, byteBufferLen - i); + byte[] b = byteBuffer; + if (n > 0) { + for (int j = 0; j < n; j++, i++) bitBuffer = (bitBuffer << 8) | (b[i] & 0xFF); + bitBufferLen += n << 3; + } else if (bitBufferLen <= 56) { + int temp = readUnderlying(); + if (temp == -1) throw new EOFException(); + bitBuffer = (bitBuffer << 8) | temp; + bitBufferLen += 8; + } + assert 8 <= bitBufferLen && bitBufferLen <= 64; + byteBufferIndex += n; + } + + /*---- Tables of constants ----*/ + + // For Rice decoding + + public int readByte() throws IOException { + checkByteAligned(); + if (bitBufferLen >= 8) return readUint(8); + else { + assert bitBufferLen == 0; + return readUnderlying(); + } + } + + public void readFully(byte[] b) throws IOException { + Objects.requireNonNull(b); + checkByteAligned(); + for (int i = 0; i < b.length; i++) b[i] = (byte) readUint(8); + } + + // Reads a byte from the byte buffer (if available) or from the underlying stream, returning either a uint8 or -1. + private int readUnderlying() throws IOException { + if (byteBufferIndex >= byteBufferLen) { + if (byteBufferLen == -1) return -1; + byteBufferStartPos += byteBufferLen; + updateCrcs(0); + byteBufferLen = readUnderlying(byteBuffer, 0, byteBuffer.length); + crcStartIndex = 0; + if (byteBufferLen <= 0) return -1; + byteBufferIndex = 0; + } + assert byteBufferIndex < byteBufferLen; + int temp = byteBuffer[byteBufferIndex] & 0xFF; + byteBufferIndex++; + return temp; + } + + // Reads up to 'len' bytes from the underlying byte-based input stream into the given array subrange. + // Returns a value in the range [0, len] for a successful read, or -1 if the end of stream was reached. + protected abstract int readUnderlying(byte[] buf, int off, int len) throws IOException; + + public void resetCrcs() { + checkByteAligned(); + crcStartIndex = byteBufferIndex - bitBufferLen / 8; + crc8 = 0; + crc16 = 0; + } + // RICE_DECODING_TABLE_BITS <= 64 + + public int getCrc8() { + checkByteAligned(); + updateCrcs(bitBufferLen / 8); + if ((crc8 >>> 8) != 0) throw new AssertionError(); + return crc8; + } + + // For CRC calculations + + public int getCrc16() { + checkByteAligned(); + updateCrcs(bitBufferLen / 8); + if ((crc16 >>> 16) != 0) throw new AssertionError(); + return crc16; + } + + // Updates the two CRC values with data in byteBuffer[crcStartIndex : byteBufferIndex - unusedTrailingBytes]. + private void updateCrcs(int unusedTrailingBytes) { + int end = byteBufferIndex - unusedTrailingBytes; + for (int i = crcStartIndex; i < end; i++) { + int b = byteBuffer[i] & 0xFF; + crc8 = CRC8_TABLE[crc8 ^ b] & 0xFF; + crc16 = CRC16_TABLE[(crc16 >>> 8) ^ b] ^ ((crc16 & 0xFF) << 8); + assert (crc8 >>> 8) == 0; + assert (crc16 >>> 16) == 0; + } + crcStartIndex = end; + } + + // Note: This class only uses memory and has no native resources. It's not strictly necessary to + // call the implementation of AbstractFlacLowLevelInput.close() here, but it's a good habit anyway. + public void close() throws IOException { + byteBuffer = null; + byteBufferLen = -1; + byteBufferIndex = -1; + bitBuffer = 0; + bitBufferLen = -1; + crc8 = -1; + crc16 = -1; + crcStartIndex = -1; + } + +} diff --git a/core/decoder/flac/ByteArrayFlacInput.java b/core/decoder/flac/ByteArrayFlacInput.java new file mode 100644 index 00000000..e2f4f43a --- /dev/null +++ b/core/decoder/flac/ByteArrayFlacInput.java @@ -0,0 +1,73 @@ +/* + * FLAC library (Java) + * Copyright (c) Project Nayuki + * https://www.nayuki.io/page/flac-library-java + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * This program 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 Lesser General Public License for more details. + * You should have received a copy of the GNU Lesser General Public License + * along with this program (see COPYING.txt and COPYING.LESSER.txt). + * If not, see . + */ + +package com.coloryr.allmusic.server.core.decoder.flac; + +import java.io.IOException; +import java.util.Objects; + +/** + * A FLAC input stream based on a fixed byte array. + */ +public final class ByteArrayFlacInput extends AbstractFlacLowLevelInput { + + /*---- Fields ----*/ + + // The underlying byte array to read from. + private byte[] data; + private int offset; + + /*---- Constructors ----*/ + + public ByteArrayFlacInput(byte[] b) { + super(); + data = Objects.requireNonNull(b); + offset = 0; + } + + /*---- Methods ----*/ + + public long getLength() { + return data.length; + } + + public void seekTo(long pos) { + offset = (int) pos; + positionChanged(pos); + } + + protected int readUnderlying(byte[] buf, int off, int len) { + if (off < 0 || off > buf.length || len < 0 || len > buf.length - off) + throw new ArrayIndexOutOfBoundsException(); + int n = Math.min(data.length - offset, len); + if (n == 0) return -1; + System.arraycopy(data, offset, buf, off, n); + offset += n; + return n; + } + + // Discards data buffers and invalidates this stream. Because this class and its superclass + // only use memory and have no native resources, it's okay to simply let a ByteArrayFlacInput + // be garbage-collected without calling close(). + public void close() throws IOException { + if (data != null) { + data = null; + super.close(); + } + } + +} diff --git a/core/decoder/flac/DataFormatException.java b/core/decoder/flac/DataFormatException.java new file mode 100644 index 00000000..7d36262d --- /dev/null +++ b/core/decoder/flac/DataFormatException.java @@ -0,0 +1,40 @@ +/* + * FLAC library (Java) + * Copyright (c) Project Nayuki + * https://www.nayuki.io/page/flac-library-java + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * This program 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 Lesser General Public License for more details. + * You should have received a copy of the GNU Lesser General Public License + * along with this program (see COPYING.txt and COPYING.LESSER.txt). + * If not, see . + */ + +package com.coloryr.allmusic.server.core.decoder.flac; + +/** + * Thrown when data being read violates the FLAC file format. + */ +@SuppressWarnings("serial") +public class DataFormatException extends RuntimeException { + + /*---- Constructors ----*/ + + public DataFormatException() { + super(); + } + + public DataFormatException(String msg) { + super(msg); + } + + public DataFormatException(String msg, Throwable cause) { + super(msg, cause); + } + +} diff --git a/core/decoder/flac/FlacDecoder.java b/core/decoder/flac/FlacDecoder.java new file mode 100644 index 00000000..51212c58 --- /dev/null +++ b/core/decoder/flac/FlacDecoder.java @@ -0,0 +1,112 @@ +/* + * FLAC library (Java) + * Copyright (c) Project Nayuki + * https://www.nayuki.io/page/flac-library-java + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * This program 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 Lesser General Public License for more details. + * You should have received a copy of the GNU Lesser General Public License + * along with this program (see COPYING.txt and COPYING.LESSER.txt). + * If not, see . + */ + +package com.coloryr.allmusic.server.core.decoder.flac; + +import java.io.BufferedInputStream; +import java.io.IOException; + +/** + * Handles high-level decoding and seeking in FLAC files. Also returns metadata blocks. + * Every object is stateful, not thread-safe, and needs to be closed. Sample usage: + * + *
+ * // Create a decoder
+ * FlacDecoder dec = new FlacDecoder(...);
+ *
+ * // Make the decoder process all metadata blocks internally.
+ * // We could capture the returned data for extra processing.
+ * // We must read all metadata before reading audio data.
+ * while (dec.readAndHandleMetadataBlock() != null);
+ *
+ * // Read audio samples starting from beginning
+ * int[][] samples = (...);
+ * dec.readAudioBlock(samples, ...);
+ * dec.readAudioBlock(samples, ...);
+ * dec.readAudioBlock(samples, ...);
+ *
+ * // Seek to some position and continue reading
+ * dec.seekAndReadAudioBlock(..., samples, ...);
+ * dec.readAudioBlock(samples, ...);
+ * dec.readAudioBlock(samples, ...);
+ *
+ * // Close underlying file stream
+ * dec.close();
+ * 
+ * + * @see FlacLowLevelInput + */ +public final class FlacDecoder implements AutoCloseable { + /*---- Fields ----*/ + public StreamInfo streamInfo; + public SeekTable seekTable; + private FlacLowLevelInput input; + private long metadataEndPos; + + // Constructs a new FLAC decoder to read the given file. + // This immediately reads the basic header but not metadata blocks. + public FlacDecoder(BufferedInputStream stream) { + // Initialize streams + this.input = new SeekableFileFlacInput(stream); + } + + // Reads, handles, and returns the next metadata block. Returns a pair (Integer type, byte[] data) if the + // next metadata block exists, otherwise returns null if the final metadata block was previously read. + // In addition to reading and returning data, this method also updates the internal state + // of this object to reflect the new data seen, and throws exceptions for situations such as + // not starting with a stream info metadata block or encountering duplicates of certain blocks. + public Object readAndHandleMetadataBlock() throws IOException { + if (metadataEndPos != -1) return null; // All metadata already consumed + + // Read entire block + boolean last = input.readUint(1) != 0; + int type = input.readUint(7); + int length = input.readUint(24); + byte[] data = new byte[length]; + input.readFully(data); + + // Handle recognized block + if (type == 0) { + if (streamInfo != null) throw new DataFormatException("Duplicate stream info metadata block"); + streamInfo = new StreamInfo(data); + return streamInfo; + } else { + if (streamInfo == null) throw new DataFormatException("Expected stream info metadata block"); + if (type == 3) { + if (seekTable != null) throw new DataFormatException("Duplicate seek table metadata block"); + seekTable = new SeekTable(data); + return seekTable; + } + } + + if (last) { + metadataEndPos = input.getPosition(); + } + return null; + } + + // Closes the underlying input streams and discards object data. + // This decoder object becomes invalid for any method calls or field usages. + public void close() throws IOException { + if (input != null) { + streamInfo = null; + seekTable = null; + input.close(); + input = null; + } + } +} diff --git a/core/decoder/flac/FlacLowLevelInput.java b/core/decoder/flac/FlacLowLevelInput.java new file mode 100644 index 00000000..9abcf3c4 --- /dev/null +++ b/core/decoder/flac/FlacLowLevelInput.java @@ -0,0 +1,104 @@ +/* + * FLAC library (Java) + * Copyright (c) Project Nayuki + * https://www.nayuki.io/page/flac-library-java + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * This program 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 Lesser General Public License for more details. + * You should have received a copy of the GNU Lesser General Public License + * along with this program (see COPYING.txt and COPYING.LESSER.txt). + * If not, see . + */ + +package com.coloryr.allmusic.server.core.decoder.flac; + +import java.io.IOException; + +/** + * A low-level input stream tailored to the needs of FLAC decoding. An overview of methods includes + * bit reading, CRC calculation, Rice decoding, and positioning and seeking (partly optional). + * + * @see SeekableFileFlacInput + * @see FrameDecoder + */ +public interface FlacLowLevelInput extends AutoCloseable { + + /*---- Stream position ----*/ + + // Returns the total number of bytes in the FLAC file represented by this input stream. + // This number should not change for the lifetime of this object. Implementing this is optional; + // it's intended to support blind seeking without the use of seek tables, such as binary searching + // the whole file. A class may choose to throw UnsupportedOperationException instead, + // such as for a non-seekable network input stream of unknown length. + public long getLength(); + + // Returns the current byte position in the stream, a non-negative value. + // This increments after every 8 bits read, and a partially read byte is treated as unread. + // This value is 0 initially, is set directly by seekTo(), and potentially increases + // after every call to a read*() method. Other methods do not affect this value. + public long getPosition(); + + // Returns the current number of consumed bits in the current byte. This starts at 0, + // increments for each bit consumed, maxes out at 7, then resets to 0 and repeats. + public int getBitPosition(); + + /*---- Reading bitwise integers ----*/ + + // Reads the next given number of bits (0 <= n <= 32) as an unsigned integer (i.e. zero-extended to int32). + // However in the case of n = 32, the result will be a signed integer that represents a uint32. + public int readUint(int n) throws IOException; + + // Reads the next given number of bits (0 <= n <= 32) as an signed integer (i.e. sign-extended to int32). + public int readSignedInt(int n) throws IOException; + + // Reads and decodes the next batch of Rice-coded signed integers. Note that any Rice-coded integer might read a + // large + // number of bits from the underlying stream (but not in practice because it would be a very inefficient encoding). + // Every new value stored into the array is guaranteed to fit into a signed int53 - see FrameDecoder.restoreLpc() + // for an explanation of why this is a necessary (but not sufficient) bound on the range of decoded values. + public void readRiceSignedInts(int param, long[] result, int start, int end) throws IOException; + + /*---- Reading bytes ----*/ + + // Returns the next unsigned byte value (in the range [0, 255]) or -1 for EOF. + // Must be called at a byte boundary (i.e. getBitPosition() == 0), otherwise IllegalStateException is thrown. + public int readByte() throws IOException; + + // Discards any partial bits, then reads the given array fully or throws EOFException. + // Must be called at a byte boundary (i.e. getBitPosition() == 0), otherwise IllegalStateException is thrown. + public void readFully(byte[] b) throws IOException; + + /*---- CRC calculations ----*/ + + // Marks the current byte position as the start of both CRC calculations. + // The effect of resetCrcs() is implied at the beginning of stream and when seekTo() is called. + // Must be called at a byte boundary (i.e. getBitPosition() == 0), otherwise IllegalStateException is thrown. + public void resetCrcs(); + + // Returns the CRC-8 hash of all the bytes read since the most recent time one of these + // events occurred: a call to resetCrcs(), a call to seekTo(), the beginning of stream. + // Must be called at a byte boundary (i.e. getBitPosition() == 0), otherwise IllegalStateException is thrown. + public int getCrc8(); + + // Returns the CRC-16 hash of all the bytes read since the most recent time one of these + // events occurred: a call to resetCrcs(), a call to seekTo(), the beginning of stream. + // Must be called at a byte boundary (i.e. getBitPosition() == 0), otherwise IllegalStateException is thrown. + public int getCrc16(); + + /*---- Miscellaneous ----*/ + + // Closes underlying objects / native resources, and possibly discards memory buffers. + // Generally speaking, this operation invalidates this input stream, so calling methods + // (other than close()) or accessing fields thereafter should be forbidden. + // The close() method must be idempotent and safe when called more than once. + // If an implementation does not have native or time-sensitive resources, it is okay for the class user + // to skip calling close() and simply let the object be garbage-collected. But out of good habit, it is + // recommended to always close a FlacLowLevelInput stream so that the logic works correctly on all types. + public void close() throws IOException; + +} diff --git a/core/decoder/flac/FrameInfo.java b/core/decoder/flac/FrameInfo.java new file mode 100644 index 00000000..53260b63 --- /dev/null +++ b/core/decoder/flac/FrameInfo.java @@ -0,0 +1,288 @@ +/* + * FLAC library (Java) + * Copyright (c) Project Nayuki + * https://www.nayuki.io/page/flac-library-java + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * This program 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 Lesser General Public License for more details. + * You should have received a copy of the GNU Lesser General Public License + * along with this program (see COPYING.txt and COPYING.LESSER.txt). + * If not, see . + */ + +package com.coloryr.allmusic.server.core.decoder.flac; + +import java.io.IOException; + +/** + * Represents most fields in a frame header, in decoded (not raw) form. Mutable structure, + * not thread safe. Also has methods for parsing and serializing this structure to/from bytes. + * All fields can be modified freely when no method call is active. + */ +public final class FrameInfo { + + /*---- Fields ----*/ + + // Exactly one of these following two fields equals -1. + + private static final int[][] BLOCK_SIZE_CODES = {{192, 1}, {576, 2}, {1152, 3}, {2304, 4}, {4608, 5}, + {256, 8}, {512, 9}, {1024, 10}, {2048, 11}, {4096, 12}, {8192, 13}, {16384, 14}, {32768, 15},}; + private static final int[][] SAMPLE_DEPTH_CODES = {{8, 1}, {12, 2}, {16, 4}, {20, 5}, {24, 6},}; + private static final int[][] SAMPLE_RATE_CODES = {{88200, 1}, {176400, 2}, {192000, 3}, {8000, 4}, + {16000, 5}, {22050, 6}, {24000, 7}, {32000, 8}, {44100, 9}, {48000, 10}, {96000, 11},}; + /** + * The index of this frame, where the foremost frame has index 0 and each subsequent frame + * increments it. This is either a uint31 value or −1 if unused. Exactly one of the fields + * frameIndex and sampleOffse is equal to −1 (not both nor neither). This value can only + * be used if the stream info's minBlockSize = maxBlockSize (constant block size encoding style). + */ + public int frameIndex; + /** + * The offset of the first sample in this frame with respect to the beginning of the + * audio stream. This is either a uint36 value or −1 if unused. Exactly one of + * the fields frameIndex and sampleOffse is equal to −1 (not both nor neither). + */ + public long sampleOffset; + /** + * The number of audio channels in this frame, in the range 1 to 8 inclusive. + * This value is fully determined by the channelAssignment field. + */ + public int numChannels; + /** + * The raw channel assignment value of this frame, which is a uint4 value. + * This indicates the number of channels, but also tells the stereo coding mode. + */ + public int channelAssignment; + /** + * The number of samples per channel in this frame, in the range 1 to 65536 inclusive. + */ + public int blockSize; + + /*---- Constructors ----*/ + /** + * The sample rate of this frame in hertz (Hz), in the range 1 to 655360 inclusive, + * or −1 if unavailable (i.e. the stream info should be consulted). + */ + public int sampleRate; + + /*---- Functions to read FrameInfo from stream ----*/ + /** + * The sample depth of this frame in bits, in the range 8 to 24 inclusive, + * or −1 if unavailable (i.e. the stream info should be consulted). + */ + public int sampleDepth; + /** + * The size of this frame in bytes, from the start of the sync sequence to the end + * of the trailing CRC-16 checksum. A valid value is at least 10, or −1 + * if unavailable (e.g. the frame header was parsed but not the entire frame). + */ + public int frameSize; + + /** + * Constructs a blank frame metadata structure, setting all fields to unknown or invalid values. + */ + public FrameInfo() { + frameIndex = -1; + sampleOffset = -1; + numChannels = -1; + channelAssignment = -1; + blockSize = -1; + sampleRate = -1; + sampleDepth = -1; + frameSize = -1; + } + + /** + * Reads the next FLAC frame header from the specified input stream, either returning + * a new frame info object or {@code null}. The stream must be aligned to a byte + * boundary and start at a sync sequence. If EOF is immediately encountered before + * any bytes were read, then this returns {@code null}. + *

+ * Otherwise this reads between 6 to 16 bytes from the stream – starting + * from the sync code, and ending after the CRC-8 value is read (but before reading + * any subframes). It tries to parse the frame header data. After the values are + * successfully decoded, a new frame info object is created, almost all fields are + * set to the parsed values, and it is returned. (This doesn't read to the end + * of the frame, so the frameSize field is set to -1.) + *

+ * + * @param in the input stream to read from (not {@code null}) + * @return a new frame info object or {@code null} + * @throws NullPointerException if the input stream is {@code null} + * @throws DataFormatException if the input data contains invalid values + * @throws IOException if an I/O exception occurred + */ + public static FrameInfo readFrame(FlacLowLevelInput in) throws IOException { + // Preliminaries + in.resetCrcs(); + int temp = in.readByte(); + if (temp == -1) return null; + FrameInfo result = new FrameInfo(); + result.frameSize = -1; + + // Read sync bits + int sync = temp << 6 | in.readUint(6); // Uint14 + if (sync != 0x3FFE) throw new DataFormatException("Sync code expected"); + + // Read various simple fields + if (in.readUint(1) != 0) throw new DataFormatException("Reserved bit"); + int blockStrategy = in.readUint(1); + int blockSizeCode = in.readUint(4); + int sampleRateCode = in.readUint(4); + int chanAsgn = in.readUint(4); + result.channelAssignment = chanAsgn; + if (chanAsgn < 8) result.numChannels = chanAsgn + 1; + else if (8 <= chanAsgn && chanAsgn <= 10) result.numChannels = 2; + else throw new DataFormatException("Reserved channel assignment"); + result.sampleDepth = decodeSampleDepth(in.readUint(3)); + if (in.readUint(1) != 0) throw new DataFormatException("Reserved bit"); + + // Read and check the frame/sample position field + long position = readUtf8Integer(in); // Reads 1 to 7 bytes + if (blockStrategy == 0) { + if ((position >>> 31) != 0) throw new DataFormatException("Frame index too large"); + result.frameIndex = (int) position; + result.sampleOffset = -1; + } else if (blockStrategy == 1) { + result.sampleOffset = position; + result.frameIndex = -1; + } else throw new AssertionError(); + + // Read variable-length data for some fields + result.blockSize = decodeBlockSize(blockSizeCode, in); // Reads 0 to 2 bytes + result.sampleRate = decodeSampleRate(sampleRateCode, in); // Reads 0 to 2 bytes + int computedCrc8 = in.getCrc8(); + if (in.readUint(8) != computedCrc8) throw new DataFormatException("CRC-8 mismatch"); + return result; + } + + // Reads 1 to 7 whole bytes from the input stream. Return value is a uint36. + // See: https://hydrogenaud.io/index.php/topic,112831.msg929128.html#msg929128 + private static long readUtf8Integer(FlacLowLevelInput in) throws IOException { + int head = in.readUint(8); + int n = Integer.numberOfLeadingZeros(~(head << 24)); // Number of leading 1s in the byte + assert 0 <= n && n <= 8; + if (n == 0) return head; + else if (n == 1 || n == 8) throw new DataFormatException("Invalid UTF-8 coded number"); + else { + long result = head & (0x7F >>> n); + for (int i = 0; i < n - 1; i++) { + int temp = in.readUint(8); + if ((temp & 0xC0) != 0x80) throw new DataFormatException("Invalid UTF-8 coded number"); + result = (result << 6) | (temp & 0x3F); + } + if ((result >>> 36) != 0) throw new AssertionError(); + return result; + } + } + + // Argument is a uint4 value. Reads 0 to 2 bytes from the input stream. + // Return value is in the range [1, 65536]. + private static int decodeBlockSize(int code, FlacLowLevelInput in) throws IOException { + if ((code >>> 4) != 0) throw new IllegalArgumentException(); + switch (code) { + case 0: + throw new DataFormatException("Reserved block size"); + case 6: + return in.readUint(8) + 1; + case 7: + return in.readUint(16) + 1; + default: + int result = searchSecond(BLOCK_SIZE_CODES, code); + if (result < 1 || result > 65536) throw new AssertionError(); + return result; + } + } + + // Argument is a uint4 value. Reads 0 to 2 bytes from the input stream. + // Return value is in the range [-1, 655350]. + private static int decodeSampleRate(int code, FlacLowLevelInput in) throws IOException { + if ((code >>> 4) != 0) throw new IllegalArgumentException(); + switch (code) { + case 0: + return -1; // Caller should obtain value from stream info metadata block + case 12: + return in.readUint(8); + case 13: + return in.readUint(16); + case 14: + return in.readUint(16) * 10; + case 15: + throw new DataFormatException("Invalid sample rate"); + default: + int result = searchSecond(SAMPLE_RATE_CODES, code); + if (result < 1 || result > 655350) throw new AssertionError(); + return result; + } + } + + // Argument is a uint3 value. Pure function and performs no I/O. Return value is in the range [-1, 24]. + private static int decodeSampleDepth(int code) { + if ((code >>> 3) != 0) throw new IllegalArgumentException(); + else if (code == 0) return -1; // Caller should obtain value from stream info metadata block + else { + int result = searchSecond(SAMPLE_DEPTH_CODES, code); + if (result == -1) throw new DataFormatException("Reserved bit depth"); + if (result < 1 || result > 32) throw new AssertionError(); + return result; + } + } + + /*---- Tables of constants and search functions ----*/ + + // Returns a uint4 value representing the given block size. Pure function. + private static int getBlockSizeCode(int blockSize) { + int result = searchFirst(BLOCK_SIZE_CODES, blockSize); + if (result != -1) ; // Already done + else if (1 <= blockSize && blockSize <= 256) result = 6; + else if (1 <= blockSize && blockSize <= 65536) result = 7; + else // blockSize < 1 || blockSize > 65536 + throw new IllegalArgumentException(); + + if ((result >>> 4) != 0) throw new AssertionError(); + return result; + } + + // Returns a uint4 value representing the given sample rate. Pure function. + private static int getSampleRateCode(int sampleRate) { + if (sampleRate == 0 || sampleRate < -1) throw new IllegalArgumentException(); + int result = searchFirst(SAMPLE_RATE_CODES, sampleRate); + if (result != -1) ; // Already done + else if (0 <= sampleRate && sampleRate < 256) result = 12; + else if (0 <= sampleRate && sampleRate < 65536) result = 13; + else if (0 <= sampleRate && sampleRate < 655360 && sampleRate % 10 == 0) result = 14; + else result = 0; + + if ((result >>> 4) != 0) throw new AssertionError(); + return result; + } + + // Returns a uint3 value representing the given sample depth. Pure function. + private static int getSampleDepthCode(int sampleDepth) { + if (sampleDepth != -1 && (sampleDepth < 1 || sampleDepth > 32)) throw new IllegalArgumentException(); + int result = searchFirst(SAMPLE_DEPTH_CODES, sampleDepth); + if (result == -1) result = 0; + if ((result >>> 3) != 0) throw new AssertionError(); + return result; + } + + private static final int searchFirst(int[][] table, int key) { + for (int[] pair : table) { + if (pair[0] == key) return pair[1]; + } + return -1; + } + + private static final int searchSecond(int[][] table, int key) { + for (int[] pair : table) { + if (pair[1] == key) return pair[0]; + } + return -1; + } + +} diff --git a/core/decoder/flac/SeekTable.java b/core/decoder/flac/SeekTable.java new file mode 100644 index 00000000..e712ecb5 --- /dev/null +++ b/core/decoder/flac/SeekTable.java @@ -0,0 +1,159 @@ +/* + * FLAC library (Java) + * Copyright (c) Project Nayuki + * https://www.nayuki.io/page/flac-library-java + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * This program 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 Lesser General Public License for more details. + * You should have received a copy of the GNU Lesser General Public License + * along with this program (see COPYING.txt and COPYING.LESSER.txt). + * If not, see . + */ + +package com.coloryr.allmusic.server.core.decoder.flac; + +import java.io.ByteArrayInputStream; +import java.io.DataInput; +import java.io.DataInputStream; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; + +/** + * Represents precisely all the fields of a seek table metadata block. Mutable structure, + * not thread-safe. Also has methods for parsing and serializing this structure to/from bytes. + * All fields and objects can be modified freely when no method call is active. + * + * @see FlacDecoder + */ +public final class SeekTable { + + /*---- Fields ----*/ + + /** + * The list of seek points in this seek table. It is okay to replace this + * list as needed (the initially constructed list object is not special). + */ + public List points; + + /*---- Constructors ----*/ + + /** + * Constructs a blank seek table with an initially empty + * list of seek points. (Note that the empty state is legal.) + */ + public SeekTable() { + points = new ArrayList<>(); + } + + /** + * Constructs a seek table by parsing the given byte array representing the metadata block. + * (The array must contain only the metadata payload, without the type or length fields.) + *

+ * This constructor does not check the validity of the seek points, namely the ordering + * of seek point offsets, so calling {@link#checkValues()} on the freshly constructed object + * can fail. However, this does guarantee that every point's frameSamples field is a uint16. + *

+ * + * @param b the metadata block's payload data to parse (not {@code null}) + * @throws NullPointerException if the array is {@code null} + * @throws IllegalArgumentException if the array length + * is not a multiple of 18 (size of each seek point) + */ + public SeekTable(byte[] b) { + this(); + Objects.requireNonNull(b); + if (b.length % 18 != 0) throw new IllegalArgumentException("Data contains a partial seek point"); + try { + DataInput in = new DataInputStream(new ByteArrayInputStream(b)); + for (int i = 0; i < b.length; i += 18) { + SeekPoint p = new SeekPoint(); + p.sampleOffset = in.readLong(); + p.fileOffset = in.readLong(); + p.frameSamples = in.readUnsignedShort(); + points.add(p); + } + // Skip closing the in-memory streams + } catch (IOException e) { + throw new AssertionError(e); + } + } + + /*---- Methods ----*/ + + /** + * Checks the state of this object and returns silently if all these criteria pass: + *
    + *
  • No object is {@code null}
  • + *
  • The frameSamples field of each point is a uint16 value
  • + *
  • All points with sampleOffset = −1 (i.e. 0xFFF...FFF) are at the end of the list
  • + *
  • All points with sampleOffset ≠ −1 have strictly increasing + * values of sampleOffset and non-decreasing values of fileOffset
  • + *
+ * + * @throws NullPointerException if the list or an element is {@code null} + * @throws IllegalStateException if the current list of seek points is contains invalid data + */ + public void checkValues() { + // Check list and each point + Objects.requireNonNull(points); + for (SeekPoint p : points) { + Objects.requireNonNull(p); + if ((p.frameSamples & 0xFFFF) != p.frameSamples) + throw new IllegalStateException("Frame samples outside uint16 range"); + } + + // Check ordering of points + for (int i = 1; i < points.size(); i++) { + SeekPoint p = points.get(i); + if (p.sampleOffset != -1) { + SeekPoint q = points.get(i - 1); + if (p.sampleOffset <= q.sampleOffset) throw new IllegalStateException("Sample offsets out of order"); + if (p.fileOffset < q.fileOffset) throw new IllegalStateException("File offsets out of order"); + } + } + } + + /*---- Helper structure ----*/ + + /** + * Represents a seek point entry in a seek table. Mutable structure, not thread-safe. + * This class itself does not check the correctness of data, but other classes might. + *

+ * A seek point with data (sampleOffset = x, fileOffset = y, frameSamples = z) means + * that at byte position (y + (byte offset of foremost audio frame)) in the file, + * a FLAC frame begins (with the sync sequence), that frame has sample offset x + * (where sample 0 is defined as the start of the audio stream), + * and the frame contains z samples per channel. + * + * @see SeekTable + */ + public static final class SeekPoint { + + /** + * The sample offset in the audio stream, a uint64 value. + * A value of -1 (i.e. 0xFFF...FFF) means this is a placeholder point. + */ + public long sampleOffset; + + /** + * The byte offset relative to the start of the foremost frame, a uint64 value. + * If sampleOffset is -1, then this value is ignored. + */ + public long fileOffset; + + /** + * The number of audio samples in the target block/frame, a uint16 value. + * If sampleOffset is -1, then this value is ignored. + */ + public int frameSamples; + + } + +} diff --git a/core/decoder/flac/SeekableFileFlacInput.java b/core/decoder/flac/SeekableFileFlacInput.java new file mode 100644 index 00000000..7841971c --- /dev/null +++ b/core/decoder/flac/SeekableFileFlacInput.java @@ -0,0 +1,63 @@ +/* + * FLAC library (Java) + * Copyright (c) Project Nayuki + * https://www.nayuki.io/page/flac-library-java + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * This program 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 Lesser General Public License for more details. + * You should have received a copy of the GNU Lesser General Public License + * along with this program (see COPYING.txt and COPYING.LESSER.txt). + * If not, see . + */ + +package com.coloryr.allmusic.server.core.decoder.flac; + +import java.io.BufferedInputStream; +import java.io.IOException; +import java.io.RandomAccessFile; + +/** + * A FLAC input stream based on a {@link RandomAccessFile}. + */ +public final class SeekableFileFlacInput extends AbstractFlacLowLevelInput { + + /*---- Fields ----*/ + + // The underlying byte-based input stream to read from. + private BufferedInputStream raf; + + /*---- Constructors ----*/ + + public SeekableFileFlacInput(BufferedInputStream stream) { + super(); + this.raf = stream; + } + + /*---- Methods ----*/ + + public long getLength() { + try { + return raf.available(); + } catch (IOException e) { + throw new RuntimeException(e); + } + } + + protected int readUnderlying(byte[] buf, int off, int len) throws IOException { + return raf.read(buf, off, len); + } + + // Closes the underlying RandomAccessFile stream (very important). + public void close() throws IOException { + if (raf != null) { + raf.close(); + raf = null; + super.close(); + } + } +} diff --git a/core/decoder/flac/StreamInfo.java b/core/decoder/flac/StreamInfo.java new file mode 100644 index 00000000..73ddc82f --- /dev/null +++ b/core/decoder/flac/StreamInfo.java @@ -0,0 +1,243 @@ +/* + * FLAC library (Java) + * Copyright (c) Project Nayuki + * https://www.nayuki.io/page/flac-library-java + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * This program 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 Lesser General Public License for more details. + * You should have received a copy of the GNU Lesser General Public License + * along with this program (see COPYING.txt and COPYING.LESSER.txt). + * If not, see . + */ + +package com.coloryr.allmusic.server.core.decoder.flac; + +import java.io.IOException; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.Objects; + +/** + * Represents precisely all the fields of a stream info metadata block. Mutable structure, + * not thread-safe. Also has methods for parsing and serializing this structure to/from bytes. + * All fields can be modified freely when no method call is active. + * + * @see FrameInfo + * @see FlacDecoder + */ +public final class StreamInfo { + + /*---- Fields about block and frame sizes ----*/ + + /** + * Minimum block size (in samples per channel) among the whole stream, a uint16 value. + * However when minBlockSize = maxBlockSize (constant block size encoding style), + * the final block is allowed to be smaller than minBlockSize. + */ + public int minBlockSize; + + /** + * Maximum block size (in samples per channel) among the whole stream, a uint16 value. + */ + public int maxBlockSize; + + /** + * Minimum frame size (in bytes) among the whole stream, a uint24 value. + * However, a value of 0 signifies that the value is unknown. + */ + public int minFrameSize; + + /** + * Maximum frame size (in bytes) among the whole stream, a uint24 value. + * However, a value of 0 signifies that the value is unknown. + */ + public int maxFrameSize; + + /*---- Fields about stream properties ----*/ + + /** + * The sample rate of the audio stream (in hertz (Hz)), a positive uint20 value. + * Note that 0 is an invalid value. + */ + public int sampleRate; + + /** + * The number of channels in the audio stream, between 1 and 8 inclusive. + * 1 means mono, 2 means stereo, et cetera. + */ + public int numChannels; + + /** + * The bits per sample in the audio stream, in the range 4 to 32 inclusive. + */ + public int sampleDepth; + + /** + * The total number of samples per channel in the whole stream, a uint36 value. + * The special value of 0 signifies that the value is unknown (not empty zero-length stream). + */ + public long numSamples; + + /** + * The 16-byte MD5 hash of the raw uncompressed audio data serialized in little endian with + * channel interleaving (not planar). It can be all zeros to signify that the hash was not computed. + * It is okay to replace this array as needed (the initially constructed array object is not special). + */ + public byte[] md5Hash; + + /*---- Constructors ----*/ + + /** + * Constructs a blank stream info structure with certain default values. + */ + public StreamInfo() { + // Set these fields to legal unknown values + minFrameSize = 0; + maxFrameSize = 0; + numSamples = 0; + md5Hash = new byte[16]; + + // Set these fields to invalid (not reserved) values + minBlockSize = 0; + maxBlockSize = 0; + sampleRate = 0; + } + + /** + * Constructs a stream info structure by parsing the specified 34-byte metadata block. + * (The array must contain only the metadata payload, without the type or length fields.) + * + * @param b the metadata block's payload data to parse (not {@code null}) + * @throws NullPointerException if the array is {@code null} + * @throws IllegalArgumentException if the array length is not 34 + * @throws DataFormatException if the data contains invalid values + */ + public StreamInfo(byte[] b) { + Objects.requireNonNull(b); + if (b.length != 34) throw new IllegalArgumentException("Invalid data length"); + try { + FlacLowLevelInput in = new ByteArrayFlacInput(b); + minBlockSize = in.readUint(16); + maxBlockSize = in.readUint(16); + minFrameSize = in.readUint(24); + maxFrameSize = in.readUint(24); + if (minBlockSize < 16) throw new DataFormatException("Minimum block size less than 16"); + if (maxBlockSize > 65535) throw new DataFormatException("Maximum block size greater than 65535"); + if (maxBlockSize < minBlockSize) + throw new DataFormatException("Maximum block size less than minimum block size"); + if (minFrameSize != 0 && maxFrameSize != 0 && maxFrameSize < minFrameSize) + throw new DataFormatException("Maximum frame size less than minimum frame size"); + sampleRate = in.readUint(20); + if (sampleRate == 0 || sampleRate > 655350) throw new DataFormatException("Invalid sample rate"); + numChannels = in.readUint(3) + 1; + sampleDepth = in.readUint(5) + 1; + numSamples = (long) in.readUint(18) << 18 | in.readUint(18); // uint36 + md5Hash = new byte[16]; + in.readFully(md5Hash); + // Skip closing the in-memory stream + } catch (IOException e) { + throw new AssertionError(e); + } + } + + /*---- Methods ----*/ + + /** + * Computes and returns the MD5 hash of the specified raw audio sample data at the specified + * bit depth. Currently, the bit depth must be a multiple of 8, between 8 and 32 inclusive. + * The returned array is a new object of length 16. + * + * @param samples the audio samples to hash, where + * each subarray is a channel (all not {@code null}) + * @param depth the bit depth of the audio samples + * (i.e. each sample value is a signed 'depth'-bit integer) + * @return a new 16-byte array representing the MD5 hash of the audio data + * @throws NullPointerException if the array or any subarray is {@code null} + * @throws IllegalArgumentException if the bit depth is unsupported + */ + public static byte[] getMd5Hash(int[][] samples, int depth) { + // Check arguments + Objects.requireNonNull(samples); + for (int[] chanSamples : samples) Objects.requireNonNull(chanSamples); + if (depth < 0 || depth > 32 || depth % 8 != 0) throw new IllegalArgumentException("Unsupported bit depth"); + + // Create hasher + MessageDigest hasher; + try { // Guaranteed available by the Java Cryptography Architecture + hasher = MessageDigest.getInstance("MD5"); + } catch (NoSuchAlgorithmException e) { + throw new AssertionError(e); + } + + // Convert samples to a stream of bytes, compute hash + int numChannels = samples.length; + int numSamples = samples[0].length; + int numBytes = depth / 8; + byte[] buf = new byte[numChannels * numBytes * Math.min(numSamples, 2048)]; + for (int i = 0, l = 0; i < numSamples; i++) { + for (int j = 0; j < numChannels; j++) { + int val = samples[j][i]; + for (int k = 0; k < numBytes; k++, l++) buf[l] = (byte) (val >>> (k << 3)); + } + if (l == buf.length || i == numSamples - 1) { + hasher.update(buf, 0, l); + l = 0; + } + } + return hasher.digest(); + } + + /** + * Checks the state of this object, and either returns silently or throws an exception. + * + * @throws NullPointerException if the MD5 hash array is {@code null} + * @throws IllegalStateException if any field has an invalid value + */ + public void checkValues() { + if ((minBlockSize >>> 16) != 0) throw new IllegalStateException("Invalid minimum block size"); + if ((maxBlockSize >>> 16) != 0) throw new IllegalStateException("Invalid maximum block size"); + if ((minFrameSize >>> 24) != 0) throw new IllegalStateException("Invalid minimum frame size"); + if ((maxFrameSize >>> 24) != 0) throw new IllegalStateException("Invalid maximum frame size"); + if (sampleRate == 0 || (sampleRate >>> 20) != 0) throw new IllegalStateException("Invalid sample rate"); + if (numChannels < 1 || numChannels > 8) throw new IllegalStateException("Invalid number of channels"); + if (sampleDepth < 4 || sampleDepth > 32) throw new IllegalStateException("Invalid sample depth"); + if ((numSamples >>> 36) != 0) throw new IllegalStateException("Invalid number of samples"); + Objects.requireNonNull(md5Hash); + if (md5Hash.length != 16) throw new IllegalStateException("Invalid MD5 hash length"); + } + + /*---- Static functions ----*/ + + /** + * Checks whether the specified frame information is consistent with values in + * this stream info object, either returning silently or throwing an exception. + * + * @param meta the frame info object to check (not {@code null}) + * @throws NullPointerException if the frame info is {@code null} + * @throws DataFormatException if the frame info contains bad values + */ + public void checkFrame(FrameInfo meta) { + if (meta.numChannels != numChannels) throw new DataFormatException("Channel count mismatch"); + if (meta.sampleRate != -1 && meta.sampleRate != sampleRate) + throw new DataFormatException("Sample rate mismatch"); + if (meta.sampleDepth != -1 && meta.sampleDepth != sampleDepth) + throw new DataFormatException("Sample depth mismatch"); + if (numSamples != 0 && meta.blockSize > numSamples) + throw new DataFormatException("Block size exceeds total number of samples"); + + if (meta.blockSize > maxBlockSize) throw new DataFormatException("Block size exceeds maximum"); + // Note: If minBlockSize == maxBlockSize, then the final block + // in the stream is allowed to be smaller than minBlockSize + + if (minFrameSize != 0 && meta.frameSize < minFrameSize) + throw new DataFormatException("Frame size less than minimum"); + if (maxFrameSize != 0 && meta.frameSize > maxFrameSize) + throw new DataFormatException("Frame size exceeds maximum"); + } + +} diff --git a/core/decoder/Bitstream.java b/core/decoder/mp3/Bitstream.java similarity index 99% rename from core/decoder/Bitstream.java rename to core/decoder/mp3/Bitstream.java index 617e54ae..217e652e 100644 --- a/core/decoder/Bitstream.java +++ b/core/decoder/mp3/Bitstream.java @@ -33,7 +33,7 @@ *---------------------------------------------------------------------- */ -package com.coloryr.allmusic.server.core.decoder; +package com.coloryr.allmusic.server.core.decoder.mp3; import java.io.*; @@ -119,9 +119,8 @@ public final class Bitstream implements BitstreamErrors { * * @param in The InputStream to read from. */ - public Bitstream(InputStream in) { + public Bitstream(BufferedInputStream in) { if (in == null) throw new NullPointerException("in"); - in = new BufferedInputStream(in); loadID3v2(in); firstframe = true; //source = new PushbackInputStream(in, 1024); diff --git a/core/decoder/BitstreamErrors.java b/core/decoder/mp3/BitstreamErrors.java similarity index 96% rename from core/decoder/BitstreamErrors.java rename to core/decoder/mp3/BitstreamErrors.java index f0fbc383..a2a0846f 100644 --- a/core/decoder/BitstreamErrors.java +++ b/core/decoder/mp3/BitstreamErrors.java @@ -19,7 +19,7 @@ *---------------------------------------------------------------------- */ -package com.coloryr.allmusic.server.core.decoder; +package com.coloryr.allmusic.server.core.decoder.mp3; /** * This interface describes all error codes that can be thrown diff --git a/core/decoder/BitstreamException.java b/core/decoder/mp3/BitstreamException.java similarity index 97% rename from core/decoder/BitstreamException.java rename to core/decoder/mp3/BitstreamException.java index ffc7bf3b..a951e8a9 100644 --- a/core/decoder/BitstreamException.java +++ b/core/decoder/mp3/BitstreamException.java @@ -18,7 +18,7 @@ *---------------------------------------------------------------------- */ -package com.coloryr.allmusic.server.core.decoder; +package com.coloryr.allmusic.server.core.decoder.mp3; /** * Instances of BitstreamException are thrown diff --git a/core/decoder/Crc16.java b/core/decoder/mp3/Crc16.java similarity index 97% rename from core/decoder/Crc16.java rename to core/decoder/mp3/Crc16.java index 88535fd1..d5a9f72e 100644 --- a/core/decoder/Crc16.java +++ b/core/decoder/mp3/Crc16.java @@ -22,7 +22,7 @@ * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. *---------------------------------------------------------------------- */ -package com.coloryr.allmusic.server.core.decoder; +package com.coloryr.allmusic.server.core.decoder.mp3; /** * 16-Bit CRC checksum diff --git a/core/decoder/Header.java b/core/decoder/mp3/Header.java similarity index 99% rename from core/decoder/Header.java rename to core/decoder/mp3/Header.java index 26d723ee..7c0b5234 100644 --- a/core/decoder/Header.java +++ b/core/decoder/mp3/Header.java @@ -29,7 +29,7 @@ * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. *---------------------------------------------------------------------- */ -package com.coloryr.allmusic.server.core.decoder; +package com.coloryr.allmusic.server.core.decoder.mp3; /** * Class for extracting information from a frame header. diff --git a/core/decoder/JavaLayerErrors.java b/core/decoder/mp3/JavaLayerErrors.java similarity index 96% rename from core/decoder/JavaLayerErrors.java rename to core/decoder/mp3/JavaLayerErrors.java index b5af9a71..54f993e8 100644 --- a/core/decoder/JavaLayerErrors.java +++ b/core/decoder/mp3/JavaLayerErrors.java @@ -18,7 +18,7 @@ *---------------------------------------------------------------------- */ -package com.coloryr.allmusic.server.core.decoder; +package com.coloryr.allmusic.server.core.decoder.mp3; /** * Exception erorr codes for components of the JavaLayer API. diff --git a/core/decoder/JavaLayerException.java b/core/decoder/mp3/JavaLayerException.java similarity index 97% rename from core/decoder/JavaLayerException.java rename to core/decoder/mp3/JavaLayerException.java index acee4ffe..1bd0fa2c 100644 --- a/core/decoder/JavaLayerException.java +++ b/core/decoder/mp3/JavaLayerException.java @@ -18,7 +18,7 @@ *---------------------------------------------------------------------- */ -package com.coloryr.allmusic.server.core.decoder; +package com.coloryr.allmusic.server.core.decoder.mp3; import java.io.PrintStream; diff --git a/core/music/api/APIMain.java b/core/music/api/APIMain.java index a83eb59f..a8e77900 100644 --- a/core/music/api/APIMain.java +++ b/core/music/api/APIMain.java @@ -1,9 +1,14 @@ package com.coloryr.allmusic.server.core.music.api; import com.coloryr.allmusic.server.core.AllMusic; +import com.coloryr.allmusic.server.core.decoder.flac.FlacDecoder; +import com.coloryr.allmusic.server.core.decoder.flac.StreamInfo; +import com.coloryr.allmusic.server.core.decoder.mp3.Bitstream; +import com.coloryr.allmusic.server.core.decoder.mp3.Header; import com.coloryr.allmusic.server.core.music.play.LyricDo; import com.coloryr.allmusic.server.core.music.play.LyricSave; import com.coloryr.allmusic.server.core.objs.HttpResObj; +import com.coloryr.allmusic.server.core.objs.MediaType; import com.coloryr.allmusic.server.core.objs.SearchMusicObj; import com.coloryr.allmusic.server.core.objs.api.music.info.InfoObj; import com.coloryr.allmusic.server.core.objs.api.music.list.DataObj; @@ -19,8 +24,12 @@ import com.coloryr.allmusic.server.core.objs.music.SongInfoObj; import com.coloryr.allmusic.server.core.sql.DataSql; import com.google.gson.JsonObject; +import java.io.BufferedInputStream; +import java.io.IOException; +import java.io.InputStream; import java.util.ArrayList; import java.util.List; +import java.util.Objects; public class APIMain { @@ -243,4 +252,73 @@ public class APIMain { } return null; } + + private static int toUnsignedInt(byte x) { + return ((int) x) & 0xff;//将高24位全部变成0,低8位保持不变 + } + + private static MediaType testMediaType(BufferedInputStream stream) throws IOException { + stream.mark(10); + byte[] temp = new byte[4]; + int res = stream.read(temp); + if (res != 4) { + return MediaType.Unknow; + } + if (temp[0] == 'R' && temp[1] == 'I' && temp[2] == 'F' && temp[3] == 'F') { + return MediaType.Wav; + } else if (temp[0] == 'f' && temp[1] == 'L' && temp[2] == 'a' && temp[3] == 'C') { + return MediaType.Flac; + } else if (temp[0] == 'I' && temp[1] == 'D' && temp[2] == '3') { + return MediaType.Mp3; + } else if (toUnsignedInt(temp[0]) == 0xFF && toUnsignedInt(temp[1]) == 0xE0) { + return MediaType.Mp3; + } + + return MediaType.Unknow; + } + + public static SongInfoObj getUrlMusic(String url) { + try { + InputStream stream = HttpClientUtil.get(url); + if (stream == null) { + return null; + } + BufferedInputStream in = new BufferedInputStream(stream); + MediaType type = testMediaType(in); + in.reset(); + float le = 0; + if (type == MediaType.Mp3) { + Bitstream bt = new Bitstream(in); + bt.readFrame(); + bt.closeFrame(); + Header h; + for (; ; ) { + h = bt.readFrame(); + if (h == null) { + break; + } + bt.closeFrame(); + le += h.ms_per_frame(); + } + bt.close(); + return new SongInfoObj(null, url, (int) le, type); + } else if (type == MediaType.Flac) { + FlacDecoder flac = new FlacDecoder(in); + for (; ; ) { + Object temp = flac.readAndHandleMetadataBlock(); + if (temp instanceof StreamInfo) { + StreamInfo info = (StreamInfo) temp; + le = (float) info.numSamples / info.sampleRate; + flac.close(); + return new SongInfoObj(null, url, (int) le, type); + } + } + } + } catch (Exception e) { + AllMusic.log.warning("§d[AllMusic3]§c歌曲长度解析错误"); + e.printStackTrace(); + } + + return null; + } } diff --git a/core/music/api/HttpClientUtil.java b/core/music/api/HttpClientUtil.java index 4d4f9e52..05257c48 100644 --- a/core/music/api/HttpClientUtil.java +++ b/core/music/api/HttpClientUtil.java @@ -38,6 +38,33 @@ public class HttpClientUtil { } } + public static InputStream get(String path) { + try { + Request request = new Request.Builder().url(path) + .addHeader("user-agent", UserAgent) + .get() + .build(); + Response response = client.newCall(request).execute(); + int httpCode = response.code(); + ResponseBody body = response.body(); + if (body == null) { + AllMusic.log.warning("§d[AllMusic3]§c获取网页错误"); + return null; + } + InputStream inputStream = body.byteStream(); + boolean ok = httpCode == 200; + if(!ok) + { + return null; + } + return inputStream; + } catch (Exception e) { + AllMusic.log.warning("§d[AllMusic3]§c获取网页错误"); + e.printStackTrace(); + } + return null; + } + public static HttpResObj get(String path, String data) { try { data = URLEncoder.encode(data, StandardCharsets.UTF_8.toString()); @@ -62,6 +89,8 @@ public class HttpClientUtil { while ((length = inputStream.read(buffer)) != -1) { result.write(buffer, 0, length); } + inputStream.close(); + response.close(); String data1 = result.toString(StandardCharsets.UTF_8.toString()); if (!ok) { AllMusic.log.warning("§d[AllMusic3]§c服务器返回错误:" + data1); diff --git a/core/music/play/PlayMusic.java b/core/music/play/PlayMusic.java index fb596929..38037ca0 100644 --- a/core/music/play/PlayMusic.java +++ b/core/music/play/PlayMusic.java @@ -1,8 +1,7 @@ package com.coloryr.allmusic.server.core.music.play; import com.coloryr.allmusic.server.core.AllMusic; -import com.coloryr.allmusic.server.core.decoder.Bitstream; -import com.coloryr.allmusic.server.core.decoder.Header; +import com.coloryr.allmusic.server.core.music.api.APIMain; import com.coloryr.allmusic.server.core.objs.config.LimitObj; import com.coloryr.allmusic.server.core.objs.message.PAL; import com.coloryr.allmusic.server.core.objs.music.MusicObj; @@ -10,9 +9,6 @@ import com.coloryr.allmusic.server.core.objs.music.SongInfoObj; import com.coloryr.allmusic.server.core.sql.DataSql; import com.coloryr.allmusic.server.core.utils.HudUtils; -import java.io.BufferedInputStream; -import java.net.URL; -import java.net.URLConnection; import java.util.*; import java.util.concurrent.ConcurrentLinkedQueue; @@ -424,25 +420,13 @@ public class PlayMusic { * @param url 链接 */ private static void addUrl(String url) { - try { - URL urlfile = new URL(url); - URLConnection con = urlfile.openConnection(); - int b = con.getContentLength();// 得到音乐文件的总长度 - BufferedInputStream bis = new BufferedInputStream(con.getInputStream()); - Bitstream bt = new Bitstream(bis); - Header h = bt.readFrame(); - int le = 6000000; - if (h == null) { - AllMusic.side.broadcastInTask(AllMusic.getMessage().musicPlay.error1); - } else { - le = (int) h.total_ms(b); - } - SongInfoObj info = new SongInfoObj(AllMusic.getMessage().custom.info, url, le); - playList.add(info); - } catch (Exception e) { - AllMusic.log.warning("§d[AllMusic3]§c歌曲信息解析错误"); - e.printStackTrace(); + SongInfoObj info = APIMain.getUrlMusic(url); + if (info == null) { + AllMusic.side.broadcastInTask(AllMusic.getMessage().musicPlay.error1); + return; } + info.setName(AllMusic.getMessage().custom.info); + playList.add(info); } /** diff --git a/core/objs/MediaType.java b/core/objs/MediaType.java new file mode 100644 index 00000000..c3d9732a --- /dev/null +++ b/core/objs/MediaType.java @@ -0,0 +1,5 @@ +package com.coloryr.allmusic.server.core.objs; + +public enum MediaType { + Wav, Mp3, Flac, Unknow +} diff --git a/core/objs/music/SongInfoObj.java b/core/objs/music/SongInfoObj.java index 85b821b6..7445c631 100644 --- a/core/objs/music/SongInfoObj.java +++ b/core/objs/music/SongInfoObj.java @@ -1,6 +1,7 @@ package com.coloryr.allmusic.server.core.objs.music; import com.coloryr.allmusic.server.core.AllMusic; +import com.coloryr.allmusic.server.core.objs.MediaType; import com.coloryr.allmusic.server.core.objs.api.music.trialinfo.freeTrialInfo; import com.coloryr.allmusic.server.core.objs.message.PAL; @@ -59,14 +60,19 @@ public class SongInfoObj { * 是否是Url歌曲 */ protected boolean isUrl; + /** + * 音乐类型 + */ + protected MediaType mediaType; - public SongInfoObj(String Name, String Url, int Length) { - this.length = Length; - playerUrl = Url; - this.name = Name; + public SongInfoObj(String name, String url, int length, MediaType type) { + this.length = length; + playerUrl = url; + this.name = name; id = alia = call = al = author = picUrl = ""; isList = false; isUrl = true; + mediaType = type; } public SongInfoObj(String Author, String Name, String ID, String Alia, String Call, String Al, @@ -82,6 +88,7 @@ public class SongInfoObj { this.length = Length; this.isTrial = isTrial; this.trialInfo = trialInfo; + this.mediaType = MediaType.Mp3; } public boolean isUrl() { @@ -149,4 +156,12 @@ public class SongInfoObj { public boolean isNull() { return name == null; } + + public void setName(String info) { + name = info; + } + + public MediaType getMediaType() { + return mediaType; + } } diff --git a/core/objs/music/TopSongInfoObj.java b/core/objs/music/TopSongInfoObj.java index 48084aa3..c50eb487 100644 --- a/core/objs/music/TopSongInfoObj.java +++ b/core/objs/music/TopSongInfoObj.java @@ -1,10 +1,11 @@ package com.coloryr.allmusic.server.core.objs.music; +import com.coloryr.allmusic.server.core.objs.MediaType; import com.coloryr.allmusic.server.core.objs.api.music.trialinfo.freeTrialInfo; public class TopSongInfoObj extends SongInfoObj { public TopSongInfoObj() { - super(null, null, 0); + super(null, null, 0, MediaType.Unknow); } public void setAl(String al) { diff --git a/version b/version index 8a0feb98..5141b615 100644 --- a/version +++ b/version @@ -1 +1 @@ -3.4.3 \ No newline at end of file +3.4.4 \ No newline at end of file