diff --git a/core/AllMusicAPI.java b/core/AllMusicAPI.java index 229a89f8..677f956d 100644 --- a/core/AllMusicAPI.java +++ b/core/AllMusicAPI.java @@ -8,6 +8,7 @@ public class AllMusicApi { /** * 注册音乐API + * * @param api 音乐API * @return 返回序号 */ @@ -18,6 +19,7 @@ public class AllMusicApi { /** * 获取默认音乐API + * * @return 音乐API */ public static IMusicApi getApiMusic() { @@ -26,6 +28,7 @@ public class AllMusicApi { /** * 获取某个音乐API + * * @param api 音乐API * @return 音乐API */ diff --git a/core/IMusicApi.java b/core/IMusicApi.java index 0ea41a44..84589812 100644 --- a/core/IMusicApi.java +++ b/core/IMusicApi.java @@ -6,14 +6,20 @@ import com.coloryr.allmusic.server.core.objs.music.SongInfoObj; public interface IMusicApi { String getId(); + SongInfoObj getMusic(String id, String player, boolean isList); + SearchPageObj search(String[] args, boolean isDefault); + void setList(String id, Object sender); + LyricSave getLyric(String id); + String getPlayUrl(String id); boolean isBusy(); String getMusicId(String arg); + boolean checkId(String id); } diff --git a/core/command/CommandEX.java b/core/command/CommandEX.java index e055ff44..dbeb83be 100644 --- a/core/command/CommandEX.java +++ b/core/command/CommandEX.java @@ -8,7 +8,6 @@ import com.coloryr.allmusic.server.core.music.PlayMusic; import com.coloryr.allmusic.server.core.objs.message.ARG; import com.coloryr.allmusic.server.core.objs.music.PlayerAddMusicObj; import com.coloryr.allmusic.server.core.sql.DataSql; -import com.coloryr.allmusic.server.core.utils.Function; import java.util.ArrayList; import java.util.HashMap; @@ -44,6 +43,7 @@ public class CommandEX { commandList.put("vote", new CommandVote()); commandList.put("mute", new CommandMute()); commandList.put("search", new CommandSearch()); + commandList.put("searchapi", new CommandSearchApi()); commandList.put("select", new CommandSelect()); commandList.put("nextpage", new CommandNextPage()); commandList.put("lastpage", new CommandLastPage()); @@ -79,6 +79,32 @@ public class CommandEX { obj.name = name; obj.args = args; obj.isDefault = isDefault; + obj.api = AllMusic.getConfig().defaultApi; + + if (AllMusic.side.onMusicAdd(sender, obj)) { + AllMusic.side.sendMessage(sender, AllMusic.getMessage().addMusic.cancel); + return; + } + + MusicSearch.addSearch(obj); + } + + /** + * 搜索音乐 + * + * @param sender 发送者 + * @param name 用户名 + * @param args 参数 + * @param isDefault 是否是默认点歌方式 + */ + public static void searchMusicApi(Object sender, String name, String[] args, boolean isDefault) { + PlayerAddMusicObj obj = new PlayerAddMusicObj(); + obj.sender = sender; + obj.name = name; + obj.args = new String[args.length - 1]; + System.arraycopy(args, 1, obj.args, 0, obj.args.length); + obj.isDefault = isDefault; + obj.api = args[0]; if (AllMusic.side.onMusicAdd(sender, obj)) { AllMusic.side.sendMessage(sender, AllMusic.getMessage().addMusic.cancel); @@ -137,7 +163,7 @@ public class CommandEX { * * @param sender 发送者 * @param name 用户名 - * @param arg 参数 + * @param arg 参数 */ public static void addMusic(Object sender, String name, String api, String arg) { String musicID; @@ -176,6 +202,7 @@ public class CommandEX { obj.id = musicID; obj.name = name; obj.isDefault = false; + obj.api = api; if (AllMusic.side.onMusicAdd(sender, obj)) { AllMusic.side.sendMessageTask(sender, AllMusic.getMessage().addMusic.cancel); @@ -236,7 +263,11 @@ public class CommandEX { break; case 0: default: - DataSql.task(() -> addMusic(sender, name, AllMusic.getConfig().defaultApi, args[0])); + if (args.length == 1) { + DataSql.task(() -> addMusic(sender, name, AllMusic.getConfig().defaultApi, args[0])); + } else if (args.length == 2) { + DataSql.task(() -> addMusic(sender, name, args[0], args[1])); + } } } } catch (Exception e) { diff --git a/core/command/sub/CommandAddList.java b/core/command/sub/CommandAddList.java index b35b9272..d5baeb30 100644 --- a/core/command/sub/CommandAddList.java +++ b/core/command/sub/CommandAddList.java @@ -3,7 +3,6 @@ package com.coloryr.allmusic.server.core.command.sub; import com.coloryr.allmusic.server.core.AllMusic; import com.coloryr.allmusic.server.core.IMusicApi; import com.coloryr.allmusic.server.core.command.ACommand; -import com.coloryr.allmusic.server.core.utils.Function; public class CommandAddList extends ACommand { @Override diff --git a/core/command/sub/CommandBan.java b/core/command/sub/CommandBan.java index a5f60d3a..fa60d61b 100644 --- a/core/command/sub/CommandBan.java +++ b/core/command/sub/CommandBan.java @@ -6,7 +6,6 @@ import com.coloryr.allmusic.server.core.command.ACommand; import com.coloryr.allmusic.server.core.music.PlayMusic; import com.coloryr.allmusic.server.core.objs.music.SongInfoObj; import com.coloryr.allmusic.server.core.sql.DataSql; -import com.coloryr.allmusic.server.core.utils.Function; import java.util.ArrayList; import java.util.Collections; diff --git a/core/command/sub/CommandSearchApi.java b/core/command/sub/CommandSearchApi.java new file mode 100644 index 00000000..47fa1400 --- /dev/null +++ b/core/command/sub/CommandSearchApi.java @@ -0,0 +1,32 @@ +package com.coloryr.allmusic.server.core.command.sub; + +import com.coloryr.allmusic.server.core.AllMusic; +import com.coloryr.allmusic.server.core.command.ACommand; +import com.coloryr.allmusic.server.core.command.CommandEX; +import com.coloryr.allmusic.server.core.command.PermissionList; + +public class CommandSearchApi extends ACommand { + @Override + public void execute(Object sender, String name, String[] args) { + if (AllMusic.getConfig().needPermission && + !AllMusic.side.checkPermission(sender, PermissionList.PERMISSION_SEARCH)) { + AllMusic.side.sendMessage(sender, AllMusic.getMessage().search.noPer); + return; + } + if (CommandEX.checkMoney(sender, name, AllMusic.getConfig().cost.searchCost)) { + return; + } + if (CommandEX.cost(sender, name, AllMusic.getConfig().cost.searchCost, + AllMusic.getMessage().cost.search)) { + return; + } + + if (args.length < 2) { + AllMusic.side.sendMessage(sender, AllMusic.getMessage().musicPlay.error2); + return; + } + + AllMusic.side.sendMessage(sender, AllMusic.getMessage().search.startSearch); + CommandEX.searchMusicApi(sender, name, args,false); + } +} diff --git a/core/command/sub/CommandUnban.java b/core/command/sub/CommandUnban.java index 02f1b22c..b52be9b8 100644 --- a/core/command/sub/CommandUnban.java +++ b/core/command/sub/CommandUnban.java @@ -5,7 +5,6 @@ import com.coloryr.allmusic.server.core.IMusicApi; import com.coloryr.allmusic.server.core.command.ACommand; import com.coloryr.allmusic.server.core.sql.Cache; import com.coloryr.allmusic.server.core.sql.DataSql; -import com.coloryr.allmusic.server.core.utils.Function; import java.util.ArrayList; import java.util.Collections; diff --git a/core/decoder/flac/AbstractFlacLowLevelInput.java b/core/decoder/flac/AbstractFlacLowLevelInput.java deleted file mode 100644 index 5457b352..00000000 --- a/core/decoder/flac/AbstractFlacLowLevelInput.java +++ /dev/null @@ -1,308 +0,0 @@ -/* - * 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 deleted file mode 100644 index e2f4f43a..00000000 --- a/core/decoder/flac/ByteArrayFlacInput.java +++ /dev/null @@ -1,73 +0,0 @@ -/* - * 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 deleted file mode 100644 index 7d36262d..00000000 --- a/core/decoder/flac/DataFormatException.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * 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 deleted file mode 100644 index 51212c58..00000000 --- a/core/decoder/flac/FlacDecoder.java +++ /dev/null @@ -1,112 +0,0 @@ -/* - * 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 deleted file mode 100644 index 9abcf3c4..00000000 --- a/core/decoder/flac/FlacLowLevelInput.java +++ /dev/null @@ -1,104 +0,0 @@ -/* - * 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 deleted file mode 100644 index 53260b63..00000000 --- a/core/decoder/flac/FrameInfo.java +++ /dev/null @@ -1,288 +0,0 @@ -/* - * 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 deleted file mode 100644 index e712ecb5..00000000 --- a/core/decoder/flac/SeekTable.java +++ /dev/null @@ -1,159 +0,0 @@ -/* - * 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 deleted file mode 100644 index 7841971c..00000000 --- a/core/decoder/flac/SeekableFileFlacInput.java +++ /dev/null @@ -1,63 +0,0 @@ -/* - * 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 deleted file mode 100644 index 73ddc82f..00000000 --- a/core/decoder/flac/StreamInfo.java +++ /dev/null @@ -1,243 +0,0 @@ -/* - * 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/mp3/Bitstream.java b/core/decoder/mp3/Bitstream.java deleted file mode 100644 index 217e652e..00000000 --- a/core/decoder/mp3/Bitstream.java +++ /dev/null @@ -1,535 +0,0 @@ -/* - * 11/19/04 1.0 moved to LGPL. - * - * 11/17/04 Uncomplete frames discarded. E.B, javalayer@javazoom.net - * - * 12/05/03 ID3v2 tag returned. E.B, javalayer@javazoom.net - * - * 12/12/99 Based on Ibitstream. Exceptions thrown on errors, - * Temporary removed seek functionality. mdm@techie.com - * - * 02/12/99 : Java Conversion by E.B , javalayer@javazoom.net - * - * 04/14/97 : Added function prototypes for new syncing and seeking - * mechanisms. Also made this file portable. Changes made by Jeff Tsay - * - * @(#) ibitstream.h 1.5, last edit: 6/15/94 16:55:34 - * @(#) Copyright (C) 1993, 1994 Tobias Bading (bading@cs.tu-berlin.de) - * @(#) Berlin University of Technology - *----------------------------------------------------------------------- - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU Library General Public License as published - * by the Free Software Foundation; either version 2 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 Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public - * License along with this program; if not, write to the Free Software - * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. - *---------------------------------------------------------------------- - */ - -package com.coloryr.allmusic.server.core.decoder.mp3; - -import java.io.*; - - -/** - * The Bistream class is responsible for parsing - * an MPEG audio bitstream. - * - * REVIEW: much of the parsing currently occurs in the - * various decoders. This should be moved into this class and associated - * inner classes. - */ -public final class Bitstream implements BitstreamErrors { - /** - * Maximum size of the frame buffer. - */ - private static final int BUFFER_INT_SIZE = 433; - /** - * Synchronization control constant for the initial - * synchronization to the start of a frame. - */ - static byte INITIAL_SYNC = 0; - - // max. 1730 bytes per frame: 144 * 384kbit/s / 32000 Hz + 2 Bytes CRC - /** - * Synchronization control constant for non-initial frame - * synchronizations. - */ - static byte STRICT_SYNC = 1; - /** - * The frame buffer that holds the data for the current frame. - */ - private final int[] framebuffer = new int[BUFFER_INT_SIZE]; - private final int[] bitmask = {0, // dummy - 0x00000001, 0x00000003, 0x00000007, 0x0000000F, - 0x0000001F, 0x0000003F, 0x0000007F, 0x000000FF, - 0x000001FF, 0x000003FF, 0x000007FF, 0x00000FFF, - 0x00001FFF, 0x00003FFF, 0x00007FFF, 0x0000FFFF, - 0x0001FFFF}; - private final PushbackInputStream source; - private final Header header = new Header(); - private final byte[] syncbuf = new byte[4]; - /** - * The bytes read from the stream. - */ - private final byte[] frame_bytes = new byte[BUFFER_INT_SIZE * 4]; - private final Crc16[] crc = new Crc16[1]; - /** - * Number of valid bytes in the frame buffer. - */ - private int framesize; - //private int current_frame_number; - //private int last_frame_number; - /** - * Index into framebuffer where the next bits are - * retrieved. - */ - private int wordpointer; - /** - * Number (0-31, from MSB to LSB) of next bit for get_bits() - */ - private int bitindex; - /** - * The current specified syncword - */ - private int syncword; - /** - * Audio header position in stream. - */ - private int header_pos = 0; - /** - * - */ - private boolean single_ch_mode; - private byte[] rawid3v2 = null; - - private boolean firstframe = true; - - - /** - * Construct a IBitstream that reads data from a - * given InputStream. - * - * @param in The InputStream to read from. - */ - public Bitstream(BufferedInputStream in) { - if (in == null) throw new NullPointerException("in"); - loadID3v2(in); - firstframe = true; - //source = new PushbackInputStream(in, 1024); - source = new PushbackInputStream(in, BUFFER_INT_SIZE * 4); - - closeFrame(); - //current_frame_number = -1; - //last_frame_number = -1; - } - - /** - * Return position of the first audio header. - * - * @return size of ID3v2 tag frames. - */ - public int header_pos() { - return header_pos; - } - - /** - * Load ID3v2 frames. - * - * @param in MP3 InputStream. - * @author JavaZOOM - */ - private void loadID3v2(InputStream in) { - int size = -1; - try { - // Read ID3v2 header (10 bytes). - in.mark(10); - size = readID3v2Header(in); - header_pos = size; - } catch (IOException e) { - } finally { - try { - // Unread ID3v2 header (10 bytes). - in.reset(); - } catch (IOException e) { - } - } - // Load ID3v2 tags. - try { - if (size > 0) { - rawid3v2 = new byte[size]; - in.read(rawid3v2, 0, rawid3v2.length); - } - } catch (IOException e) { - } - } - - /** - * Parse ID3v2 tag header to find out size of ID3v2 frames. - * - * @param in MP3 InputStream - * @return size of ID3v2 frames + header - * @throws IOException - * @author JavaZOOM - */ - private int readID3v2Header(InputStream in) throws IOException { - byte[] id3header = new byte[4]; - int size = -10; - in.read(id3header, 0, 3); - // Look for ID3v2 - if ((id3header[0] == 'I') && (id3header[1] == 'D') && (id3header[2] == '3')) { - in.read(id3header, 0, 3); - int majorVersion = id3header[0]; - int revision = id3header[1]; - in.read(id3header, 0, 4); - size = (id3header[0] << 21) + (id3header[1] << 14) + (id3header[2] << 7) + (id3header[3]); - } - return (size + 10); - } - - /** - * Return raw ID3v2 frames + header. - * - * @return ID3v2 InputStream or null if ID3v2 frames are not available. - */ - public InputStream getRawID3v2() { - if (rawid3v2 == null) return null; - else { - return new ByteArrayInputStream(rawid3v2); - } - } - - /** - * Close the Bitstream. - * - * @throws BitstreamException - */ - public void close() throws BitstreamException { - try { - source.close(); - } catch (IOException ex) { - throw newBitstreamException(STREAM_ERROR, ex); - } - } - - /** - * Reads and parses the next frame from the input source. - * - * @return the Header describing details of the frame read, - * or null if the end of the stream has been reached. - */ - public Header readFrame() throws BitstreamException { - Header result = null; - try { - result = readNextFrame(); - // E.B, Parse VBR (if any) first frame. - if (firstframe) { - result.parseVBR(frame_bytes); - firstframe = false; - } - } catch (BitstreamException ex) { - if ((ex.getErrorCode() == INVALIDFRAME)) { - // Try to skip this frame. - //System.out.println("INVALIDFRAME"); - try { - closeFrame(); - result = readNextFrame(); - } catch (BitstreamException e) { - if ((e.getErrorCode() != STREAM_EOF)) { - // wrap original exception so stack trace is maintained. - throw newBitstreamException(e.getErrorCode(), e); - } - } - } else if ((ex.getErrorCode() != STREAM_EOF)) { - // wrap original exception so stack trace is maintained. - throw newBitstreamException(ex.getErrorCode(), ex); - } - } - return result; - } - - /** - * Read next MP3 frame. - * - * @return MP3 frame header. - * @throws BitstreamException - */ - private Header readNextFrame() throws BitstreamException { - if (framesize == -1) { - nextFrame(); - } - return header; - } - - - /** - * Read next MP3 frame. - * - * @throws BitstreamException - */ - private void nextFrame() throws BitstreamException { - // entire frame is read by the header class. - header.read_header(this, crc); - } - - /** - * Unreads the bytes read from the frame. - * - * @throws BitstreamException - */ - // REVIEW: add new error codes for this. - public void unreadFrame() throws BitstreamException { - if (wordpointer == -1 && bitindex == -1 && (framesize > 0)) { - try { - source.unread(frame_bytes, 0, framesize); - } catch (IOException ex) { - throw newBitstreamException(STREAM_ERROR); - } - } - } - - /** - * Close MP3 frame. - */ - public void closeFrame() { - framesize = -1; - wordpointer = -1; - bitindex = -1; - } - - /** - * Determines if the next 4 bytes of the stream represent a - * frame header. - */ - public boolean isSyncCurrentPosition(int syncmode) throws BitstreamException { - int read = readBytes(syncbuf, 0, 4); - int headerstring = ((syncbuf[0] << 24) & 0xFF000000) | ((syncbuf[1] << 16) & 0x00FF0000) | ((syncbuf[2] << 8) & 0x0000FF00) | ((syncbuf[3] << 0) & 0x000000FF); - - try { - source.unread(syncbuf, 0, read); - } catch (IOException ex) { - } - - boolean sync = false; - switch (read) { - case 0: - sync = true; - break; - case 4: - sync = isSyncMark(headerstring, syncmode, syncword); - break; - } - - return sync; - } - - BitstreamException newBitstreamException(int errorcode) { - return new BitstreamException(errorcode, null); - } - - private BitstreamException newBitstreamException(int errorcode, Throwable throwable) { - return new BitstreamException(errorcode, throwable); - } - - /** - * Get next 32 bits from bitstream. - * They are stored in the headerstring. - * syncmod allows Synchro flag ID - * The returned value is False at the end of stream. - */ - - int syncHeader(byte syncmode) throws BitstreamException { - boolean sync; - int headerstring; - // read additional 2 bytes - int bytesRead = readBytes(syncbuf, 0, 3); - - if (bytesRead != 3) throw newBitstreamException(STREAM_EOF, null); - - headerstring = ((syncbuf[0] << 16) & 0x00FF0000) | ((syncbuf[1] << 8) & 0x0000FF00) | ((syncbuf[2]) & 0x000000FF); - - do { - headerstring <<= 8; - - if (readBytes(syncbuf, 3, 1) != 1) - throw newBitstreamException(STREAM_EOF, null); - - headerstring |= (syncbuf[3] & 0x000000FF); - - sync = isSyncMark(headerstring, syncmode, syncword); - } - while (!sync); - - return headerstring; - } - - public boolean isSyncMark(int headerstring, int syncmode, int word) { - boolean sync = false; - - if (syncmode == INITIAL_SYNC) { - sync = ((headerstring & 0xFFE00000) == 0xFFE00000); // SZD: MPEG 2.5 - } else { - sync = ((headerstring & 0xFFF80C00) == word) && - (((headerstring & 0x000000C0) == 0x000000C0) == single_ch_mode); - } - - // filter out invalid sample rate - if (sync) - sync = (((headerstring >>> 10) & 3) != 3); - // filter out invalid layer - if (sync) - sync = (((headerstring >>> 17) & 3) != 0); - // filter out invalid version - if (sync) - sync = (((headerstring >>> 19) & 3) != 1); - - return sync; - } - - /** - * Reads the data for the next frame. The frame is not parsed - * until parse frame is called. - */ - int read_frame_data(int bytesize) throws BitstreamException { - int numread = readFully(frame_bytes, 0, bytesize); - framesize = bytesize; - wordpointer = -1; - bitindex = -1; - return numread; - } - - /** - * Parses the data previously read with read_frame_data(). - */ - void parse_frame() throws BitstreamException { - // Convert Bytes read to int - int b = 0; - byte[] byteread = frame_bytes; - int bytesize = framesize; - - for (int k = 0; k < bytesize; k = k + 4) { - int convert = 0; - byte b0 = 0; - byte b1 = 0; - byte b2 = 0; - byte b3 = 0; - b0 = byteread[k]; - if (k + 1 < bytesize) b1 = byteread[k + 1]; - if (k + 2 < bytesize) b2 = byteread[k + 2]; - if (k + 3 < bytesize) b3 = byteread[k + 3]; - framebuffer[b++] = ((b0 << 24) & 0xFF000000) | ((b1 << 16) & 0x00FF0000) | ((b2 << 8) & 0x0000FF00) | (b3 & 0x000000FF); - } - wordpointer = 0; - bitindex = 0; - } - - /** - * Read bits from buffer into the lower bits of an unsigned int. - * The LSB contains the latest read bit of the stream. - * (1 <= number_of_bits <= 16) - */ - public int get_bits(int number_of_bits) { - int returnvalue = 0; - int sum = bitindex + number_of_bits; - - // E.B - // There is a problem here, wordpointer could be -1 ?! - if (wordpointer < 0) wordpointer = 0; - // E.B : End. - - if (sum <= 32) { - // all bits contained in *wordpointer - returnvalue = (framebuffer[wordpointer] >>> (32 - sum)) & bitmask[number_of_bits]; - // returnvalue = (wordpointer[0] >> (32 - sum)) & bitmask[number_of_bits]; - if ((bitindex += number_of_bits) == 32) { - bitindex = 0; - wordpointer++; // added by me! - } - return returnvalue; - } - - int Right = (framebuffer[wordpointer] & 0x0000FFFF); - wordpointer++; - int Left = (framebuffer[wordpointer] & 0xFFFF0000); - returnvalue = ((Right << 16) & 0xFFFF0000) | ((Left >>> 16) & 0x0000FFFF); - - returnvalue >>>= 48 - sum; // returnvalue >>= 16 - (number_of_bits - (32 - bitindex)) - returnvalue &= bitmask[number_of_bits]; - bitindex = sum - 32; - return returnvalue; - } - - /** - * Set the word we want to sync the header to. - * In Big-Endian byte order - */ - void set_syncword(int syncword0) { - syncword = syncword0 & 0xFFFFFF3F; - single_ch_mode = ((syncword0 & 0x000000C0) == 0x000000C0); - } - - /** - * Reads the exact number of bytes from the source - * input stream into a byte array. - * - * @param b The byte array to read the specified number - * of bytes into. - * @param offs The index in the array where the first byte - * read should be stored. - * @param len the number of bytes to read. - * @throws BitstreamException is thrown if the specified - * number of bytes could not be read from the stream. - */ - private int readFully(byte[] b, int offs, int len) - throws BitstreamException { - int nRead = 0; - try { - while (len > 0) { - int bytesread = source.read(b, offs, len); - if (bytesread == -1) { - while (len-- > 0) { - b[offs++] = 0; - } - break; - //throw newBitstreamException(UNEXPECTED_EOF, new EOFException()); - } - nRead = nRead + bytesread; - offs += bytesread; - len -= bytesread; - } - } catch (IOException ex) { - throw newBitstreamException(STREAM_ERROR, ex); - } - return nRead; - } - - /** - * Simlar to readFully, but doesn't throw exception when - * EOF is reached. - */ - private int readBytes(byte[] b, int offs, int len) - throws BitstreamException { - int totalBytesRead = 0; - try { - while (len > 0) { - int bytesread = source.read(b, offs, len); - if (bytesread == -1) { - break; - } - totalBytesRead += bytesread; - offs += bytesread; - len -= bytesread; - } - } catch (IOException ex) { - throw newBitstreamException(STREAM_ERROR, ex); - } - return totalBytesRead; - } -} diff --git a/core/decoder/mp3/BitstreamErrors.java b/core/decoder/mp3/BitstreamErrors.java deleted file mode 100644 index a2a0846f..00000000 --- a/core/decoder/mp3/BitstreamErrors.java +++ /dev/null @@ -1,55 +0,0 @@ -/* - * 11/19/04 1.0 moved to LGPL. - * 11/17/04 INVALIDFRAME code added. javalayer@javazoom.net - * 12/12/99 Initial version. mdm@techie.com - *----------------------------------------------------------------------- - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU Library General Public License as published - * by the Free Software Foundation; either version 2 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 Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public - * License along with this program; if not, write to the Free Software - * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. - *---------------------------------------------------------------------- - */ - -package com.coloryr.allmusic.server.core.decoder.mp3; - -/** - * This interface describes all error codes that can be thrown - * in BistreamExceptions. - * - * @author MDM 12/12/99 - * @see BitstreamException - * @since 0.0.6 - */ - -public interface BitstreamErrors extends JavaLayerErrors { - - /** - * An undeterminable error occurred. - */ - int UNKNOWN_ERROR = BITSTREAM_ERROR; - - /** - * A problem occurred reading from the stream. - */ - int STREAM_ERROR = BITSTREAM_ERROR + 2; - - /** - * The end of the stream was reached. - */ - int STREAM_EOF = BITSTREAM_ERROR + 4; - - /** - * Frame data are missing. - */ - int INVALIDFRAME = BITSTREAM_ERROR + 5; - -} diff --git a/core/decoder/mp3/BitstreamException.java b/core/decoder/mp3/BitstreamException.java deleted file mode 100644 index a951e8a9..00000000 --- a/core/decoder/mp3/BitstreamException.java +++ /dev/null @@ -1,65 +0,0 @@ -/* - * 11/19/04 1.0 moved to LGPL. - * 12/12/99 Initial version. mdm@techie.com - *----------------------------------------------------------------------- - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU Library General Public License as published - * by the Free Software Foundation; either version 2 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 Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public - * License along with this program; if not, write to the Free Software - * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. - *---------------------------------------------------------------------- - */ - -package com.coloryr.allmusic.server.core.decoder.mp3; - -/** - * Instances of BitstreamException are thrown - * when operations on a Bitstream fail. - *

- * The exception provides details of the exception condition - * in two ways: - *

  1. - * as an error-code describing the nature of the error - *


  2. - * as the Throwable instance, if any, that was thrown - * indicating that an exceptional condition has occurred. - *

- * - * @author MDM 12/12/99 - * @since 0.0.6 - */ - -public class BitstreamException extends JavaLayerException - implements BitstreamErrors { - private int errorcode = UNKNOWN_ERROR; - - public BitstreamException(String msg, Throwable t) { - super(msg, t); - } - - public BitstreamException(int errorcode, Throwable t) { - this(getErrorString(errorcode), t); - this.errorcode = errorcode; - } - - static public String getErrorString(int errorcode) { - // REVIEW: use resource bundle to map error codes - // to locale-sensitive strings. - - return "Bitstream errorcode " + Integer.toHexString(errorcode); - } - - public int getErrorCode() { - return errorcode; - } - - -} diff --git a/core/decoder/mp3/Crc16.java b/core/decoder/mp3/Crc16.java deleted file mode 100644 index d5a9f72e..00000000 --- a/core/decoder/mp3/Crc16.java +++ /dev/null @@ -1,64 +0,0 @@ -/* - * 11/19/04 : 1.0 moved to LGPL. - * - * 02/12/99 : Java Conversion by E.B , javalayer@javazoom.net - * - * @(#) crc.h 1.5, last edit: 6/15/94 16:55:32 - * @(#) Copyright (C) 1993, 1994 Tobias Bading (bading@cs.tu-berlin.de) - * @(#) Berlin University of Technology - *----------------------------------------------------------------------- - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU Library General Public License as published - * by the Free Software Foundation; either version 2 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 Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public - * License along with this program; if not, write to the Free Software - * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. - *---------------------------------------------------------------------- - */ -package com.coloryr.allmusic.server.core.decoder.mp3; - -/** - * 16-Bit CRC checksum - */ -public final class Crc16 { - private short crc; - - /** - * Dummy Constructor - */ - public Crc16() { - crc = (short) 0xFFFF; - } - - /** - * Feed a bitstring to the crc calculation (0 < length <= 32). - */ - public void add_bits(int bitstring, int length) { - int bitmask = 1 << (length - 1); - do - if (((crc & 0x8000) == 0) ^ ((bitstring & bitmask) == 0)) { - crc <<= 1; - short polynomial = (short) 0x8005; - crc ^= polynomial; - } else - crc <<= 1; - while ((bitmask >>>= 1) != 0); - } - - /** - * Return the calculated checksum. - * Erase it for next calls to add_bits(). - */ - public short checksum() { - short sum = crc; - crc = (short) 0xFFFF; - return sum; - } -} diff --git a/core/decoder/mp3/Header.java b/core/decoder/mp3/Header.java deleted file mode 100644 index 7c0b5234..00000000 --- a/core/decoder/mp3/Header.java +++ /dev/null @@ -1,618 +0,0 @@ -/* - * 11/19/04 : 1.0 moved to LGPL. - * VBRI header support added, E.B javalayer@javazoom.net - * - * 12/04/03 : VBR (XING) header support added, E.B javalayer@javazoom.net - * - * 02/13/99 : Java Conversion by JavaZOOM , E.B javalayer@javazoom.net - * - * Declarations for MPEG header class - * A few layer III, MPEG-2 LSF, and seeking modifications made by Jeff Tsay. - * Last modified : 04/19/97 - * - * @(#) header.h 1.7, last edit: 6/15/94 16:55:33 - * @(#) Copyright (C) 1993, 1994 Tobias Bading (bading@cs.tu-berlin.de) - * @(#) Berlin University of Technology - *----------------------------------------------------------------------- - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU Library General Public License as published - * by the Free Software Foundation; either version 2 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 Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public - * License along with this program; if not, write to the Free Software - * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. - *---------------------------------------------------------------------- - */ -package com.coloryr.allmusic.server.core.decoder.mp3; - -/** - * Class for extracting information from a frame header. - */ -public final class Header { - public static final int[][] frequencies = - {{22050, 24000, 16000, 1}, - {44100, 48000, 32000, 1}, - {11025, 12000, 8000, 1}}; // SZD: MPEG25 - - /** - * Constant for MPEG-2 LSF version - */ - public static final int MPEG2_LSF = 0; - public static final int MPEG25_LSF = 2; // SZD - - /** - * Constant for MPEG-1 version - */ - public static final int MPEG1 = 1; - - public static final int STEREO = 0; - public static final int JOINT_STEREO = 1; - public static final int DUAL_CHANNEL = 2; - public static final int SINGLE_CHANNEL = 3; - public static final int FOURTYFOUR_POINT_ONE = 0; - public static final int FOURTYEIGHT = 1; - public static final int THIRTYTWO = 2; - // E.B -> private to public - public static final int[][][] bitrates = { - {{0 /*free format*/, 32000, 48000, 56000, 64000, 80000, 96000, - 112000, 128000, 144000, 160000, 176000, 192000, 224000, 256000, 0}, - {0 /*free format*/, 8000, 16000, 24000, 32000, 40000, 48000, - 56000, 64000, 80000, 96000, 112000, 128000, 144000, 160000, 0}, - {0 /*free format*/, 8000, 16000, 24000, 32000, 40000, 48000, - 56000, 64000, 80000, 96000, 112000, 128000, 144000, 160000, 0}}, - - {{0 /*free format*/, 32000, 64000, 96000, 128000, 160000, 192000, - 224000, 256000, 288000, 320000, 352000, 384000, 416000, 448000, 0}, - {0 /*free format*/, 32000, 48000, 56000, 64000, 80000, 96000, - 112000, 128000, 160000, 192000, 224000, 256000, 320000, 384000, 0}, - {0 /*free format*/, 32000, 40000, 48000, 56000, 64000, 80000, - 96000, 112000, 128000, 160000, 192000, 224000, 256000, 320000, 0}}, - // SZD: MPEG2.5 - {{0 /*free format*/, 32000, 48000, 56000, 64000, 80000, 96000, - 112000, 128000, 144000, 160000, 176000, 192000, 224000, 256000, 0}, - {0 /*free format*/, 8000, 16000, 24000, 32000, 40000, 48000, - 56000, 64000, 80000, 96000, 112000, 128000, 144000, 160000, 0}, - {0 /*free format*/, 8000, 16000, 24000, 32000, 40000, 48000, - 56000, 64000, 80000, 96000, 112000, 128000, 144000, 160000, 0}}, - - }; - // E.B -> private to public - public static final String[][][] bitrate_str = { - {{"free format", "32 kbit/s", "48 kbit/s", "56 kbit/s", "64 kbit/s", - "80 kbit/s", "96 kbit/s", "112 kbit/s", "128 kbit/s", "144 kbit/s", - "160 kbit/s", "176 kbit/s", "192 kbit/s", "224 kbit/s", "256 kbit/s", - "forbidden"}, - {"free format", "8 kbit/s", "16 kbit/s", "24 kbit/s", "32 kbit/s", - "40 kbit/s", "48 kbit/s", "56 kbit/s", "64 kbit/s", "80 kbit/s", - "96 kbit/s", "112 kbit/s", "128 kbit/s", "144 kbit/s", "160 kbit/s", - "forbidden"}, - {"free format", "8 kbit/s", "16 kbit/s", "24 kbit/s", "32 kbit/s", - "40 kbit/s", "48 kbit/s", "56 kbit/s", "64 kbit/s", "80 kbit/s", - "96 kbit/s", "112 kbit/s", "128 kbit/s", "144 kbit/s", "160 kbit/s", - "forbidden"}}, - - {{"free format", "32 kbit/s", "64 kbit/s", "96 kbit/s", "128 kbit/s", - "160 kbit/s", "192 kbit/s", "224 kbit/s", "256 kbit/s", "288 kbit/s", - "320 kbit/s", "352 kbit/s", "384 kbit/s", "416 kbit/s", "448 kbit/s", - "forbidden"}, - {"free format", "32 kbit/s", "48 kbit/s", "56 kbit/s", "64 kbit/s", - "80 kbit/s", "96 kbit/s", "112 kbit/s", "128 kbit/s", "160 kbit/s", - "192 kbit/s", "224 kbit/s", "256 kbit/s", "320 kbit/s", "384 kbit/s", - "forbidden"}, - {"free format", "32 kbit/s", "40 kbit/s", "48 kbit/s", "56 kbit/s", - "64 kbit/s", "80 kbit/s", "96 kbit/s", "112 kbit/s", "128 kbit/s", - "160 kbit/s", "192 kbit/s", "224 kbit/s", "256 kbit/s", "320 kbit/s", - "forbidden"}}, - // SZD: MPEG2.5 - {{"free format", "32 kbit/s", "48 kbit/s", "56 kbit/s", "64 kbit/s", - "80 kbit/s", "96 kbit/s", "112 kbit/s", "128 kbit/s", "144 kbit/s", - "160 kbit/s", "176 kbit/s", "192 kbit/s", "224 kbit/s", "256 kbit/s", - "forbidden"}, - {"free format", "8 kbit/s", "16 kbit/s", "24 kbit/s", "32 kbit/s", - "40 kbit/s", "48 kbit/s", "56 kbit/s", "64 kbit/s", "80 kbit/s", - "96 kbit/s", "112 kbit/s", "128 kbit/s", "144 kbit/s", "160 kbit/s", - "forbidden"}, - {"free format", "8 kbit/s", "16 kbit/s", "24 kbit/s", "32 kbit/s", - "40 kbit/s", "48 kbit/s", "56 kbit/s", "64 kbit/s", "80 kbit/s", - "96 kbit/s", "112 kbit/s", "128 kbit/s", "144 kbit/s", "160 kbit/s", - "forbidden"}}, - }; - // VBR support added by E.B - private final double[] h_vbr_time_per_frame = {-1, 384, 1152, 1152}; - public short checksum; - public int framesize; - public int nSlots; - private int h_layer, h_protection_bit, h_bitrate_index, - h_padding_bit, h_mode_extension; - private int h_version; - private int h_mode; - private int h_sample_frequency; - private int h_number_of_subbands, h_intensity_stereo_bound; - private boolean h_vbr; - private int h_vbr_frames; - private int h_vbr_bytes; - private byte syncmode = Bitstream.INITIAL_SYNC; - private Crc16 crc; - - Header() { - } - - /** - * Returns total ms. - * - * @param streamsize - * @return total milliseconds - */ - public float total_ms(int streamsize) { - return (max_number_of_frames(streamsize) * ms_per_frame()); - } - - public String toString() { - StringBuilder buffer = new StringBuilder(200); - buffer.append("Layer "); - buffer.append(layer_string()); - buffer.append(" frame "); - buffer.append(mode_string()); - buffer.append(' '); - buffer.append(version_string()); - if (!checksums()) - buffer.append(" no"); - buffer.append(" checksums"); - buffer.append(' '); - buffer.append(sample_frequency_string()); - buffer.append(','); - buffer.append(' '); - buffer.append(bitrate_string()); - - return buffer.toString(); - } - - // Functions to query header contents: - - /** - * Read a 32-bit header from the bitstream. - */ - void read_header(Bitstream stream, Crc16[] crcp) throws BitstreamException { - int headerstring; - int channel_bitrate; - boolean sync = false; - do { - headerstring = stream.syncHeader(syncmode); - if (syncmode == Bitstream.INITIAL_SYNC) { - h_version = ((headerstring >>> 19) & 1); - if (((headerstring >>> 20) & 1) == 0) // SZD: MPEG2.5 detection - if (h_version == MPEG2_LSF) - h_version = MPEG25_LSF; - else - throw stream.newBitstreamException(Bitstream.UNKNOWN_ERROR); - if ((h_sample_frequency = ((headerstring >>> 10) & 3)) == 3) { - throw stream.newBitstreamException(Bitstream.UNKNOWN_ERROR); - } - } - h_layer = 4 - (headerstring >>> 17) & 3; - h_protection_bit = (headerstring >>> 16) & 1; - h_bitrate_index = (headerstring >>> 12) & 0xF; - h_padding_bit = (headerstring >>> 9) & 1; - h_mode = ((headerstring >>> 6) & 3); - h_mode_extension = (headerstring >>> 4) & 3; - if (h_mode == JOINT_STEREO) - h_intensity_stereo_bound = (h_mode_extension << 2) + 4; - else - h_intensity_stereo_bound = 0; // should never be used - // calculate number of subbands: - if (h_layer == 1) - h_number_of_subbands = 32; - else { - channel_bitrate = h_bitrate_index; - // calculate bitrate per channel: - if (h_mode != SINGLE_CHANNEL) - if (channel_bitrate == 4) - channel_bitrate = 1; - else - channel_bitrate -= 4; - if ((channel_bitrate == 1) || (channel_bitrate == 2)) - if (h_sample_frequency == THIRTYTWO) - h_number_of_subbands = 12; - else - h_number_of_subbands = 8; - else if ((h_sample_frequency == FOURTYEIGHT) || ((channel_bitrate >= 3) && (channel_bitrate <= 5))) - h_number_of_subbands = 27; - else - h_number_of_subbands = 30; - } - if (h_intensity_stereo_bound > h_number_of_subbands) - h_intensity_stereo_bound = h_number_of_subbands; - // calculate framesize and nSlots - calculate_framesize(); - // read framedata: - int framesizeloaded = stream.read_frame_data(framesize); - if ((framesize >= 0) && (framesizeloaded != framesize)) { - // Data loaded does not match to expected framesize, - // it might be an ID3v1 TAG. (Fix 11/17/04). - throw stream.newBitstreamException(Bitstream.INVALIDFRAME); - } - if (stream.isSyncCurrentPosition(syncmode)) { - if (syncmode == Bitstream.INITIAL_SYNC) { - syncmode = Bitstream.STRICT_SYNC; - stream.set_syncword(headerstring & 0xFFF80CC0); - } - sync = true; - } else { - stream.unreadFrame(); - } - } - while (!sync); - stream.parse_frame(); - if (h_protection_bit == 0) { - // frame contains a crc checksum - checksum = (short) stream.get_bits(16); - if (crc == null) - crc = new Crc16(); - crc.add_bits(headerstring, 16); - crcp[0] = crc; - } else - crcp[0] = null; - } - - /** - * Parse frame to extract optionnal VBR frame. - * - * @param firstframe - * @author E.B (javalayer@javazoom.net) - */ - void parseVBR(byte[] firstframe) throws BitstreamException { - // Trying Xing header. - String xing = "Xing"; - byte[] tmp = new byte[4]; - int offset = 0; - // Compute "Xing" offset depending on MPEG version and channels. - if (h_version == MPEG1) { - if (h_mode == SINGLE_CHANNEL) offset = 21 - 4; - else offset = 36 - 4; - } else { - if (h_mode == SINGLE_CHANNEL) offset = 13 - 4; - else offset = 21 - 4; - } - byte[] h_vbr_toc; - try { - System.arraycopy(firstframe, offset, tmp, 0, 4); - // Is "Xing" ? - if (xing.equals(new String(tmp))) { - //Yes. - h_vbr = true; - h_vbr_frames = -1; - h_vbr_bytes = -1; - h_vbr_toc = new byte[100]; - - int length = 4; - // Read flags. - byte[] flags = new byte[4]; - System.arraycopy(firstframe, offset + length, flags, 0, flags.length); - length += flags.length; - // Read number of frames (if available). - if ((flags[3] & (byte) (1)) != 0) { - System.arraycopy(firstframe, offset + length, tmp, 0, tmp.length); - h_vbr_frames = (tmp[0] << 24) & 0xFF000000 | (tmp[1] << 16) & 0x00FF0000 | (tmp[2] << 8) & 0x0000FF00 | tmp[3] & 0x000000FF; - length += 4; - } - // Read size (if available). - if ((flags[3] & (byte) (1 << 1)) != 0) { - System.arraycopy(firstframe, offset + length, tmp, 0, tmp.length); - h_vbr_bytes = (tmp[0] << 24) & 0xFF000000 | (tmp[1] << 16) & 0x00FF0000 | (tmp[2] << 8) & 0x0000FF00 | tmp[3] & 0x000000FF; - length += 4; - } - // Read TOC (if available). - if ((flags[3] & (byte) (1 << 2)) != 0) { - System.arraycopy(firstframe, offset + length, h_vbr_toc, 0, h_vbr_toc.length); - length += h_vbr_toc.length; - } - // Read scale (if available). - if ((flags[3] & (byte) (1 << 3)) != 0) { - System.arraycopy(firstframe, offset + length, tmp, 0, tmp.length); - } - } - } catch (ArrayIndexOutOfBoundsException e) { - throw new BitstreamException("XingVBRHeader Corrupted", e); - } - - // Trying VBRI header. - String vbri = "VBRI"; - offset = 36 - 4; - try { - System.arraycopy(firstframe, offset, tmp, 0, 4); - // Is "VBRI" ? - if (vbri.equals(new String(tmp))) { - //Yes. - h_vbr = true; - h_vbr_frames = -1; - h_vbr_bytes = -1; - // Bytes. - int length = 4 + 6; - System.arraycopy(firstframe, offset + length, tmp, 0, tmp.length); - h_vbr_bytes = (tmp[0] << 24) & 0xFF000000 | (tmp[1] << 16) & 0x00FF0000 | (tmp[2] << 8) & 0x0000FF00 | tmp[3] & 0x000000FF; - length += 4; - // Frames. - System.arraycopy(firstframe, offset + length, tmp, 0, tmp.length); - h_vbr_frames = (tmp[0] << 24) & 0xFF000000 | (tmp[1] << 16) & 0x00FF0000 | (tmp[2] << 8) & 0x0000FF00 | tmp[3] & 0x000000FF; - } - } catch (ArrayIndexOutOfBoundsException e) { - throw new BitstreamException("VBRIVBRHeader Corrupted", e); - } - } - - /** - * Returns version. - */ - public int version() { - return h_version; - } - - /** - * Returns Layer ID. - */ - public int layer() { - return h_layer; - } - - /** - * Returns bitrate index. - */ - public int bitrate_index() { - return h_bitrate_index; - } - - /** - * Returns Sample Frequency. - */ - public int sample_frequency() { - return h_sample_frequency; - } - - /** - * Returns Frequency. - */ - public int frequency() { - return frequencies[h_version][h_sample_frequency]; - } - - /** - * Returns Mode. - */ - public int mode() { - return h_mode; - } - - /** - * Returns Protection bit. - */ - public boolean checksums() { - return h_protection_bit == 0; - } - - // Seeking and layer III stuff - - /** - * Returns Checksum flag. - * Compares computed checksum with stream checksum. - */ - public boolean checksum_ok() { - return (checksum == crc.checksum()); - } - - /** - * Returns Slots. - */ - public int slots() { - return nSlots; - } - - // E.B -> private to public - - /** - * Returns Mode Extension. - */ - public int mode_extension() { - return h_mode_extension; - } - - /** - * Calculate Frame size. - * Calculates framesize in bytes excluding header size. - */ - public void calculate_framesize() { - - if (h_layer == 1) { - framesize = (12 * bitrates[h_version][0][h_bitrate_index]) / - frequencies[h_version][h_sample_frequency]; - if (h_padding_bit != 0) framesize++; - framesize <<= 2; // one slot is 4 bytes long - nSlots = 0; - } else { - framesize = (144 * bitrates[h_version][h_layer - 1][h_bitrate_index]) / - frequencies[h_version][h_sample_frequency]; - if (h_version == MPEG2_LSF || h_version == MPEG25_LSF) framesize >>= 1; // SZD - if (h_padding_bit != 0) framesize++; - // Layer III slots - if (h_layer == 3) { - if (h_version == MPEG1) { - nSlots = framesize - ((h_mode == SINGLE_CHANNEL) ? 17 : 32) // side info size - - ((h_protection_bit != 0) ? 0 : 2) // CRC size - - 4; // header size - } else { // MPEG-2 LSF, SZD: MPEG-2.5 LSF - nSlots = framesize - ((h_mode == SINGLE_CHANNEL) ? 9 : 17) // side info size - - ((h_protection_bit != 0) ? 0 : 2) // CRC size - - 4; // header size - } - } else { - nSlots = 0; - } - } - framesize -= 4; // subtract header size - } - - /** - * Returns the maximum number of frames in the stream. - * - * @param streamsize - * @return number of frames - */ - public int max_number_of_frames(int streamsize) // E.B - { - if (h_vbr) return h_vbr_frames; - else { - if ((framesize + 4 - h_padding_bit) == 0) return 0; - else return (streamsize / (framesize + 4 - h_padding_bit)); - } - } - - /** - * Returns ms/frame. - * - * @return milliseconds per frame - */ - public float ms_per_frame() // E.B - { - if (h_vbr) { - double tpf = h_vbr_time_per_frame[layer()] / frequency(); - if ((h_version == MPEG2_LSF) || (h_version == MPEG25_LSF)) tpf /= 2; - return ((float) (tpf * 1000)); - } else { - float[][] ms_per_frame_array = {{8.707483f, 8.0f, 12.0f}, - {26.12245f, 24.0f, 36.0f}, - {26.12245f, 24.0f, 36.0f}}; - return (ms_per_frame_array[h_layer - 1][h_sample_frequency]); - } - } - - // functions which return header informations as strings: - - /** - * Return Layer version. - */ - public String layer_string() { - switch (h_layer) { - case 1: - return "I"; - case 2: - return "II"; - case 3: - return "III"; - } - return null; - } - - /** - * Return Bitrate. - * - * @return bitrate in bps - */ - public String bitrate_string() { - if (h_vbr) { - return bitrate() / 1000 + " kb/s"; - } else return bitrate_str[h_version][h_layer - 1][h_bitrate_index]; - } - - /** - * Return Bitrate. - * - * @return bitrate in bps and average bitrate for VBR header - */ - public int bitrate() { - if (h_vbr) { - return ((int) ((h_vbr_bytes * 8) / (ms_per_frame() * h_vbr_frames))) * 1000; - } else return bitrates[h_version][h_layer - 1][h_bitrate_index]; - } - - /** - * Returns Frequency - * - * @return frequency string in kHz - */ - public String sample_frequency_string() { - switch (h_sample_frequency) { - case THIRTYTWO: - if (h_version == MPEG1) - return "32 kHz"; - else if (h_version == MPEG2_LSF) - return "16 kHz"; - else // SZD - return "8 kHz"; - case FOURTYFOUR_POINT_ONE: - if (h_version == MPEG1) - return "44.1 kHz"; - else if (h_version == MPEG2_LSF) - return "22.05 kHz"; - else // SZD - return "11.025 kHz"; - case FOURTYEIGHT: - if (h_version == MPEG1) - return "48 kHz"; - else if (h_version == MPEG2_LSF) - return "24 kHz"; - else // SZD - return "12 kHz"; - } - return (null); - } - - /** - * Returns Mode. - */ - public String mode_string() { - switch (h_mode) { - case STEREO: - return "Stereo"; - case JOINT_STEREO: - return "Joint stereo"; - case DUAL_CHANNEL: - return "Dual channel"; - case SINGLE_CHANNEL: - return "Single channel"; - } - return null; - } - - /** - * Returns Version. - * - * @return MPEG-1 or MPEG-2 LSF or MPEG-2.5 LSF - */ - public String version_string() { - switch (h_version) { - case MPEG1: - return "MPEG-1"; - case MPEG2_LSF: - return "MPEG-2 LSF"; - case MPEG25_LSF: // SZD - return "MPEG-2.5 LSF"; - } - return (null); - } - - /** - * Returns the number of subbands in the current frame. - * - * @return number of subbands - */ - public int number_of_subbands() { - return h_number_of_subbands; - } - - /** - * Returns Intensity Stereo. - * (Layer II joint stereo only). - * Returns the number of subbands which are in stereo mode, - * subbands above that limit are in intensity stereo mode. - * - * @return intensity - */ - public int intensity_stereo_bound() { - return h_intensity_stereo_bound; - } -} diff --git a/core/decoder/mp3/JavaLayerErrors.java b/core/decoder/mp3/JavaLayerErrors.java deleted file mode 100644 index 54f993e8..00000000 --- a/core/decoder/mp3/JavaLayerErrors.java +++ /dev/null @@ -1,39 +0,0 @@ -/* - * 11/19/04 1.0 moved to LGPL. - * 12/12/99 Initial version. mdm@techie.com - *----------------------------------------------------------------------- - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU Library General Public License as published - * by the Free Software Foundation; either version 2 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 Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public - * License along with this program; if not, write to the Free Software - * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. - *---------------------------------------------------------------------- - */ - -package com.coloryr.allmusic.server.core.decoder.mp3; - -/** - * Exception erorr codes for components of the JavaLayer API. - */ -public interface JavaLayerErrors { - /** - * The first bitstream error code. See the {@link DecoderErrors DecoderErrors} - * interface for other bitstream error codes. - */ - int BITSTREAM_ERROR = 0x100; - - /** - * The first decoder error code. See the {@link DecoderErrors DecoderErrors} - * interface for other decoder error codes. - */ - int DECODER_ERROR = 0x200; - -} diff --git a/core/decoder/mp3/JavaLayerException.java b/core/decoder/mp3/JavaLayerException.java deleted file mode 100644 index 1bd0fa2c..00000000 --- a/core/decoder/mp3/JavaLayerException.java +++ /dev/null @@ -1,61 +0,0 @@ -/* - * 11/19/04 1.0 moved to LGPL. - * 12/12/99 Initial version. mdm@techie.com - *----------------------------------------------------------------------- - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU Library General Public License as published - * by the Free Software Foundation; either version 2 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 Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public - * License along with this program; if not, write to the Free Software - * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. - *---------------------------------------------------------------------- - */ - -package com.coloryr.allmusic.server.core.decoder.mp3; - -import java.io.PrintStream; - - -/** - * The JavaLayerException is the base class for all API-level - * exceptions thrown by JavaLayer. To facilitate conversion and - * common handling of exceptions from other domains, the class - * can delegate some functionality to a contained Throwable instance. - *

- * - * @author MDM - */ -public class JavaLayerException extends Exception { - - private Throwable exception; - - public JavaLayerException(String msg) { - super(msg); - } - - public JavaLayerException(String msg, Throwable t) { - super(msg); - exception = t; - } - - public void printStackTrace() { - printStackTrace(System.err); - } - - public void printStackTrace(PrintStream ps) { - if (this.exception == null) { - super.printStackTrace(ps); - } else { - exception.printStackTrace(); - } - } - - -} diff --git a/core/music/MusicHttpClient.java b/core/music/MusicHttpClient.java index c9704eaf..4e88335c 100644 --- a/core/music/MusicHttpClient.java +++ b/core/music/MusicHttpClient.java @@ -1,13 +1,7 @@ package com.coloryr.allmusic.server.core.music; 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.objs.CookieObj; -import com.coloryr.allmusic.server.core.objs.MediaType; -import com.coloryr.allmusic.server.core.objs.music.SongInfoObj; import org.apache.hc.client5.http.classic.methods.HttpGet; import org.apache.hc.client5.http.config.RequestConfig; import org.apache.hc.client5.http.cookie.BasicCookieStore; @@ -22,8 +16,6 @@ import org.apache.hc.core5.http.HttpEntity; import org.apache.hc.core5.http.io.entity.EntityUtils; import org.apache.hc.core5.util.Timeout; -import java.io.BufferedInputStream; -import java.io.IOException; import java.io.InputStream; import java.time.Instant; import java.util.List; diff --git a/core/music/PlayMusic.java b/core/music/PlayMusic.java index 74376afa..92c5c7c9 100644 --- a/core/music/PlayMusic.java +++ b/core/music/PlayMusic.java @@ -2,9 +2,9 @@ package com.coloryr.allmusic.server.core.music; import com.coloryr.allmusic.server.core.AllMusic; import com.coloryr.allmusic.server.core.IMusicApi; -import com.coloryr.allmusic.server.core.objs.music.MusicObj; import com.coloryr.allmusic.server.core.objs.config.LimitObj; import com.coloryr.allmusic.server.core.objs.message.ARG; +import com.coloryr.allmusic.server.core.objs.music.MusicObj; import com.coloryr.allmusic.server.core.objs.music.PlayerAddMusicObj; import com.coloryr.allmusic.server.core.objs.music.SongInfoObj; import com.coloryr.allmusic.server.core.sql.DataSql; @@ -208,8 +208,6 @@ public class PlayMusic { return pushPlayer.contains(player); } - ; - /** * 添加点歌任务 * @@ -225,7 +223,7 @@ public class PlayMusic { PlayerAddMusicObj obj = tasks.poll(); if (obj != null) { IMusicApi api = AllMusic.MUSIC_APIS.get(obj.api); - if(api != null) { + if (api != null) { addMusic(obj.sender, obj.id, api, obj.name, obj.isDefault); } } @@ -411,7 +409,8 @@ public class PlayMusic { /** * 是否在播放列表中 - * @param id 音乐编号 + * + * @param id 音乐编号 * @param api 音乐API编号 * @return 是否在列表种 */ @@ -459,6 +458,7 @@ public class PlayMusic { /** * 检查这个空闲歌是否已经放了 + * * @param music 空闲音乐 * @return 是否已经放过了 */ diff --git a/core/objs/MediaType.java b/core/objs/MediaType.java deleted file mode 100644 index c3d9732a..00000000 --- a/core/objs/MediaType.java +++ /dev/null @@ -1,5 +0,0 @@ -package com.coloryr.allmusic.server.core.objs; - -public enum MediaType { - Wav, Mp3, Flac, Unknow -} diff --git a/core/objs/message/SearchObj.java b/core/objs/message/SearchObj.java index c6bcc366..76de0ffb 100644 --- a/core/objs/message/SearchObj.java +++ b/core/objs/message/SearchObj.java @@ -10,6 +10,7 @@ public class SearchObj { public String cantNext; public String cantLast; public String startSearch; + public String error1; public static SearchObj make() { SearchObj obj = new SearchObj(); diff --git a/core/objs/music/SongInfoObj.java b/core/objs/music/SongInfoObj.java index 5cb146b8..29e80929 100644 --- a/core/objs/music/SongInfoObj.java +++ b/core/objs/music/SongInfoObj.java @@ -1,9 +1,8 @@ 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.netapi.obj.music.trialinfo.freeTrialInfo; import com.coloryr.allmusic.server.core.objs.message.ARG; +import com.coloryr.allmusic.server.netapi.obj.music.trialinfo.freeTrialInfo; public class SongInfoObj { /** @@ -60,28 +59,18 @@ public class SongInfoObj { * 是否是Url歌曲 */ protected boolean isUrl; - /** - * 音乐类型 - */ - protected MediaType mediaType; - /** * 音乐API */ protected String api; - 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() { + } public SongInfoObj(String Author, String Name, String ID, String Alia, String Call, String Al, - boolean isList, long Length, String picUrl, boolean isTrial, freeTrialInfo trialInfo) { + boolean isList, long Length, String picUrl, boolean isTrial, freeTrialInfo trialInfo, + String api) { this.author = Author; this.name = Name; this.id = ID; @@ -93,7 +82,7 @@ public class SongInfoObj { this.length = Length; this.isTrial = isTrial; this.trialInfo = trialInfo; - this.mediaType = MediaType.Mp3; + this.api = api; } public boolean isUrl() { @@ -166,10 +155,6 @@ public class SongInfoObj { return name == null; } - public MediaType getMediaType() { - return mediaType; - } - public String getApi() { return api; } diff --git a/core/objs/music/TopSongInfoObj.java b/core/objs/music/TopSongInfoObj.java index 5a088de2..e78c66d2 100644 --- a/core/objs/music/TopSongInfoObj.java +++ b/core/objs/music/TopSongInfoObj.java @@ -1,13 +1,8 @@ package com.coloryr.allmusic.server.core.objs.music; -import com.coloryr.allmusic.server.core.objs.MediaType; import com.coloryr.allmusic.server.netapi.obj.music.trialinfo.freeTrialInfo; public class TopSongInfoObj extends SongInfoObj { - public TopSongInfoObj() { - super(null, null, 0, MediaType.Unknow); - } - public void setAl(String al) { this.al = al; } diff --git a/core/sql/DataSql.java b/core/sql/DataSql.java index d634a69d..99293ca8 100644 --- a/core/sql/DataSql.java +++ b/core/sql/DataSql.java @@ -53,7 +53,7 @@ public class DataSql { private static final String table1 = "CREATE TABLE IF NOT EXISTS \"allmusic_list\" (\n" + " \"id\" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,\n" + - " \"sid\" TEXT(40)\n" + + " \"sid\" TEXT(40),\n" + " \"api\" TEXT(40)\n" + ");"; @@ -69,7 +69,7 @@ public class DataSql { private static final String table4 = "CREATE TABLE IF NOT EXISTS \"allmusic_banlist\" (\n" + " \"id\" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,\n" + - " \"sid\" TEXT(40)\n" + + " \"sid\" TEXT(40),\n" + " \"api\" TEXT(40)\n" + ");"; diff --git a/netapi/LyricDecoder.java b/netapi/LyricDecoder.java index d9891832..40aa04aa 100644 --- a/netapi/LyricDecoder.java +++ b/netapi/LyricDecoder.java @@ -1,9 +1,9 @@ package com.coloryr.allmusic.server.netapi; import com.coloryr.allmusic.server.core.AllMusic; -import com.coloryr.allmusic.server.netapi.obj.music.lyric.WLyricObj; import com.coloryr.allmusic.server.core.objs.music.LyricItemObj; import com.coloryr.allmusic.server.core.utils.Function; +import com.coloryr.allmusic.server.netapi.obj.music.lyric.WLyricObj; import java.util.*; import java.util.regex.Matcher; @@ -15,9 +15,11 @@ public class LyricDecoder { public boolean isHave = false; public boolean isHaveK = false; public Map kly = new LinkedHashMap<>(); + public Map getTemp() { return temp; } + public Map getKLyric() { return kly; } diff --git a/netapi/NetiApiMain.java b/netapi/NetiApiMain.java index 463fe885..ca90cebd 100644 --- a/netapi/NetiApiMain.java +++ b/netapi/NetiApiMain.java @@ -2,15 +2,13 @@ package com.coloryr.allmusic.server.netapi; import com.coloryr.allmusic.server.core.AllMusic; import com.coloryr.allmusic.server.core.IMusicApi; -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.LyricSave; -import com.coloryr.allmusic.server.core.music.MusicHttpClient; 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.message.ARG; +import com.coloryr.allmusic.server.core.objs.music.SearchPageObj; +import com.coloryr.allmusic.server.core.objs.music.SongInfoObj; +import com.coloryr.allmusic.server.core.sql.DataSql; import com.coloryr.allmusic.server.core.utils.Function; import com.coloryr.allmusic.server.netapi.obj.music.info.InfoObj; import com.coloryr.allmusic.server.netapi.obj.music.list.DataObj; @@ -19,15 +17,8 @@ import com.coloryr.allmusic.server.netapi.obj.music.search.SearchDataObj; import com.coloryr.allmusic.server.netapi.obj.music.search.songs; import com.coloryr.allmusic.server.netapi.obj.music.trialinfo.TrialInfoObj; import com.coloryr.allmusic.server.netapi.obj.program.info.PrInfoObj; -import com.coloryr.allmusic.server.core.objs.message.ARG; -import com.coloryr.allmusic.server.core.objs.music.SearchPageObj; -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; @@ -99,7 +90,8 @@ public class NetiApiMain implements IMusicApi { TrialInfoObj obj = AllMusic.gson.fromJson(res.data, TrialInfoObj.class); return new SongInfoObj(temp.getAuthor(), temp.getName(), id, temp.getAlia(), player, temp.getAl(), isList, temp.getLength(), - temp.getPicUrl(), obj.isTrial(), obj.getFreeTrialInfo()); + temp.getPicUrl(), obj.isTrial(), obj.getFreeTrialInfo(), + getId()); } } return null; @@ -130,7 +122,7 @@ public class NetiApiMain implements IMusicApi { if (temp.isOk()) { return new SongInfoObj(temp.getAuthor(), temp.getName(), temp.getId(), temp.getAlia(), player, "电台", isList, temp.getLength(), - null, false, null); + null, false, null, getId()); } else { AllMusic.log.warning("§d[AllMusic3]§c歌曲信息获取为空"); } diff --git a/server/src/main/java/com/coloryr/allmusic/server/side/bukkit/FunCore.java b/server/src/main/java/com/coloryr/allmusic/server/side/bukkit/FunCore.java index 1d7e8d59..61c73dbb 100644 --- a/server/src/main/java/com/coloryr/allmusic/server/side/bukkit/FunCore.java +++ b/server/src/main/java/com/coloryr/allmusic/server/side/bukkit/FunCore.java @@ -4,8 +4,6 @@ import com.coloryr.allmusic.server.core.AllMusic; import org.bukkit.Bukkit; import org.bukkit.World; -import java.util.Random; - public class FunCore { public static void addMusic() { if (AllMusic.getConfig().funConfig.rain) {