Skip to content

Instantly share code, notes, and snippets.

@jan4984
Created October 16, 2017 06:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jan4984/3b5b6c40926b5bab99acc84e2a654273 to your computer and use it in GitHub Desktop.
Save jan4984/3b5b6c40926b5bab99acc84e2a654273 to your computer and use it in GitHub Desktop.
opus encoder decoder java binding
#include "jni.h"
JNIEXPORT jlong JNICALL
Java_com_XXX_opus_Encoder_create(JNIEnv* env
, jobject thiz)
{
(void)env;(void)thiz;
int error;
void* enc = (void*)opus_encoder_create(16000, 1, OPUS_APPLICATION_VOIP, &error);
if(error){
printf("opus create encoder failed:%d\n",error);
return 0;
}
return (jlong)enc;
}
JNIEXPORT void JNICALL
Java_com_XXX_opus_Encoder_destory(JNIEnv* env
, jobject thiz
, jlong handle)
{
(void)env;(void)thiz;
opus_encoder_destroy((OpusEncoder*)handle);
}
JNIEXPORT jint JNICALL
Java_com_XXX_opus_Encoder_encodeFrame(JNIEnv* env
, jobject thiz
, jlong handle
, jobject buf_pcm
, jint length_in_byte
, jobject buf_opus)
{
(void)thiz;
char* bbuf_pcm;
char* bbuf_opus;
bbuf_pcm = (*env)->GetDirectBufferAddress(env, buf_pcm);
bbuf_opus= (*env)->GetDirectBufferAddress(env, buf_opus);
int outc=opus_encode((OpusEncoder*)handle, bbuf_pcm, length_in_byte/2, &bbuf_opus[1], 256);
if(outc<0){
printf("opus encode error:%d\n",outc);
return (jint)outc;
}
bbuf_opus[0]=(char)outc;
return outc;
}
JNIEXPORT jlong JNICALL
Java_com_XXX_opus_Decoder_create(JNIEnv* env
, jobject thiz)
{
int error=0;
OpusDecoder* dec = opus_decoder_create(16000, 1, &error);
if (error) {
printf("create opus decoder failed:%d\n", error);
return 0;
}
return (jlong)dec;
}
JNIEXPORT void JNICALL
Java_com_iflytek_opus_Decoder_destory(JNIEnv* env, jobject thiz, jlong handle)
{
if (!handle) return;
opus_decoder_destroy((OpusDecoder*)handle);
}
JNIEXPORT jint JNICALL
Java_com_XXX_opus_Decoder_reset(JNIEnv* env, jobject thiz, jlong handle) {
if (!handle) return -1;
return opus_decoder_ctl((OpusDecoder*)handle, OPUS_RESET_STATE);
}
JNIEXPORT jint JNICALL
Java_com_XXX_opus_Decoder_decodeFrame(JNIEnv* env
, jobject thiz
, jlong handle
, jobject opus
, jint opus_bytes
, jobject pcm
, jint max_pcm_bytes)
{
char* bbuf_pcm;
char* bbuf_opus;
bbuf_pcm = (*env)->GetDirectBufferAddress(env, pcm);
bbuf_opus = (*env)->GetDirectBufferAddress(env, opus);
int offset = 0;
int pcm_offset = 0;
int pkg_len;
while (offset<opus_bytes && pcm_offset < max_pcm_bytes) {
pkg_len = bbuf_opus[offset];
int samples = opus_decode((OpusDecoder*)handle, (const unsigned char*)&bbuf_opus[offset + 1], pkg_len, (opus_int16*)&bbuf_pcm[pcm_offset], (max_pcm_bytes - pcm_offset) / 2, 0);
if (samples < 0) {
return samples;
}
offset += pkg_len+1;
pcm_offset += samples * 2;
}
return pcm_offset;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment