Java Code Examples for java.nio.ShortBuffer#allocate()

The following examples show how to use java.nio.ShortBuffer#allocate() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: BufferUtils.java    From aion-germany with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Creates a new ShortBuffer with the same contents as the given ShortBuffer. The new ShortBuffer is seperate from the old one and changes are not reflected across. If you want to reflect changes,
 * consider using Buffer.duplicate().
 *
 * @param buf
 *            the ShortBuffer to copy
 * @return the copy
 */
public static ShortBuffer clone(ShortBuffer buf) {
	if (buf == null) {
		return null;
	}
	buf.rewind();

	ShortBuffer copy;
	if (buf.isDirect()) {
		copy = createShortBuffer(buf.limit());
	}
	else {
		copy = ShortBuffer.allocate(buf.limit());
	}
	copy.put(buf);

	return copy;
}
 
Example 2
Source File: BufferUtils.java    From Ultraino with MIT License 6 votes vote down vote up
/**
 * Creates a new ShortBuffer with the same contents as the given
 * ShortBuffer. The new ShortBuffer is separate from the old one and changes
 * are not reflected across. If you want to reflect changes, consider using
 * Buffer.duplicate().
 *
 * @param buf
 *            the ShortBuffer to copy
 * @return the copy
 */
public static ShortBuffer clone(ShortBuffer buf) {
    if (buf == null) {
        return null;
    }
    buf.rewind();

    ShortBuffer copy;
    if (isDirect(buf)) {
        copy = createShortBuffer(buf.limit());
    } else {
        copy = ShortBuffer.allocate(buf.limit());
    }
    copy.put(buf);

    return copy;
}
 
Example 3
Source File: BufferUtils.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 6 votes vote down vote up
/**
 * Creates a new ShortBuffer with the same contents as the given ShortBuffer.
 * The new ShortBuffer is seperate from the old one and changes are not
 * reflected across. If you want to reflect changes, consider using
 * Buffer.duplicate().
 *
 * @param buf
 *            the ShortBuffer to copy
 * @return the copy
 */
public static ShortBuffer clone(ShortBuffer buf) {
    if (buf == null) {
        return null;
    }
    buf.rewind();

    ShortBuffer copy;
    if (buf.isDirect()) {
        copy = createShortBuffer(buf.limit());
    } else {
        copy = ShortBuffer.allocate(buf.limit());
    }
    copy.put(buf);

    return copy;
}
 
Example 4
Source File: AudioConnection.java    From JDA with Apache License 2.0 6 votes vote down vote up
private ByteBuffer encodeToOpus(ByteBuffer rawAudio)
{
    ShortBuffer nonEncodedBuffer = ShortBuffer.allocate(rawAudio.remaining() / 2);
    ByteBuffer encoded = ByteBuffer.allocate(4096);
    for (int i = rawAudio.position(); i < rawAudio.limit(); i += 2)
    {
        int firstByte =  (0x000000FF & rawAudio.get(i));      //Promotes to int and handles the fact that it was unsigned.
        int secondByte = (0x000000FF & rawAudio.get(i + 1));

        //Combines the 2 bytes into a short. Opus deals with unsigned shorts, not bytes.
        short toShort = (short) ((firstByte << 8) | secondByte);

        nonEncodedBuffer.put(toShort);
    }
    ((Buffer) nonEncodedBuffer).flip();

    int result = Opus.INSTANCE.opus_encode(opusEncoder, nonEncodedBuffer, OpusPacket.OPUS_FRAME_SIZE, encoded, encoded.capacity());
    if (result <= 0)
    {
        LOG.error("Received error code from opus_encode(...): {}", result);
        return null;
    }

    ((Buffer) encoded).position(0).limit(result);
    return encoded;
}
 
Example 5
Source File: FSKEncoder.java    From android-fskmodem with GNU General Public License v3.0 5 votes vote down vote up
protected void allocateBufferSignal() {
	if (mConfig.pcmFormat == FSKConfig.PCM_8BIT) {
		mSignalPCM8 = ByteBuffer.allocate(mConfig.sampleRate); //1 second buffer
	}
	else if (mConfig.pcmFormat == FSKConfig.PCM_16BIT) {
		mSignalPCM16 = ShortBuffer.allocate(mConfig.sampleRate); //1 second buffer
	}
}
 
Example 6
Source File: BitmapPixels.java    From codeexamples-android with Eclipse Public License 1.0 5 votes vote down vote up
private static ShortBuffer makeBuffer(short[] src, int n) {
    ShortBuffer dst = ShortBuffer.allocate(n*n);
    for (int i = 0; i < n; i++) {
        dst.put(src);
    }
    dst.rewind();
    return dst;
}
 
Example 7
Source File: ProvidedImage.java    From settlers-remake with MIT License 5 votes vote down vote up
public ShortBuffer getData() {
	ShortBuffer data = ShortBuffer.allocate(image.getWidth() * image.getHeight());
	for (int y = 0; y < image.getHeight(); y++) {
		for (int x = 0; x < image.getWidth(); x++) {
			Color color = new Color(image.getRGB(x, y));
			data.put(color.toShortColor(1));
		}
	}
	data.rewind();
	return data;
}
 
Example 8
Source File: RandomAccessByteStreamTest.java    From succinct with Apache License 2.0 5 votes vote down vote up
public void testGetShort1() throws Exception {
  ShortBuffer buf = ShortBuffer.allocate(10);
  for (int i = 0; i < 10; i++) {
    buf.put((short) i);
  }
  FSDataInputStream is = TestUtils.getStream(buf);
  RandomAccessByteStream bs = new RandomAccessByteStream(is, 0, 20);
  for (int i = 0; i < 10; i++) {
    assertEquals(i, bs.getShort(i * 2));
  }
}
 
Example 9
Source File: RandomAccessByteStreamTest.java    From succinct with Apache License 2.0 5 votes vote down vote up
public void testGetShort() throws Exception {
  ShortBuffer buf = ShortBuffer.allocate(10);
  for (int i = 0; i < 10; i++) {
    buf.put((short) i);
  }
  FSDataInputStream is = TestUtils.getStream(buf);
  RandomAccessByteStream bs = new RandomAccessByteStream(is, 0, 20);
  for (int i = 0; i < 10; i++) {
    assertEquals(i, bs.getShort());
  }
}
 
Example 10
Source File: Decoder.java    From JDA with Apache License 2.0 5 votes vote down vote up
public short[] decodeFromOpus(AudioPacket decryptedPacket)
{
    int result;
    ShortBuffer decoded = ShortBuffer.allocate(4096);
    if (decryptedPacket == null)    //Flag for packet-loss
    {
        result = Opus.INSTANCE.opus_decode(opusDecoder, null, 0, decoded, OpusPacket.OPUS_FRAME_SIZE, 0);
        lastSeq = (char) -1;
        lastTimestamp = -1;
    }
    else
    {
        this.lastSeq = decryptedPacket.getSequence();
        this.lastTimestamp = decryptedPacket.getTimestamp();

        ByteBuffer encodedAudio = decryptedPacket.getEncodedAudio();
        int length = encodedAudio.remaining();
        int offset = encodedAudio.arrayOffset() + encodedAudio.position();
        byte[] buf = new byte[length];
        byte[] data = encodedAudio.array();
        System.arraycopy(data, offset, buf, 0, length);
        result = Opus.INSTANCE.opus_decode(opusDecoder, buf, buf.length, decoded, OpusPacket.OPUS_FRAME_SIZE, 0);
    }

    //If we get a result that is less than 0, then there was an error. Return null as a signifier.
    if (result < 0)
    {
        handleDecodeError(result);
        return null;
    }

    short[] audio = new short[result * 2];
    decoded.get(audio);
    return audio;
}
 
Example 11
Source File: OggOpusEnc.java    From speech-android-sdk with Apache License 2.0 5 votes vote down vote up
/**
 * Encode raw audio data into Opus format then call OpusWriter to write the Ogg packet
 *
 * @param rawAudio
 * @return
 * @throws IOException
 */
public int encodeAndWrite(byte[] rawAudio) throws IOException {
    int uploadedAudioSize = 0;
    ByteArrayInputStream ios = new ByteArrayInputStream(rawAudio);

    byte[] data = new byte[SpeechConfiguration.FRAME_SIZE*2];
    int bufferSize, read;

    while((read = ios.read(data)) > 0){
        bufferSize = read;
        byte[] pcmBuffer = new byte[read];
        System.arraycopy(data, 0, pcmBuffer, 0, read);

        ShortBuffer shortBuffer = ShortBuffer.allocate(bufferSize);
        for (int i = 0; i < read; i += 2) {
            int b1 = pcmBuffer[i] & 0xff;
            int b2 = pcmBuffer[i+1] << 8;
            shortBuffer.put((short) (b1 | b2));
        }
        shortBuffer.flip();
        ByteBuffer opusBuffer = ByteBuffer.allocate(bufferSize);

        int opus_encoded = JNAOpus.INSTANCE.opus_encode(this.opusEncoder, shortBuffer, SpeechConfiguration.FRAME_SIZE, opusBuffer, bufferSize);

        opusBuffer.position(opus_encoded);
        opusBuffer.flip();

        byte[] opusData = new byte[opusBuffer.remaining()];
        opusBuffer.get(opusData, 0, opusData.length);

        if (opus_encoded > 0) {
            uploadedAudioSize += opusData.length;
            writer.writePacket(opusData, 0, opusData.length);
        }
    }

    ios.close();
    return uploadedAudioSize;
}
 
Example 12
Source File: ChannelCountPcmAudioFilter.java    From lavaplayer with Apache License 2.0 5 votes vote down vote up
/**
 * @param inputChannels Number of input channels
 * @param outputChannels Number of output channels
 * @param downstream The next filter in line
 */
public ChannelCountPcmAudioFilter(int inputChannels, int outputChannels, UniversalPcmAudioFilter downstream) {
  this.downstream = downstream;
  this.inputChannels = inputChannels;
  this.outputChannels = outputChannels;
  this.outputBuffer = ShortBuffer.allocate(2048 * inputChannels);
  this.commonChannels = Math.min(outputChannels, inputChannels);
  this.channelsToAdd = outputChannels - commonChannels;
  this.inputSet = new short[inputChannels];
  this.splitFloatOutput = new float[outputChannels][];
  this.splitShortOutput = new short[outputChannels][];
  this.inputIndex = 0;
}
 
Example 13
Source File: OpusEncoder.java    From ts3j with Apache License 2.0 5 votes vote down vote up
public OpusEncoder(int sampleRate, int frameSize,
                   int channels, boolean bigEndian,
                   int maxPacketLength) {
    this.channels = channels;
    this.sampleRate = sampleRate;
    this.frameSize = frameSize;
    this.bigEndian = bigEndian;
    this.expectedByteSize = frameSize * channels * 2;

    if (!ArrayUtils.contains(OPUS_PERMITTED_FRAME_SIZES, frameSize))
        throw new IllegalArgumentException("Invalid Opus frame size: " + frameSize);

    if (!ArrayUtils.contains(OPUS_PERMITTED_SAMPLE_RATES, sampleRate))
        throw new IllegalArgumentException("Invalid Opus sample rate: " + sampleRate);

    if (!ArrayUtils.contains(OPUS_PERMITTED_CHANNEL_COUNTS, channels))
        throw new IllegalArgumentException("Invalid Opus channel count: " + channels);

    this.sourceShortBuffer = ShortBuffer.allocate(frameSize * channels);
    this.sourceByteBuffer = ByteBuffer.allocate(frameSize * channels * 2);
    this.sourceByteBuffer.order(bigEndian ? ByteOrder.BIG_ENDIAN : ByteOrder.LITTLE_ENDIAN);

    this.targetBuffer = ByteBuffer.allocate(maxPacketLength);

    IntBuffer errorBuffer = IntBuffer.allocate(1);

    encoder = Opus.INSTANCE.opus_encoder_create(
            sampleRate,
            channels,
            Opus.OPUS_APPLICATION_AUDIO,
            errorBuffer
    );

    if (encoder == null) throw new NullPointerException("encoder");

    OpusUtil.checkError(
            "opus_encoder_create",
            errorBuffer.get()
    );
}
 
Example 14
Source File: Recorder.java    From VideoAndroid with Apache License 2.0 5 votes vote down vote up
@Override
public void run() {
    android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_URGENT_AUDIO);

    // Audio
    int bufferSize;
    ShortBuffer audioData;
    int bufferReadResult;

    bufferSize = AudioRecord.getMinBufferSize(sampleAudioRateInHz,
            AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT);
    mAudioRecord = new AudioRecord(MediaRecorder.AudioSource.MIC, sampleAudioRateInHz,
            AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT, bufferSize);

    audioData = ShortBuffer.allocate(bufferSize);

    mAudioRecord.startRecording();

    /* ffmpeg_audio encoding loop */
    while (mRunAudioThread) {
        //获取音频数据
        bufferReadResult = mAudioRecord.read(audioData.array(), 0, audioData.capacity());
        audioData.limit(bufferReadResult);
        if (bufferReadResult > 0) {
            if(mFFmpegFrameRecorder != null && mRecording) {
                try {
                    mFFmpegFrameRecorder.recordSamples(audioData);      //写入音频数据
                } catch (FFmpegFrameRecorder.Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /* encoding finish, release recorder */
    if (mAudioRecord != null) {
        mAudioRecord.stop();
        mAudioRecord.release();
    }
}
 
Example 15
Source File: ShortNioDataBufferTest.java    From java with Apache License 2.0 4 votes vote down vote up
@Override
protected ShortDataBuffer allocate(long size) {
  return new ShortNioDataBuffer(ShortBuffer.allocate((int)size));
}
 
Example 16
Source File: FSKDecoder.java    From android-fskmodem with GNU General Public License v3.0 4 votes vote down vote up
protected void allocateBufferSignal() {
	mSignal = ShortBuffer.allocate(mSignalBufferSize);
}
 
Example 17
Source File: FSKDecoder.java    From android-fskmodem with GNU General Public License v3.0 4 votes vote down vote up
protected void allocateBufferFrame() {
	mFrame = ShortBuffer.allocate(mConfig.samplesPerBit); // one frame contains one bit
}
 
Example 18
Source File: OggOpusEnc.java    From android-sdk with Apache License 2.0 4 votes vote down vote up
/**
 * Encode raw audio data into Opus format then call OpusWriter to write the Ogg packet.
 *
 * @param rawAudio the raw audio
 * @return the int
 * @throws IOException Signals that an I/O exception has occurred.
 */
public int encodeAndWrite(byte[] rawAudio) throws IOException {
  int uploadedAudioSize = 0;
  ByteArrayInputStream ios = new ByteArrayInputStream(rawAudio);

  byte[] data = new byte[SpeechConfiguration.FRAME_SIZE * 2];
  int bufferSize, read;

  while ((read = ios.read(data)) > 0) {
    bufferSize = read;
    byte[] pcmBuffer = new byte[read];
    System.arraycopy(data, 0, pcmBuffer, 0, read);

    ShortBuffer shortBuffer = ShortBuffer.allocate(bufferSize);
    for (int i = 0; i < read; i += 2) {
      int b1 = pcmBuffer[i] & 0xff;
      int b2 = pcmBuffer[i + 1] << 8;
      shortBuffer.put((short) (b1 | b2));
    }
    shortBuffer.flip();
    ByteBuffer opusBuffer = ByteBuffer.allocate(bufferSize);

    int opus_encoded = JNAOpus.INSTANCE.opus_encode(this.opusEncoder, shortBuffer, SpeechConfiguration.FRAME_SIZE,
            opusBuffer, bufferSize);

    opusBuffer.position(opus_encoded);
    opusBuffer.flip();

    byte[] opusData = new byte[opusBuffer.remaining()];
    opusBuffer.get(opusData, 0, opusData.length);

    if (opus_encoded > 0) {
      uploadedAudioSize += opusData.length;
      // System.out.println("This is where I'd write some data. " + uploadedAudioSize + " to be specific.");
      writer.writePacket(opusData, 0, opusData.length);
    }
  }

  ios.close();

  return uploadedAudioSize;
}
 
Example 19
Source File: NullImage.java    From settlers-remake with MIT License 4 votes vote down vote up
private NullImage() {
	super(ShortBuffer.allocate(1), 1, 1, 0, 0, "placeholder/null");
}
 
Example 20
Source File: SettlerImage.java    From settlers-remake with MIT License 4 votes vote down vote up
private void generateUData() {
	toffsetX = offsetX;
	toffsetY = offsetY;

	int tx = offsetX+width;
	int ty = offsetY+height;

	if(torso != null) {
		if(torso.offsetX < toffsetX) toffsetX = torso.offsetX;
		if(torso.offsetY < toffsetY) toffsetY = torso.offsetY;
		if(torso.offsetX+torso.width > tx) tx = torso.offsetX+torso.width;
		if(torso.offsetY+torso.height > ty) ty = torso.offsetY+torso.height;
	}

	if(shadow != null) {
		if(shadow.offsetX < toffsetX) toffsetX = shadow.offsetX;
		if(shadow.offsetY < toffsetY) toffsetY = shadow.offsetY;
		if(shadow.offsetX+shadow.width > tx) tx = shadow.offsetX+shadow.width;
		if(shadow.offsetY+shadow.height > ty) ty = shadow.offsetY+shadow.height;
	}

	twidth = tx-toffsetX;
	theight = ty-toffsetY;

	tdata = ShortBuffer.allocate(twidth * theight);

	short[] temp = new short[0];

	if(shadow != null) {
		int hoffX = shadow.offsetX-toffsetX;
		int hoffY = shadow.offsetY-toffsetY;

		if(temp.length < shadow.width) temp = new short[shadow.width];

		for(int y = 0;y != shadow.height;y++) {
			shadow.data.position(y*shadow.width);
			shadow.data.get(temp, 0, shadow.width);

			for(int x = 0;x != shadow.width;x++) {
				if(temp[x] == 0) continue;
				tdata.put((y+hoffY)*twidth+hoffX+x, (short)((temp[x]&0xF)<<8)); // move alpha to green
			}
		}
	}

	if(torso != null) {
		int toffX = torso.offsetX-toffsetX;
		int toffY = torso.offsetY-toffsetY;

		if(temp.length < torso.width) temp = new short[torso.width];

		for(int y = 0;y != torso.height;y++) {
			torso.data.position(y*torso.width);
			torso.data.get(temp, 0, torso.width);

			for(int x = 0;x != torso.width;x++) {
				if(temp[x] == 0) continue;
				tdata.put((y+toffY)*twidth+toffX+x, (short) ((temp[x]&0xF0)|0xF000)); // strip out everything except blue channel and set full red channel
			}
		}
	}

	int soffX = offsetX-toffsetX;
	int soffY = offsetY-toffsetY;

	if(temp.length < width) temp = new short[width];

	for(int y = 0;y != height;y++) {
		data.position(y*width);
		data.get(temp, 0, width);

		for(int x = 0;x != width;x++) {
			if(temp[x] != 0) tdata.put((y+soffY)*twidth+soffX+x, temp[x]);
		}
	}
}