JNIEXPORT jint JNICALL Java_org_echocat_jopus_OpusEncoderJNI_encode
    (JNIEnv *env, jclass thisClass, jlong handle, jshortArray pcm, jint frameSize, jbyteArray packet, jint packetLength) {

    int result = 0;

    if (Java_org_echocat_jogg_OggJNISupport_checkNotNull(env, pcm) && Java_org_echocat_jogg_OggJNISupport_checkNotNull(env, packet)) {
        jboolean npcmIsCopy = 0;
        short* npcm = (*env)->GetPrimitiveArrayCritical(env, pcm, &npcmIsCopy);
        if (npcm != NULL) {
            jboolean npacketIsCopy = 0;
            char* npacket = (*env)->GetPrimitiveArrayCritical(env, packet, &npacketIsCopy);
            if (npacket != NULL) {
                result = opus_encode((OpusEncoder*) handle, npcm, frameSize, npacket, packetLength);
                (*env)->ReleasePrimitiveArrayCritical(env, packet, npacket, 0);

                Java_org_echocat_jogg_OggJNISupport_checkResponse(env, result);
            } else {
                Java_org_echocat_jogg_OggJNISupport_throwOutOfMemoryError(env);
            }
            (*env)->ReleasePrimitiveArrayCritical(env, pcm, npcm, JNI_ABORT);
        } else {
            Java_org_echocat_jogg_OggJNISupport_throwOutOfMemoryError(env);
        }
    }

    return result;
}
Esempio n. 2
0
static switch_status_t switch_opus_encode(switch_codec_t *codec,
										  switch_codec_t *other_codec,
										  void *decoded_data,
										  uint32_t decoded_data_len,
										  uint32_t decoded_rate, void *encoded_data, uint32_t *encoded_data_len, uint32_t *encoded_rate,
										  unsigned int *flag)
{
	struct opus_context *context = codec->private_info;
	int bytes = 0;
	int len = (int) *encoded_data_len;

	if (!context) {
		return SWITCH_STATUS_FALSE;
	}

	if (len > 1275) len = 1275;

	bytes = opus_encode(context->encoder_object, (void *) decoded_data, decoded_data_len / 2, (unsigned char *) encoded_data, len);

	if (bytes > 0) {
		*encoded_data_len = (uint32_t) bytes;
		return SWITCH_STATUS_SUCCESS;
	}

	switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Encoder Error!\n");
	return SWITCH_STATUS_GENERR;
}
Esempio n. 3
0
static switch_status_t switch_opus_encode(switch_codec_t *codec,
										  switch_codec_t *other_codec,
										  void *decoded_data,
										  uint32_t decoded_data_len,
										  uint32_t decoded_rate, void *encoded_data, uint32_t *encoded_data_len, uint32_t *encoded_rate,
										  unsigned int *flag)
{
	struct opus_context *context = codec->private_info;
	int bytes = 0;
	int len = (int) *encoded_data_len;

	if (!context) {
		return SWITCH_STATUS_FALSE;
	}
	
	bytes = opus_encode(context->encoder_object, (void *) decoded_data, context->enc_frame_size, (unsigned char *) encoded_data, len);
	
	if (bytes > 0) {
		*encoded_data_len = (uint32_t) bytes;
		return SWITCH_STATUS_SUCCESS;
	}

	switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Encoder Error: %s Decoded Datalen %u Codec NumberChans %u Len %u DecodedDate %p EncodedData %p ContextEncoderObject %p!\n", opus_strerror(bytes),decoded_data_len,codec->implementation->number_of_channels,len,(void *) decoded_data,(void *) encoded_data,(void *) context->encoder_object);

	return SWITCH_STATUS_GENERR;
}
Esempio n. 4
0
/**
 * @brief Encode audio frame
 *
 * @param av Handler
 * @param dest dest
 * @param dest_max Max dest size
 * @param frame The frame
 * @param frame_size The frame size
 * @return int
 * @retval ToxAvError On error.
 * @retval >0 On success
 */
int toxav_prepare_audio_frame ( ToxAv *av, int32_t call_index, uint8_t *dest, int dest_max, const int16_t *frame,
                                int frame_size)
{
    if (cii(call_index, av->msi_session) || !av->calls[call_index].call_active) {
        LOGGER_WARNING("Action on inactive call: %d", call_index);
        return ErrorNoCall;
    }

    CallSpecific *call = &av->calls[call_index];
    pthread_mutex_lock(&call->mutex);


    if (!call->call_active) {
        pthread_mutex_unlock(&call->mutex);
        LOGGER_WARNING("Action on inactive call: %d", call_index);
        return ErrorNoCall;
    }

    int32_t rc = opus_encode(call->cs->audio_encoder, frame, frame_size, dest, dest_max);
    pthread_mutex_unlock(&call->mutex);

    if (rc < 0) {
        LOGGER_ERROR("Failed to encode payload: %s\n", opus_strerror(rc));
        return ErrorInternal;
    }

    return rc;
}
Esempio n. 5
0
/* Send audio to the group chat.
 *
 * return 0 on success.
 * return -1 on failure.
 */
int group_send_audio(Group_Chats *g_c, int groupnumber, const int16_t *pcm, unsigned int samples, uint8_t channels,
                     unsigned int sample_rate)
{
    Group_AV *group_av = group_get_object(g_c, groupnumber);

    if (!group_av)
        return -1;

    if (channels != 1 && channels != 2)
        return -1;

    //TODO: allow different sample rates
    if (sample_rate != 48000)
        return -1;

    if (!group_av->audio_encoder || group_av->audio_channels != channels || group_av->audio_sample_rate != sample_rate) {
        group_av->audio_channels = channels;
        group_av->audio_sample_rate = sample_rate;
        group_av->audio_bitrate = 64000; //TODO: add way of adjusting bitrate

        if (recreate_encoder(group_av) == -1)
            return -1;
    }

    uint8_t encoded[1024];
    int32_t size = opus_encode(group_av->audio_encoder, pcm, samples, encoded, sizeof(encoded));

    if (size <= 0)
        return -1;

    return send_audio_packet(g_c, groupnumber, encoded, size);
}
Esempio n. 6
0
static int encode(struct aucodec_st *st, struct mbuf *dst, struct mbuf *src)
{
	int len;

	if (!mbuf_get_left(src))
		return 0;

	if (mbuf_get_left(src) != st->fsize) {
		DEBUG_WARNING("encode: got %d bytes, expected %d\n",
			      mbuf_get_left(src), st->fsize);
		return EINVAL;
	}

	if (mbuf_get_space(dst) < MAX_PACKET) {
		int err = mbuf_resize(dst, dst->pos + MAX_PACKET);
		if (err)
			return err;
	}

	len = opus_encode(st->enc, (short *)mbuf_buf(src), st->frame_size,
			  mbuf_buf(dst), (int)mbuf_get_space(dst));
	if (len < 0) {
		DEBUG_WARNING("encode error: %d (%u bytes)\n", len,
			      mbuf_get_left(src));
		return EPROTO;
	}

	src->pos = src->end;
	dst->end = dst->pos + len;

	return 0;
}
Esempio n. 7
0
WebRtc_Word16 WebRtcOpus_Encode(OPUS_encinst_t* encInst,
                                WebRtc_Word16* input,
                                WebRtc_Word16* output,
                                WebRtc_Word16 len,
                                WebRtc_Word16 byteLen){
  
  return opus_encode(((OPUS_Enc_Inst_t*)encInst)->enc, (short*)input, len, (unsigned char*)output, MAX_PACKET);
}
Esempio n. 8
0
int opus_enc_encode(opus_enc *opus, short *pcm_buf, char *enc_buf, int size)
{

    int w = 0;
	ogg_packet op;
	int ret;

    if(size == 0)
        return 0;

	//printf("Opus Encoder encoding %d samples\n", size);

	if (opus->encoder == NULL) {
		printf("Opus Encoder NULL wtf?\n");
		return 0;
	}
	
	while (ogg_stream_flush(&opus->os, &opus->og) != 0) {
        memcpy(enc_buf+w, opus->og.header, opus->og.header_len);
        w += opus->og.header_len;
        memcpy(enc_buf+w, opus->og.body, opus->og.body_len);
        w += opus->og.body_len;
	}
	
	if (opus->last_bitrate != opus->bitrate) {
		if ((opus->bitrate < 9600) || (opus->bitrate > 320000)) {
			opus->bitrate = DEFAULT_OPUS_BITRATE;
		}	
		opus_encoder_ctl (opus->encoder, OPUS_SET_BITRATE(opus->bitrate));
		opus->last_bitrate = opus->bitrate;
	}
	

	ret = opus_encode (opus->encoder, pcm_buf, 960, opus->buffer, 2048 * 4);
	
	//printf("Opus Encoder encoding %d samples, got back %d bytes\n", size, ret);
	
	op.b_o_s = 0;
	op.e_o_s = 0;
	op.granulepos = opus->granulepos;
	op.packetno = opus->packetno++;
	op.packet = opus->buffer;
	op.bytes = ret;

	opus->granulepos += 960;

	ogg_stream_packetin (&opus->os, &op);
	
	while (ogg_stream_flush(&opus->os, &opus->og) != 0) {
        memcpy(enc_buf+w, opus->og.header, opus->og.header_len);
        w += opus->og.header_len;
        memcpy(enc_buf+w, opus->og.body, opus->og.body_len);
        w += opus->og.body_len;
	}
	
    return w;
}
Esempio n. 9
0
/**
 * @brief Encode and send audio frame.
 *
 * @param av Handler.
 * @param frame The frame (raw 16 bit signed pcm with AUDIO_CHANNELS channels audio.)
 * @param frame_size Its size in number of frames/samples (one frame/sample is 16 bits or 2 bytes)
 *                   frame size should be AUDIO_FRAME_SIZE.
 * @return int
 * @retval 0 Success.
 * @retval ToxAvError On error.
 */
inline__ int toxav_send_audio ( ToxAv *av, const int16_t *frame, int frame_size)
{
    uint8_t temp_data[RTP_PAYLOAD_SIZE];
    int32_t ret = opus_encode(av->cs->audio_encoder, frame, frame_size, temp_data, sizeof(temp_data));

    if (ret <= 0)
        return ErrorInternal;

    return toxav_send_rtp_payload(av, TypeAudio, temp_data, ret);
}
Esempio n. 10
0
int OpusEncode::Encode(const short* input_buffer, int input_samples,
                        char* output_buffer, int output_bufsize)
{
    assert(m_encoder);
    assert(input_buffer);
    assert(output_buffer);
    return opus_encode(m_encoder, input_buffer, input_samples, 
                       reinterpret_cast<unsigned char*>(output_buffer),
                       output_bufsize);
}
Esempio n. 11
0
EMSCRIPTEN_KEEPALIVE
int encode(Encoder* encoder, int length, int frame_size) {
    to_big_endian(encoder->in_pcm, length, encoder->in_big_endian);
    return opus_encode(
        encoder->encoder,
        encoder->in_big_endian,
        frame_size,
        encoder->out_encoded,
        MAX_OUTPUT_BYTES
    );
}
Esempio n. 12
0
size_t Opus::encode(const std::vector<std::vector<SFLAudioSample> > &pcm, uint8_t *data, size_t len)
{
    if (data == nullptr) return 0;
    int ret;
    if (channelsCur_ == 1) {
        ret = opus_encode(encoder_, pcm[0].data(), FRAME_SIZE, data, len);
    } else {
        std::array<SFLAudioSample, 2 * FRAME_SIZE> ibuf; // interleave on stack, 1.875KiB used;
        for (unsigned i = 0; i < FRAME_SIZE; i++) {
            ibuf[2 * i] = pcm[0][i];
            ibuf[2 * i + 1] = pcm[1][i];
        }
        ret = opus_encode(encoder_, ibuf.data(), FRAME_SIZE, data, len);
    }
    if (ret < 0) {
        std::cerr << opus_strerror(ret) << std::endl;
        ret = 0;
    }
    return ret;
}
Esempio n. 13
0
/**
 * @brief Encode audio frame
 *
 * @param av Handler
 * @param dest dest
 * @param dest_max Max dest size
 * @param frame The frame
 * @param frame_size The frame size
 * @return int
 * @retval ToxAvError On error.
 * @retval >0 On success
 */
inline__ int toxav_prepare_audio_frame ( ToxAv *av, int32_t call_index, uint8_t *dest, int dest_max,
        const int16_t *frame, int frame_size)
{
    int32_t rc = opus_encode(av->calls[call_index].cs->audio_encoder, frame, frame_size, dest, dest_max);

    if (rc < 0) {
        fprintf(stderr, "Failed to encode payload: %s\n", opus_strerror(rc));
        return ErrorInternal;
    }

    return rc;
}
Esempio n. 14
0
void Encoder::encode(const QByteArray& src)
{
    buffer_ += src;
    int buffer_size = framesize_ * (2 * sizeof(quint16));
    while (buffer_.size() >= buffer_size) {
        QByteArray encodedBuf(4000, 0);
        opus_int32 length = opus_encode(encoder_, reinterpret_cast<const opus_int16*>(buffer_.data()), framesize_,
                    reinterpret_cast<unsigned char*>(encodedBuf.data()), encodedBuf.size());
        position_ += framesize_;
        encodedBuf.resize(length);
        emit encoded(encodedBuf, position_);
        buffer_ = buffer_.mid(buffer_size);
    }
}
Esempio n. 15
0
/**
 * @brief Encode audio frame
 *
 * @param av Handler
 * @param dest dest
 * @param dest_max Max dest size
 * @param frame The frame
 * @param frame_size The frame size
 * @return int
 * @retval ToxAvError On error.
 * @retval >0 On success
 */
inline__ int toxav_prepare_audio_frame ( ToxAv *av, int32_t call_index, uint8_t *dest, int dest_max,
        const int16_t *frame, int frame_size)
{
    if (cii(call_index, av->msi_session)) return ErrorNoCall;

    int32_t rc = opus_encode(av->calls[call_index].cs->audio_encoder, frame, frame_size, dest, dest_max);

    if (rc < 0) {
        LOGGER_ERROR("Failed to encode payload: %s\n", opus_strerror(rc));
        return ErrorInternal;
    }

    return rc;
}
Esempio n. 16
0
int AudioInput::encodeOpusFrame(short *source, int size, EncodingOutputBuffer& buffer) {
	int len = 0;
#ifdef USE_OPUS
	if (!bPreviousVoice)
		opus_encoder_ctl(opusState, OPUS_RESET_STATE, NULL);

	opus_encoder_ctl(opusState, OPUS_SET_BITRATE(iAudioQuality));

	len = opus_encode(opusState, source, size, &buffer[0], buffer.size());
	const int tenMsFrameCount = (size / iFrameSize);
	iBitrate = (len * 100 * 8) / tenMsFrameCount;
#endif
	return len;
}
Esempio n. 17
0
int AudioInput::encodeOpusFrame(short *source, int size, EncodingOutputBuffer& buffer) {
	int len = 0;
#ifdef USE_OPUS
	if (bResetEncoder) {
		opus_encoder_ctl(opusState, OPUS_RESET_STATE, NULL);
		bResetEncoder = false;
	}

	opus_encoder_ctl(opusState, OPUS_SET_BITRATE(iAudioQuality));

	len = opus_encode(opusState, source, size, &buffer[0], static_cast<opus_int32>(buffer.size()));
	const int tenMsFrameCount = (size / iFrameSize);
	iBitrate = (len * 100 * 8) / tenMsFrameCount;
#endif
	return len;
}
int16_t WebRtcOpus_EncodeNative(OpusEncInst *inst,
                                int16_t     *audioIn,
                                uint8_t     *encoded,
                                int16_t      encodedLenByte,
                                int16_t      len)
{
  opus_int16 *audio = (opus_int16 *)audioIn;
  unsigned char *coded = encoded;

  int res = opus_encode(inst->encoder, audio, len, coded, encodedLenByte);

  if (res > 0) {
    return res;
  }

  return -1;
}
Esempio n. 19
0
int16_t WebRtcOpus_Encode(OpusEncInst* inst, int16_t* audio_in, int16_t samples,
                          int16_t length_encoded_buffer, uint8_t* encoded) {
  opus_int16* audio = (opus_int16*) audio_in;
  unsigned char* coded = encoded;
  int res;

  if (samples > 48 * kWebRtcOpusMaxEncodeFrameSizeMs) {
    return -1;
  }

  res = opus_encode(inst->encoder, audio, samples, coded,
                    length_encoded_buffer);

  if (res > 0) {
    return res;
  }
  return -1;
}
Esempio n. 20
0
    virtual bool Transcode(const void * fromPtr,
                             unsigned & fromLen,
                                 void * toPtr,
                             unsigned & toLen,
                             unsigned & flags)
    {
      opus_int32 result = opus_encode(m_encoder,
                                      (const opus_int16 *)fromPtr, fromLen/m_channels/2,
                                      (unsigned char *)toPtr, toLen);
      if (result < 0) {
        PTRACE(1, MY_CODEC_LOG, "Encoder error " << result << ' ' << opus_strerror(result));
        return false;
      }

      toLen = result;
      fromLen = opus_packet_get_nb_samples((const unsigned char *)toPtr, toLen, m_sampleRate)*m_channels*2;
      return true;
    }
Esempio n. 21
0
int pcm16_2_opus( unsigned char* out_buf, unsigned char* in_buf, unsigned int size,
		  unsigned int channels, unsigned int rate, long h_codec )
{
  opus_state_t* codec_inst;
  int res;

  if (!h_codec){
    ERROR("opus codec not initialized.\n");
    return 0;
  }
  codec_inst = (opus_state_t*)h_codec;

  res = opus_encode(codec_inst->opus_enc, (opus_int16*)in_buf, size/2/channels, out_buf, AUDIO_BUFFER_SIZE);
  /* returns bytes in encoded frame */

  /* DBG ("OPUS encode: size: %d, chan: %d, rate: %d, result %d.\n", size, channels, rate, res); */
  return res;
}
Esempio n. 22
0
CODEC_API int PLG_ENCODE_V1(opus_48000)(void* opaqueCodecContext, const void* pcmAudioBuffer,
                                        unsigned pcmAudioSamples, int* samplesConsumed,
                                        void* encodedData, unsigned maxCodedDataSize,
                                        int* encodedDataSize, unsigned* sendNow)
{
    int status = RPLG_INVALID_ARGUMENT;
    assert(opaqueCodecContext);
    struct MpCodecOpusCodecState* encoderContext = (struct MpCodecOpusCodecState*) opaqueCodecContext;
    assert(encoderContext->mCodecType == CODEC_ENCODE);
    assert(encoderContext->mpEncoderContext);
    if(encoderContext->mpEncoderContext)
    {

        int encodedBytes = opus_encode(encoderContext->mpEncoderContext, 
                                       pcmAudioBuffer,
                                       pcmAudioSamples,
                                       encodedData,
                                       maxCodedDataSize);
        if(encodedBytes >= 0)
        {
            status = RPLG_SUCCESS;
            *encodedDataSize = encodedBytes;
            *samplesConsumed = pcmAudioSamples;
            *sendNow = TRUE;
        }
        else
        {
            status = OpusToPluginError(encodedBytes);
            *encodedDataSize = 0;
            *samplesConsumed = 0;
            *sendNow = FALSE;
            mppLogError("opus_encode buffer: %p, samples: %d, opus error: %d status: %d",
                        pcmAudioBuffer, pcmAudioSamples, encodedBytes, status);
        }
    }

    else
    {
        mppLogError("opus_48000 encode called with NULL context");
    }

    return(status);
}
Esempio n. 23
0
int opus_encode_frm(struct auenc_state *aes, uint8_t *buf, size_t *len,
		    const int16_t *sampv, size_t sampc)
{
	opus_int32 n;

	if (!aes || !buf || !len || !sampv)
		return EINVAL;

	n = opus_encode(aes->enc, sampv, (int)(sampc/aes->ch),
			buf, (opus_int32)(*len));
	if (n < 0) {
		warning("opus: encode error: %s\n", opus_strerror((int)n));
		return EPROTO;
	}

	*len = n;

	return 0;
}
Esempio n. 24
0
boolean SoundWavData::toOpus(BinaryData& dst)
{
	EndianSafeBinaryDataAccessor a(dst);

	MyOpusFileHeader header;
	header.channels = _channels;
	header.packetSize = SOUNDLIB_OPUS_PACKET_SIZE * _channels;
	header.save(a);

	int err;
	OpusEncoder* enc = opus_encoder_create(header.framesPerSecond, header.channels, OPUS_APPLICATION_AUDIO, &err);
	if(!enc){
		logError << "opus_encoder_create ";
		return false;
	}

	uint bitrate = AUDIOLIB_FRAME_RATE / SOUNDLIB_OPUS_PACKET_FRAMES * 8 * _channels * SOUNDLIB_OPUS_PACKET_SIZE;
	err = opus_encoder_ctl(enc, OPUS_SET_BITRATE(bitrate));
	if(err != OPUS_OK){
		logError << "opus_encoder_ctl OPUS_SET_BITRATE " << bitrate;
	}
		
	byte buff[AUDIOLIB_PACKET_FRAMES * AUDIOLIB_MAX_CHANNELS * 2];
	Assert(AUDIOLIB_PACKET_FRAMES * AUDIOLIB_MAX_CHANNELS * 2 > header.packetSize);
	uint unusedbytes = 0;
	for(uint fr=0; fr + header.packetFrames <= _frames; fr += header.packetFrames)
	{
		int s = opus_encode(enc, _data + _channels * fr, header.packetFrames, buff, header.packetSize);
		Assert(s > 0);

		int d = header.packetSize - s;
		if(d){
			memoryClear(buff + s, d);
			unusedbytes += d; 
		}
			
		a.write(buff, header.packetSize);
	}
	opus_encoder_destroy(enc);
	logInfo << "unused bytes " << unusedbytes;
	return true;
}
Esempio n. 25
0
int tc_opus_encode(OpusEncoder *encoder, unsigned char *pcm_bytes, unsigned char *cbits, int channels, int frame_size)
{
      int i;
      int nbBytes;
      opus_int16 in[frame_size*channels];

      /* Convert from little-endian ordering. */
      for (i=0;i<channels*frame_size;i++)
         in[i]=pcm_bytes[2*i+1]<<8|pcm_bytes[2*i];


      nbBytes = opus_encode(encoder, in, frame_size, cbits, frame_size*channels*2);
      if (nbBytes<0)
      {
         pa_log_error("encode failed: %s", opus_strerror(nbBytes));
         return EXIT_FAILURE;
      }

      return nbBytes;
}
Esempio n. 26
0
AM_UINT CAudioCodecOpus::encode(AM_U8 *input, AM_UINT inDataSize,
                                AM_U8 *output, AM_UINT *outDataSize)
{
  *outDataSize = 0;
  if (AM_LIKELY(0 == (inDataSize % mEncFrameBytes))) {
    bool isOk = true;
    AM_U8 *out = mEncodeBuf;

    memset(out, 0, sizeof(mEncodeBuf));
    mRepacketizer = opus_repacketizer_init(mRepacketizer);
    for (AM_UINT i = 0; i < (inDataSize / mEncFrameBytes); ++ i) {
      const opus_int16* pcm = (opus_int16*)(input + i * mEncFrameBytes);
      int ret = opus_encode(mEncoder, pcm, mEncFrameSize, out, 4096);
      if (AM_LIKELY(ret > 0)) {
        int retval = opus_repacketizer_cat(mRepacketizer, out, ret);
        if (AM_UNLIKELY(retval != OPUS_OK)) {
          ERROR("Opus repacketizer error: %s", opus_strerror(retval));
          isOk = false;
          break;
        }
        out += ret;
      } else {
        ERROR("Opus encode error: %s", opus_strerror(ret));
        isOk = false;
        break;
      }
    }
    if (AM_LIKELY(isOk)) {
      int ret = opus_repacketizer_out(mRepacketizer, output, 4096);
      if (AM_LIKELY(ret > 0)) {
        *outDataSize = ret;
      } else {
        ERROR("Opus repacketizer error: %s", opus_strerror(ret));
      }
    }
  } else {
    ERROR("Invalid input data length: %u, must be n times of %u",
          inDataSize, mEncFrameBytes);
  }
  return *outDataSize;
}
JNIEXPORT jint JNICALL
Java_org_jitsi_impl_neomedia_codec_audio_opus_Opus_encode
    (JNIEnv *env, jclass clazz, jlong encoder, jbyteArray input,
        jint inputOffset, jint inputFrameSize, jbyteArray output,
        jint outputOffset, jint outputLength)
{
    int ret;

    if (input && output)
    {
        jbyte *input_ = (*env)->GetPrimitiveArrayCritical(env, input, 0);

        if (input_)
        {
            jbyte *output_ = (*env)->GetPrimitiveArrayCritical(env, output, 0);

            if (output_)
            {
                ret
                    = opus_encode(
                            (OpusEncoder *) (intptr_t) encoder,
                            (opus_int16 *) (input_ + inputOffset),
                            inputFrameSize,
                            (unsigned char *) (output_ + outputOffset),
                            outputLength);
                (*env)->ReleasePrimitiveArrayCritical(env, output, output_, 0);
            }
            else
                ret = OPUS_ALLOC_FAIL;
            (*env)->ReleasePrimitiveArrayCritical(
                    env,
                    input, input_, JNI_ABORT);
        }
        else
            ret = OPUS_ALLOC_FAIL;
    }
    else
        ret = OPUS_BAD_ARG;
    return ret;
}
Esempio n. 28
0
JNIEXPORT jbyteArray JNICALL Java_aopus_OpusLibrary_encoderEncode
  (JNIEnv *env, jobject obj, jlong state, jbyteArray data, jint index, jint length)
{
    Encoder *encoder = (Encoder *)state;
    
    // copy managed to unmanaged
    unsigned char *dataBytes = malloc(length);
    (* env)->GetByteArrayRegion(env, data, index, length, dataBytes);

    int encodedLength = opus_encode(encoder->enc, (opus_int16 *)dataBytes, encoder->frameSizePerChannel, encoder->buffer, encoder->maxBufferSize);
    free(dataBytes);

    if (encodedLength > 0)
    {
        // copy unmanaged to managed
        jbyteArray encodedFrame = (* env)->NewByteArray(env, encodedLength);
        (* env)->SetByteArrayRegion(env, encodedFrame, 0, encodedLength, encoder->buffer);
        return encodedFrame;
    }
    
    return NULL;
}
Esempio n. 29
0
            bin_data opus_encoder::encode(const bin_data& b)
            {
                REQUIRE(_opus);
                REQUIRE_FALSE(b.data.empty());
                if(b.data.size() != MIN_BUF_SIZE) return {};

                u::bytes r;
                r.resize(MIN_BUF_SIZE);
                auto size = opus_encode(_opus, 
                        reinterpret_cast<const opus_int16*>(b.data.data()),
                        FRAMES,
                        reinterpret_cast<unsigned char*>(r.data()),
                        r.size());

                if(size < 0) 
                {
                    LOG << "opus encode error: "; log_opus_error(size);
                    return {};
                }
                r.resize(size);
                return {r};
            }
Esempio n. 30
0
static struct ast_frame *lintoopus_frameout(struct ast_trans_pvt *pvt)
{
	struct opus_coder_pvt *opvt = pvt->pvt;
	int datalen = 0;	/* output bytes */
	int samples = 0;	/* output samples */

	/* We can't work on anything less than a frame in size */
	if (pvt->samples < opvt->framesize) {
		return NULL;
	}

	/* Encode 160 samples (or more if it's not narrowband) */
	ast_debug(3, "[Encoder #%d (%d)] %d samples, %d bytes\n",
		opvt->id,
		opvt->sampling_rate,
		opvt->framesize,
		opvt->framesize * 2);

	if ((datalen = opus_encode(opvt->opus, opvt->buf, opvt->framesize, pvt->outbuf.uc, BUFFER_SAMPLES)) < 0) {
		ast_log(LOG_ERROR, "Error encoding the Opus frame: %s\n", opus_strerror(datalen));
		return NULL;
	}

	samples += opvt->framesize;
	pvt->samples -= opvt->framesize;

	/* Move the data at the end of the buffer to the front */
	if (pvt->samples) {
		memmove(opvt->buf, opvt->buf + samples, pvt->samples * 2);
	}

	ast_debug(3, "[Encoder #%d (%d)]   >> Got %d samples, %d bytes\n",
		opvt->id,
		opvt->sampling_rate,
		opvt->multiplier * samples,
		datalen);

	return ast_trans_frameout(pvt, datalen, opvt->multiplier * samples);
}