📄 floatsamplebuffer.java
字号:
/* * FloatSampleBuffer.java *//* * Copyright (c) 2000 by Florian Bomers <florian@bome.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 org.tritonus.sampled;import java.util.ArrayList;import java.util.Iterator;import java.util.Random;import javax.sound.sampled.AudioSystem;import javax.sound.sampled.AudioFormat;import javax.sound.sampled.AudioFileFormat;import javax.sound.sampled.AudioInputStream;import javax.sound.sampled.spi.AudioFileWriter;import org.tritonus.TDebug;/** * A class for small buffers of samples in linear, 32-bit * floating point format. All samples are normalized to the * interval [-1.0...1.0]. * <p> * It is supposed to be a replacement of the byte[] stream * architecture of JavaSound, especially for chains of * AudioInputStreams. Ideally, all involved AudioInputStreams * handle reading into a FloatSampleBuffer. * <p> * Using a FloatSampleBuffer for streaming has some advantages: * <ul> * <li>no conversions from bytes have to be done during processing * <li>the sample size in bits is irrelevant - normalized range * <li>higher quality for processing * <li>separated channels * <li>potentially less copying of audio data, as processing * of the float samples is generally done in-place. The same * instance of a FloatSampleBuffer may be used from the data source * to the final data sink. * </ul> * Simple benchmarks showed that the computational power * used by the conversion to and from float * is neglectible without dithering, and significantly higher * with dithering. An own implementation of a random number * generator may improve this. * <p> * It supports "lazy" deletion of samples and channels: * <ul> * <li>When the sample count is reduced, the arrays are not resized, but * only the member variable <code>sampleCount</code> is reduced. A subsequent * increase of the sample count (which will occur frequently), will check * that and eventually reuse the existing array. * <li>When a channel is deleted, it is not removed from memory but only * hidden. Subsequent insertions of a channel will check whether a hidden channel * can be reused. * </ul> * The lazy mechanism can save many array instantiation (and copy-) operations * for the sake of performance. All relevant methods exist in a second * version which allows explicitely to disable lazy deletion. * <p> * Use the <code>reset</code> functions to clear the memory and remove * hidden samples and channels. * <p> * Note that the lazy mechanism implies that the arrays returned * from <code>getChannel(int)</code> may have a greater size * than getSampleCount(). Consequently, be sure to never rely on the * length field of the sample arrays. * <p> * As an example, consider a chain of converters that all act * on the same instance of FloatSampleBuffer. Some converters * may decrease the sample count (e.g. sample rate converter) and * delete channels (e.g. PCM2PCM converter). So, processing of one * chunk will decrease both. For the next chunk, all starts * from the beginning. With the lazy mechanism, all float arrays * are only created once for processing all chunks.<br> * Having lazy disabled would require for each chunk that is processed * <ol> * <li>new instantiation of all channel arrays * at the converter chain beginning as they have been * either deleted or decreased in size during processing of the * previous chunk, and * <li>re-instantiation of all channel arrays for * the reduction of the sample count. * </ol> * <p> * By default, this class uses dithering for reduction * of sample width (e.g. original data was 16bit, target * data is 8bit). As dithering may be needed in other cases * (especially when the float samples are processed using DSP * algorithms), or it is preferred to switch it off, * dithering can be explicitely switched on or off with * the method setDitherMode(int).<br> * For a discussion about dithering, see * <a href="http://www.iqsoft.com/IQSMagazine/BobsSoapbox/Dithering.htm"> * here</a> and * <a href="http://www.iqsoft.com/IQSMagazine/BobsSoapbox/Dithering2.htm"> * here</a>. * * @author Florian Bomers */public class FloatSampleBuffer { /** Whether the functions without lazy parameter are lazy or not. */ private static final boolean LAZY_DEFAULT=true; private ArrayList channels=new ArrayList(); // contains for each channel a float array private int sampleCount=0; private int channelCount=0; private float sampleRate=0; private int originalFormatType=0; /** Constant for setDitherMode: dithering will be enabled if sample size is decreased */ public static final int DITHER_MODE_AUTOMATIC=0; /** Constant for setDitherMode: dithering will be done */ public static final int DITHER_MODE_ON=1; /** Constant for setDitherMode: dithering will not be done */ public static final int DITHER_MODE_OFF=2; private static Random random=null; private float ditherBits=0.8f; private boolean doDither=false; // set in convertFloatToBytes // e.g. the sample rate converter may want to force dithering private int ditherMode=DITHER_MODE_AUTOMATIC; // sample width (must be in order !) private static final int F_8=1; private static final int F_16=2; private static final int F_24=3; private static final int F_32=4; private static final int F_SAMPLE_WIDTH_MASK=F_8 | F_16 | F_24 | F_32; // format bit-flags private static final int F_SIGNED=8; private static final int F_BIGENDIAN=16; // supported formats private static final int CT_8S=F_8 | F_SIGNED; private static final int CT_8U=F_8; private static final int CT_16SB=F_16 | F_SIGNED | F_BIGENDIAN; private static final int CT_16SL=F_16 | F_SIGNED; private static final int CT_24SB=F_24 | F_SIGNED | F_BIGENDIAN; private static final int CT_24SL=F_24 | F_SIGNED; private static final int CT_32SB=F_32 | F_SIGNED | F_BIGENDIAN; private static final int CT_32SL=F_32 | F_SIGNED; //////////////////////////////// initialization ///////////////////////////////// public FloatSampleBuffer() { this(0,0,1); } public FloatSampleBuffer(int channelCount, int sampleCount, float sampleRate) { init(channelCount, sampleCount, sampleRate, LAZY_DEFAULT); } public FloatSampleBuffer(byte[] buffer, int offset, int byteCount, AudioFormat format) { this(format.getChannels(), byteCount/(format.getSampleSizeInBits()/8*format.getChannels()), format.getSampleRate()); initFromByteArray(buffer, offset, byteCount, format); } protected void init(int channelCount, int sampleCount, float sampleRate) { init(channelCount, sampleCount, sampleRate, LAZY_DEFAULT); } protected void init(int channelCount, int sampleCount, float sampleRate, boolean lazy) { if (channelCount<0 || sampleCount<0) { throw new IllegalArgumentException( "Invalid parameters in initialization of FloatSampleBuffer."); } setSampleRate(sampleRate); if (getSampleCount()!=sampleCount || getChannelCount()!=channelCount) { createChannels(channelCount, sampleCount, lazy); } } private void createChannels(int channelCount, int sampleCount, boolean lazy) { this.sampleCount=sampleCount; // lazy delete of all channels. Intentionally lazy ! this.channelCount=0; for (int ch=0; ch<channelCount; ch++) { insertChannel(ch, false, lazy); } if (!lazy) { // remove hidden channels while (channels.size()>channelCount) { channels.remove(channels.size()-1); } } } public void initFromByteArray(byte[] buffer, int offset, int byteCount, AudioFormat format) { initFromByteArray(buffer, offset, byteCount, format, LAZY_DEFAULT); } public void initFromByteArray(byte[] buffer, int offset, int byteCount, AudioFormat format, boolean lazy) { if (offset+byteCount>buffer.length) { throw new IllegalArgumentException ("FloatSampleBuffer.initFromByteArray: buffer too small."); } boolean signed=format.getEncoding().equals(AudioFormat.Encoding.PCM_SIGNED); if (!signed && !format.getEncoding().equals(AudioFormat.Encoding.PCM_UNSIGNED)) { throw new IllegalArgumentException ("FloatSampleBuffer: only PCM samples are possible."); } int bytesPerSample=format.getSampleSizeInBits()/8; int bytesPerFrame=bytesPerSample*format.getChannels(); int thisSampleCount=byteCount/bytesPerFrame; init(format.getChannels(), thisSampleCount, format.getSampleRate(), lazy); int formatType=getFormatType(format.getSampleSizeInBits(), signed, format.isBigEndian()); // save format for automatic dithering mode originalFormatType=formatType; for (int ch=0; ch<format.getChannels(); ch++) { convertByteToFloat(buffer, offset, sampleCount, getChannel(ch), bytesPerFrame, formatType); offset+=bytesPerSample; // next channel } } public void initFromFloatSampleBuffer(FloatSampleBuffer source) { init(source.getChannelCount(), source.getSampleCount(), source.getSampleRate()); for (int ch=0; ch<getChannelCount(); ch++) { System.arraycopy(source.getChannel(ch), 0, getChannel(ch), 0, sampleCount); } } /** * deletes all channels, frees memory... * This also removes hidden channels by lazy remove. */ public void reset() { init(0,0,1, false); } /** * destroys any existing data and creates new channels. * It also destroys lazy removed channels and samples. */ public void reset(int channels, int sampleCount, float sampleRate) { init(channels, sampleCount, sampleRate, false); } //////////////////////////////// conversion back to bytes ///////////////////////////////// /** * returns the required size of the buffer * when convertToByteArray(..) is called */ public int getByteArrayBufferSize(AudioFormat format) { if (!format.getEncoding().equals(AudioFormat.Encoding.PCM_SIGNED) && !format.getEncoding().equals(AudioFormat.Encoding.PCM_UNSIGNED)) { throw new IllegalArgumentException ("FloatSampleBuffer: only PCM samples are possible."); } int bytesPerSample=format.getSampleSizeInBits()/8; int bytesPerFrame=bytesPerSample*format.getChannels(); return bytesPerFrame*getSampleCount(); } /** * throws exception when buffer is too small or <code>format</code> doesn't match */ public void convertToByteArray(byte[] buffer, int offset, AudioFormat format) { int byteCount=getByteArrayBufferSize(format); if (offset+byteCount>buffer.length) { throw new IllegalArgumentException ("FloatSampleBuffer.convertToByteArray: buffer too small."); } boolean signed=format.getEncoding().equals(AudioFormat.Encoding.PCM_SIGNED); if (!signed && !format.getEncoding().equals(AudioFormat.Encoding.PCM_UNSIGNED)) { throw new IllegalArgumentException ("FloatSampleBuffer.convertToByteArray: only PCM samples are allowed."); } if (format.getSampleRate()!=getSampleRate()) { throw new IllegalArgumentException ("FloatSampleBuffer.convertToByteArray: different samplerates."); } if (format.getChannels()!=getChannelCount()) { throw new IllegalArgumentException ("FloatSampleBuffer.convertToByteArray: different channel count."); } int bytesPerSample=format.getSampleSizeInBits()/8; int bytesPerFrame=bytesPerSample*format.getChannels(); int formatType=getFormatType(format.getSampleSizeInBits(), signed, format.isBigEndian()); for (int ch=0; ch<format.getChannels(); ch++) { convertFloatToByte(getChannel(ch), sampleCount, buffer, offset, bytesPerFrame, formatType); offset+=bytesPerSample; // next channel } } /** * Creates a new byte[] buffer and returns it. * Throws an exception when sample rate doesn't match. * @see #convertToByteArray(byte[], int, AudioFormat) * public byte[] convertToByteArray(AudioFormat format) { // throws exception when sampleRate doesn't match // creates a new byte[] buffer and returns it byte[] res=new byte[getByteArrayBufferSize(format)]; convertToByteArray(res, 0, format); return res; } //////////////////////////////// actions ///////////////////////////////// /** * Resizes this buffer. * <p>If <code>keepOldSamples</code> is true, as much as possible samples are * retained. If the buffer is enlarged, silence is added at the end. * If <code>keepOldSamples</code> is false, existing samples are discarded * and the buffer contains random samples. */ public void changeSampleCount(int newSampleCount, boolean keepOldSamples) { int oldSampleCount=getSampleCount(); Object[] oldChannels=null; if (keepOldSamples) { oldChannels=getAllChannels(); } init(getChannelCount(), newSampleCount, getSampleRate()); if (keepOldSamples) { // copy old channels and eventually silence out new samples int copyCount=newSampleCount<oldSampleCount? newSampleCount:oldSampleCount; for (int ch=0; ch<getChannelCount(); ch++) { float[] oldSamples=(float[]) oldChannels[ch]; float[] newSamples=(float[]) getChannel(ch); if (oldSamples!=newSamples) { // if this sample array was not object of lazy delete System.arraycopy(oldSamples, 0, newSamples, 0, copyCount); } if (oldSampleCount<newSampleCount) { // silence out new samples for (int i=oldSampleCount; i<newSampleCount; i++) { newSamples[i]=0.0f; } } } } } public void makeSilence() { // silence all channels if (getChannelCount()>0) { makeSilence(0); for (int ch=1; ch<getChannelCount(); ch++) { copyChannel(0, ch); } } } public void makeSilence(int channel) { float[] samples=getChannel(0); for (int i=0; i<getSampleCount(); i++) { samples[i]=0.0f; } } public void addChannel(boolean silent) { // creates new, silent channel insertChannel(getChannelCount(), silent); } /** * lazy insert of a (silent) channel at position <code>index</code>. */ public void insertChannel(int index, boolean silent) { insertChannel(index, silent, LAZY_DEFAULT); } /** * Inserts a channel at position <code>index</code>. * <p>If <code>silent</code> is true, the new channel will be silent. * Otherwise it will contain random data. * <p>If <code>lazy</code> is true, hidden channels which have at least getSampleCount() * elements will be examined for reusage as inserted channel.<br> * If <code>lazy</code> is false, still hidden channels are reused, * but it is assured that the inserted channel has exactly getSampleCount() elements, * thus not wasting memory. */ public void insertChannel(int index, boolean silent, boolean lazy) { int physSize=channels.size(); int virtSize=getChannelCount();
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -