Beispiel #1
0
JNIEXPORT int JNICALL FUNCSPEEX(encodeSpeex)(JNIEnv* env, jobject obj, jbyteArray in) {
	speex_bits_reset(&ebits);
	jbyte* ptr = env->GetByteArrayElements(in, 0);
	int ret = speex_encode_int(enc_state, (spx_int16_t*)ptr, &ebits);
	env->ReleaseByteArrayElements(in, ptr, 0);
	return ret;
}
//*****************************************************************************
//
//! Encode a single frame of speex encoded audio.
//!
//! \param pui16InBuffer is the buffer that contains the raw PCM audio.
//! \param ui32InSize is the number of valid bytes in the \e pui16InBuffer
//! buffer.
//! \param pui8OutBuffer is a pointer to the buffer to store the encoded audio.
//! \param ui32OutSize is the size of the buffer pointed to by the
//! \e pui8OutBuffer pointer.
//!
//! This function will take a buffer of PCM audio and encode it into a frame
//! of speex compressed audio.  The \e pui16InBuffer parameter should contain
//! a single frame of PCM audio.  The \e pui8OutBuffer will contain the encoded
//! audio after returning from this function.
//!
//! \return This function returns the number of encoded bytes in the
//! \e pui8OutBuffer parameter.
//
//*****************************************************************************
int32_t
SpeexEncode(int16_t *pui16InBuffer, uint32_t ui32InSize,
            uint8_t *pui8OutBuffer, uint32_t ui32OutSize)
{
    int32_t i32Bytes;

    //
    // Reset the bit stream before encoding a new frame.
    //
    speex_bits_reset(&g_sSpeexEncoder.sBits);

    //
    // Encode a single frame.
    //
    speex_encode_int(g_sSpeexEncoder.pvState, pui16InBuffer,
                     &g_sSpeexEncoder.sBits);

    //
    // Read the PCM data from the encoded bit stream.
    //
    i32Bytes = speex_bits_write(&g_sSpeexEncoder.sBits, (char *)pui8OutBuffer,
                                ui32OutSize);

    //
    // Return the number of bytes in the PCM data.
    //
    return(i32Bytes);
}
Beispiel #3
0
int Pcm16_2_Speex( unsigned char* out_buf, unsigned char* in_buf, 
		   unsigned int size,
		   unsigned int channels, unsigned int rate, long h_codec )
{
  SpeexState* ss;
  short* pcm = (short*) in_buf;
  char* buffer = (char*)out_buf;
  div_t blocks;
    
  ss = (SpeexState*) h_codec;
    
  if (!ss || channels!=1)
    return -1;

  blocks = div(size>>1, ss->frame_size);
  if (blocks.rem) {
    ERROR("Pcm16_2_Speex: not integral number of blocks %d.%d\n", 
	  blocks.quot, blocks.rem);
    return -1;
  }
    
  /* For each chunk of ss->frame_size bytes, encode a single frame */
  speex_bits_reset(&ss->encoder.bits);
  while (blocks.quot--) {
    speex_encode_int(ss->encoder.state, pcm, &ss->encoder.bits);
    pcm += ss->frame_size;
  }
    
  buffer += speex_bits_write(&ss->encoder.bits, buffer, AUDIO_BUFFER_SIZE);
  return buffer - (char*)out_buf;
}
Beispiel #4
0
//function encodes input buffer, stores in output buffer, return number of compressed bytes
int encode(char* in, char* out, int max_bytes){
  int nbBytes; //track the size of compressed buffer
  speex_bits_reset(&enc_bits);  //Flush the struct's bits and prepare for next frame
  speex_encode_int(enc_state, (short*)in, &enc_bits); //encode the input
  int num_bytes = speex_bits_write(&enc_bits, out, max_bytes); //copy the encoded bytes to output stream
  return num_bytes; //return the length of the compressed buffer
}
Beispiel #5
0
JNIEXPORT jint JNICALL Java_com_speex_encode_Speex_encode
    (JNIEnv *env, jobject obj, jshortArray lin, jint offset, jbyteArray encoded, jint size) {

        jshort buffer[enc_frame_size];
        jbyte output_buffer[enc_frame_size];
	int nsamples = (size-1)/enc_frame_size + 1;
	int i, tot_bytes = 0;

	if (!codec_open)
		return 0;

	speex_bits_reset(&ebits);

	for (i = 0; i < nsamples; i++) {
		env->GetShortArrayRegion(lin, offset + i*enc_frame_size, enc_frame_size, buffer);
		speex_encode_int(enc_state, buffer, &ebits);
	}
	//env->GetShortArrayRegion(lin, offset, enc_frame_size, buffer);
	//speex_encode_int(enc_state, buffer, &ebits);

	tot_bytes = speex_bits_write(&ebits, (char *)output_buffer,
				     enc_frame_size);
	env->SetByteArrayRegion(encoded, 0, tot_bytes,
				output_buffer);

        return (jint)tot_bytes;
}
//*****************************************************************************
//
//! Encode a single frame of speex encoded audio.
//!
//! /param pusInBuffer is the buffer that contains the raw PCM audio.
//! /param ulInSize is the number of valid bytes in the pusInBuffer buffer.
//! /param pucOutBuffer is a pointer to the buffer to store the encoded audio.
//! /param ulOutSize is the size of the buffer pointed to by the pucOutBuffer
//! pointer.
//!
//! This function will take a buffer of PCM audio and encode it into a frame
//! of speex compressed audio.  The /e pusInBuffer parameter should contain
//! a single frame of PCM audio.  The /e pucOutBuffer will contain the encoded
//! audio after returning from this function.
//!
//! /return This function returns the number of encoded bytes in the
//! /e pucOutBuffer parameter.
//
//*****************************************************************************
int
SpeexEncode(short *pusInBuffer, unsigned long ulInSize,
            unsigned char *pucOutBuffer, unsigned long ulOutSize)
{
    int iBytes;

    //
    // Reset the bit stream before encoding a new frame.
    //
    speex_bits_reset(&g_sSpeexEncoder.sBits);

    //
    // Encode a single frame.
    //
    speex_encode_int(g_sSpeexEncoder.State, pusInBuffer,
                     &g_sSpeexEncoder.sBits);

    //
    // Read the PCM data from the encoded bit stream.
    //
    iBytes = speex_bits_write(&g_sSpeexEncoder.sBits, (char *)pucOutBuffer,
                              ulOutSize);

    //
    // return the number of bytes in the PCM data.
    //
    return(iBytes);
}
Beispiel #7
0
static int encode_speex(int16_t * input_frame, uint8_t nbframes, char * output, int bitrate) {
	int i, bytesToWrite, nbBytes;
  SpeexBits bits;
  void * state;
  long long total;

  speex_bits_init(&bits);
  state = speex_encoder_init(&speex_nb_mode);
  speex_encoder_ctl(state, SPEEX_SET_QUALITY, &bitrate);
  speex_bits_reset(&bits);
  
  total = 0;
  for(i=0;i<5*160;i++) {
    total += input_frame[i];
  }
  total /= (5*160);
  if(abs(total) < 10)
    return 0;

  for(i=0;i<5;i++) {
	  speex_encode_int(state, input_frame + (i*160), &bits);
  }

	bytesToWrite = speex_bits_nbytes(&bits);
  nbBytes = speex_bits_write(&bits, output, bytesToWrite);
  speex_bits_destroy(&bits);
  speex_decoder_destroy(state);
	return nbBytes;
}
void* SpeexEncoder::encodingThreadMethod(void)
	{
	Threads::Thread::setCancelState(Threads::Thread::CANCEL_ENABLE);
	// Threads::Thread::setCancelType(Threads::Thread::CANCEL_ASYNCHRONOUS);
	
	while(true)
		{
		try
			{
			/* Read raw audio data from the recording PCM device: */
			size_t numFrames=read(recordingBuffer,speexFrameSize);
			
			/* Check for possible error conditions: */
			if(numFrames==speexFrameSize&&speex_encode_int(speexState,recordingBuffer,&speexBits)>=0)
				{
				/* Write packed bits into the SPEEX packet queue: */
				char* speexPacket=speexPacketQueue.getWriteSegment();
				speex_bits_write(&speexBits,speexPacket,speexPacketSize);
				speexPacketQueue.pushSegment();
				speex_bits_reset(&speexBits);
				}
			}
		catch(Sound::ALSAPCMDevice::OverrunError)
			{
			/* Restart the recording PCM device: */
			prepare();
			start();
			}
		}
	
	return 0;
	}
Beispiel #9
0
tsk_size_t tdav_codec_speex_encode(tmedia_codec_t* self, const void* in_data, tsk_size_t in_size, void** out_data, tsk_size_t* out_max_size)
{	
	tdav_codec_speex_t* speex = (tdav_codec_speex_t*)self;
	tsk_size_t outsize = 0;
	
	if(!self || !in_data || !in_size || !out_data){
		TSK_DEBUG_ERROR("Invalid parameter");
		return 0;
	}
	
	speex_bits_reset(&speex->encoder.bits);
	speex_encode_int(speex->encoder.state, (spx_int16_t*)in_data, &speex->encoder.bits);

	if(*out_max_size <speex->encoder.size){
		if((*out_data = tsk_realloc(*out_data, speex->encoder.size))){
			*out_max_size = speex->encoder.size;
		}
		else{
			*out_max_size = 0;
			return 0;
		}
	}
	
	outsize = speex_bits_write(&speex->encoder.bits, *out_data, speex->encoder.size/2);

   return outsize;
}
JNIEXPORT jint JNICALL Java_org_thoughtcrime_redphone_codec_SpeexCodec_encode (JNIEnv *env, jobject obj, jshortArray decArr, jbyteArray encArr, jint rawLen ){
  if( !initialized ) {
    logv( env, "tried to encode without initializing" );
    return -1;
  }

  //  logv( env, "entered encode %d", rawLen );
  //  logv( env, "encoding %d samples", rawLen );
  jshort *raw_stream = env->GetShortArrayElements( decArr, NULL );
  speex_bits_reset( &enc_bits );

  //  logv( env, "bits reset" );
  //  speex_preprocess_run( prepState, (spx_int16_t *)raw_stream );
  speex_encode_int( enc, (spx_int16_t *)raw_stream, &enc_bits );

  //  logv( env, "encode complete" );

  env->ReleaseShortArrayElements( decArr, raw_stream, JNI_ABORT );

  //  logv( env, "writing up to %d bytes to buffer", enc_frame_size );

  int nbytes = speex_bits_write( &enc_bits, enc_buffer, enc_frame_size );

  //  logv( env, "wrote %d bytes to buffer", nbytes );

  env->SetByteArrayRegion( encArr, 0, nbytes, (jbyte*)enc_buffer );

  //  logv( env, "wrote back to java buffer" );

  return (jint)nbytes;
}
bool NetworkSoundRecorder::onProcessSamples(const cpp3ds::Int16 *samples, std::size_t sampleCount)
{
	m_samples.insert(m_samples.end(), samples, samples + sampleCount);

	std::vector<char> encodedSamples;
	char out[m_frameSize*2];
	int size = m_samples.size();
	int i = 0;

	while (size >= m_frameSize)
	{
		spx_int16_t* audioFrame = &m_samples[0] + i * m_frameSize;

		speex_preprocess_run(m_speexPreprocessState, audioFrame);

		speex_bits_reset(&m_speexBits);
		speex_encode_int(m_speexState, audioFrame, &m_speexBits);

		char bytes = speex_bits_write(&m_speexBits, out, sizeof(out));

		encodedSamples.push_back(bytes);
		encodedSamples.insert(encodedSamples.end(), out, out + bytes);

		i++;
		size -= m_frameSize;
	}

	std::vector<cpp3ds::Int16>(m_samples.end() - size, m_samples.end()).swap(m_samples);

	std::cout << "size: " << sampleCount * sizeof(cpp3ds::Int16) << std::endl;

	m_context->client.sendVoiceData(m_context->name.toAnsiString(), &encodedSamples[0], encodedSamples.size());
	return true;
}
Beispiel #12
0
static int speex_encode_frame(AVCodecContext *avctx,
                      unsigned char *frame, int buf_size, void *data)
{
    SpeexContext *s = avctx->priv_data;
    int bytes_written = 0;
    
    if (avctx->channels == 2)
        speex_encode_stereo_int(data, avctx->frame_size, &s->bits);
        
    speex_encode_int(s->st, data, &s->bits);

    //speex_bits_insert_terminator(&s->bits);
        
    if (!(avctx->flags2 & CODEC_FLAG2_NO_OUTPUT))
    {
    	bytes_written = speex_bits_write(&s->bits, frame, buf_size);
    }

	speex_bits_reset(&s->bits);

    if (avctx->debug & FF_DEBUG_BITSTREAM)
    {    
        av_log(avctx, AV_LOG_DEBUG, "Speex: encoded speex frame (%d bytes total, framesize: %d)\n", 
            bytes_written, avctx->frame_size);
    }
    
    return bytes_written;
}
Beispiel #13
0
int	speex_encoder_encode(unsigned char* src, int inlen, unsigned char*dest, int outlen) {
	int len = 0;
	speex_bits_reset(&bits);
	speex_encode_int(speex_encoder, (short*)src, &bits);
	len = speex_bits_write(&bits, dest, outlen);
	return len;
}
Beispiel #14
0
BYTE* encodeSPEEX(signed short *data)
{
	char *pCh = (char*)(&in_byte[0]);
	speex_bits_reset(&inbits);
	speex_encode_int(pEnc, data, &inbits);
	speex_bits_write(&inbits, pCh, SPEEX_SIZE);
	return (BYTE*)pCh;
}
Beispiel #15
0
/*
 * Encode frames.
 */
static pj_status_t spx_codec_encode( pjmedia_codec *codec, 
				     const struct pjmedia_frame *input,
				     unsigned output_buf_len, 
				     struct pjmedia_frame *output)
{
    struct spx_private *spx;
    unsigned samples_per_frame;
    int tx = 0;
    spx_int16_t *pcm_in = (spx_int16_t*)input->buf;
    pj_size_t nsamples;

    spx = (struct spx_private*) codec->codec_data;

    if (input->type != PJMEDIA_FRAME_TYPE_AUDIO) {
	output->size = 0;
	output->buf = NULL;
	output->timestamp = input->timestamp;
	output->type = input->type;
	return PJ_SUCCESS;
    }

    nsamples = input->size >> 1;
    samples_per_frame=spx_factory.speex_param[spx->param_id].samples_per_frame;

    PJ_ASSERT_RETURN(nsamples % samples_per_frame == 0, 
		     PJMEDIA_CODEC_EPCMFRMINLEN);

    /* Flush all the bits in the struct so we can encode a new frame */
    speex_bits_reset(&spx->enc_bits);

    /* Encode the frames */
    while (nsamples >= samples_per_frame) {
	tx += speex_encode_int(spx->enc, pcm_in, &spx->enc_bits);
	pcm_in += samples_per_frame;
	nsamples -= samples_per_frame;
    }

    /* Check if we need not to transmit the frame (DTX) */
    if (tx == 0) {
	output->buf = NULL;
	output->size = 0;
	output->timestamp.u64 = input->timestamp.u64;
	output->type = PJMEDIA_FRAME_TYPE_NONE;
	return PJ_SUCCESS;
    }

    /* Check size. */
    pj_assert(speex_bits_nbytes(&spx->enc_bits) <= (int)output_buf_len);

    /* Copy the bits to an array of char that can be written */
    output->size = speex_bits_write(&spx->enc_bits, 
				    (char*)output->buf, output_buf_len);
    output->type = PJMEDIA_FRAME_TYPE_AUDIO;
    output->timestamp = input->timestamp;

    return PJ_SUCCESS;
}
Beispiel #16
0
OsStatus MpeSipxSpeexUWb::encode(const MpAudioSample* pAudioSamples,
                              const int numSamples,
                              int& rSamplesConsumed,
                              unsigned char* pCodeBuf,
                              const int bytesLeft,
                              int& rSizeInBytes,
                              UtlBoolean& sendNow,
                              MpSpeechType& speechType)
{
   int size = 0;

   if (speechType == MP_SPEECH_SILENT && ms_bEnableVAD && mBufferLoad == 0)
   {
      // VAD must be enabled, do DTX
      rSamplesConsumed = numSamples;
      rSizeInBytes = 0;
      sendNow = TRUE; // sends any unsent frames now
      return OS_SUCCESS;
   }

   memcpy(&mpBuffer[mBufferLoad], pAudioSamples, sizeof(MpAudioSample)*numSamples);
   mBufferLoad = mBufferLoad + numSamples;
   assert(mBufferLoad <= 640);

   // Check for necessary number of samples
   if(mBufferLoad == 640)
   {
      speex_bits_reset(&mBits);

      // We don't have echo data, but it should be possible to use the
      // Speex echo cancelator in sipxtapi.
      if(mDoPreprocess)
         speex_preprocess(mpPreprocessState, mpBuffer, NULL);
      speex_encode_int(mpEncoderState, mpBuffer, &mBits);

      // Copy to the byte buffer
      size = speex_bits_write(&mBits,(char*)pCodeBuf, bytesLeft);      

      // Reset the buffer count.
      mBufferLoad = 0;

      if (size > 0)
      {
         sendNow = true;
      }
   }
   else
   {
      sendNow = false;
   }

   rSamplesConsumed = numSamples;
   rSizeInBytes = size;
   
   return OS_SUCCESS;
}
Beispiel #17
0
int ph_speex_encode(void *ctx, const void *src, int srcsize, void *dst, int dstsize)
{
  struct speexenc *speex = (struct speexenc *)ctx; 
  short *new_speech = (short *)src;
  int count;

  speex_bits_reset(&speex->bits);
  speex_encode_int(speex->st, new_speech, &speex->bits);
  count = speex_bits_write(&speex->bits, dst, dstsize);

  return count;
}
Beispiel #18
0
uint16 t_speex_audio_encoder::encode(int16 *sample_buf, uint16 nsamples, 
			uint8 *payload, uint16 payload_size, bool &silence)
{
	assert(payload_size >= _max_payload_size);

	silence = false;
	speex_bits_reset(&speex_bits);
            
    if (speex_encode_int(speex_enc_state, sample_buf, &speex_bits) == 0) 
		silence = true;

	return speex_bits_write(&speex_bits, (char *)payload, payload_size);
}
static switch_status_t switch_speex_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 speex_context *context = codec->private_info;
	short *buf;
	int is_speech = 1;

	if (!context) {
		return SWITCH_STATUS_FALSE;
	}

	buf = decoded_data;

	if (context->pp) {
		is_speech = speex_preprocess(context->pp, buf, NULL);
	}

	if (is_speech) {
		is_speech = speex_encode_int(context->encoder_state, buf, &context->encoder_bits)
			|| !context->codec_settings.dtx;
	} else {
		speex_bits_pack(&context->encoder_bits, 0, 5);
	}


	if (is_speech) {
		switch_clear_flag(context, SWITCH_CODEC_FLAG_SILENCE);
		*flag |= SWITCH_CODEC_FLAG_SILENCE_STOP;
	} else {
		if (switch_test_flag(context, SWITCH_CODEC_FLAG_SILENCE)) {
			*encoded_data_len = 0;
			*flag |= SWITCH_CODEC_FLAG_SILENCE;
			return SWITCH_STATUS_SUCCESS;
		}

		switch_set_flag(context, SWITCH_CODEC_FLAG_SILENCE);
		*flag |= SWITCH_CODEC_FLAG_SILENCE_START;
	}


	speex_bits_pack(&context->encoder_bits, 15, 5);
	*encoded_data_len = speex_bits_write(&context->encoder_bits, (char *) encoded_data, context->encoder_frame_size);
	speex_bits_reset(&context->encoder_bits);
	(*encoded_data_len)--;

	return SWITCH_STATUS_SUCCESS;
}
static void enc_process(MSFilter *f){
	SpeexEncState *s=(SpeexEncState*)f->data;
	mblk_t *im;
	int nbytes;
	uint8_t *buf;
	int frame_per_packet=1;

	if (s->frame_size<=0)
		return;

	ms_filter_lock(f);

	if (s->ptime>=20)
	{
		frame_per_packet = s->ptime/20;
	}

	if (frame_per_packet<=0)
		frame_per_packet=1;
	if (frame_per_packet>7) /* 7*20 == 140 ms max */
		frame_per_packet=7;

	nbytes=s->frame_size*2;
	buf=(uint8_t*)alloca(nbytes*frame_per_packet);

	while((im=ms_queue_get(f->inputs[0]))!=NULL){
		ms_bufferizer_put(s->bufferizer,im);
	}
	while(ms_bufferizer_read(s->bufferizer,buf,nbytes*frame_per_packet)==nbytes*frame_per_packet){
		mblk_t *om=allocb(nbytes*frame_per_packet,0);//too large...
		int k;
		SpeexBits bits;
		speex_bits_init(&bits);
		for (k=0;k<frame_per_packet;k++)
		{
			speex_encode_int(s->state,(int16_t*)(buf + (k*s->frame_size*2)),&bits);
			s->ts+=s->frame_size;
		}
		speex_bits_insert_terminator(&bits);
		k=speex_bits_write(&bits, (char*)om->b_wptr, nbytes*frame_per_packet);
		om->b_wptr+=k;

		mblk_set_timestamp_info(om,s->ts-s->frame_size);
		ms_bufferizer_fill_current_metas(s->bufferizer, om);
		ms_queue_put(f->outputs[0],om);
		speex_bits_destroy(&bits);
	}
	ms_filter_unlock(f);
}
Beispiel #21
0
int qSpeexEncode(QSpeexCodecPtr handle, void* samples, int sampleSize)
{
	int offset;

	speex_bits_reset(&handle->encBits);

	/** Floods the console **/
	/**   fprintf(stderr, "encoding bytes: \n");	**/
	for(offset=0; offset<sampleSize; offset+=handle->frameSize) {
		short* ptr = ((short*)samples) + offset;
		speex_encode_int(handle->encState, ptr, &handle->encBits);
	}
	speex_bits_insert_terminator(&handle->encBits);
	return speex_bits_nbytes(&handle->encBits);
}
uint16 SpeexPlugin::encode(int16 *sample_buf, uint16 nsamples, uint8 *payload,
		uint16 payload_size, bool &silence)
		throw(OperationNotPerfomedException) {

	if (payload_size < MAX_PAYLOAD_SIZE)
		throw OperationNotPerfomedException("The buffer is not large enough");

	if (!encoder)
		throw OperationNotPerfomedException("Encoder not ready");

	//	// Falta fazer o echo cancelling
	//
	//
	//	if (usingEchoCancellation && !echoCapturedLast) {
	//		uint32 samplesize = getSampleSize();
	//		spx_int16_t *input_buf = new spx_int16_t[samplesize / 2];
	//
	//		for (int i = 0; i < getSampleSize() / 2; i++) {
	//			input_buf[i] = sample_buf[i];
	//		}
	//
	//		speex_echo_capture(echocancellation, input_buf, sample_buf);
	//		echoCapturedLast = true;
	//		delete input_buf;
	//	}

	bool preprocessing_silence = false;
	if (preprocess) {
		preprocessing_silence = !speex_preprocess_run(preprocess, sample_buf); //Garantir que o nsamples sera sempre o mesmo
		bool speex_dsp_vad;
		speex_preprocess_ctl(preprocess, SPEEX_PREPROCESS_GET_VAD,
				&speex_dsp_vad);
		if (!speex_dsp_vad)
			preprocessing_silence = false;
	}

	silence = false;
	speex_bits_reset(&encoder->bits);

	silence = speex_encode_int(encoder->state, sample_buf, &encoder->bits) == 0;

	silence = silence || preprocessing_silence;

	return speex_bits_write(&encoder->bits, (char *) payload, payload_size);

}
Beispiel #23
0
int universal_speex_encode(void* handle, const void* pAudioBuffer, 
                          unsigned cbAudioSamples, int* rSamplesConsumed, 
                          void* pCodedData, unsigned cbMaxCodedData, 
                          int* pcbCodedSize, unsigned* pbSendNow)
{
   struct speex_codec_data_encoder *mpSpeexEnc = 
      (struct speex_codec_data_encoder *)handle;
   assert(handle != NULL);

   memcpy(&mpSpeexEnc->mpBuffer[mpSpeexEnc->mBufferLoad], pAudioBuffer,
          SIZE_OF_SAMPLE * cbAudioSamples);
   mpSpeexEnc->mBufferLoad = mpSpeexEnc->mBufferLoad+cbAudioSamples;
   assert(mpSpeexEnc->mBufferLoad <= mpSpeexEnc->mNumSamplesPerFrame);

   // Check for necessary number of samples
   if(mpSpeexEnc->mBufferLoad == mpSpeexEnc->mNumSamplesPerFrame)
   {
      SpeexBits bits;

      // Wrap our buffer to speex bits structure
      speex_bits_init_buffer(&bits, pCodedData, cbMaxCodedData);

      // Preprocess data if requested
      if(mpSpeexEnc->mDoPreprocess)
         speex_preprocess(mpSpeexEnc->mpPreprocessState, mpSpeexEnc->mpBuffer, NULL);
      // Encode frame and append terminator
      speex_encode_int(mpSpeexEnc->mpEncoderState, mpSpeexEnc->mpBuffer, &bits);
      speex_bits_insert_terminator(&bits);

      // Tell that we've produced packet
      *pbSendNow = TRUE;
      *pcbCodedSize = speex_bits_nbytes(&bits);

      // Reset the buffer count.
      mpSpeexEnc->mBufferLoad = 0;
   }
   else
   {
      *pbSendNow = FALSE;
      *pcbCodedSize = 0;
   }

   *rSamplesConsumed = cbAudioSamples;

   return RPLG_SUCCESS;
}
Beispiel #24
0
static int encode(struct auenc_state *st, uint8_t *buf,
		  size_t *len, const int16_t *sampv, size_t sampc)
{
	const size_t n = st->channels * st->frame_size;
	int ret, r;

	if (*len < 128)
		return ENOMEM;

	/* VAD */
	if (!sampv || !sampc) {
		/* 5 zeros interpreted by Speex as silence (submode 0) */
		speex_bits_pack(&st->bits, 0, 5);
		goto out;
	}

	/* Handle multiple Speex frames in one RTP packet */
	while (sampc > 0) {

		/* Assume stereo */
		if (2 == st->channels) {
			speex_encode_stereo_int((int16_t *)sampv,
						st->frame_size, &st->bits);
		}

		ret = speex_encode_int(st->enc, (int16_t *)sampv, &st->bits);
		if (1 != ret) {
			warning("speex: speex_encode_int: ret=%d\n", ret);
		}

		sampc -= n;
		sampv += n;
	}

 out:
	/* Terminate bit stream */
	speex_bits_pack(&st->bits, 15, 5);

	r = speex_bits_write(&st->bits, (char *)buf, (int)*len);
	*len = r;

	speex_bits_reset(&st->bits);

	return 0;
}
Beispiel #25
0
int AudioInput::encodeSpeexFrame(short *psSource, unsigned char *buffer) {
	int vbr = 0;
	speex_encoder_ctl(esSpeex, SPEEX_GET_VBR_MAX_BITRATE, &vbr);
	if (vbr != iAudioQuality) {
		vbr = iAudioQuality;
		speex_encoder_ctl(esSpeex, SPEEX_SET_VBR_MAX_BITRATE, &vbr);
	}

	if (! bPreviousVoice)
		speex_encoder_ctl(esSpeex, SPEEX_RESET_STATE, NULL);

	speex_encode_int(esSpeex, psSource, &sbBits);
	int len = speex_bits_write(&sbBits, reinterpret_cast<char *>(buffer), 127);
	iBitrate = len * 50 * 8;
	speex_bits_reset(&sbBits);

	return len;
}
Beispiel #26
0
	void oper_one( const string& src, string& dst )
	{
		dst = "" ;
		int src_len = src.size();
		int block_size = sizeof(short) * frame_size ;
		if( src_len % sizeof(short) != 0 && src_len % block_size != 0 )
		{	
			return ;
		}

		int times = src_len / block_size ;
		const char* buff = src.data() ;
		for( int i = 0 ; i < times; ++ i )
		{
			speex_bits_reset( &bits );
			memcpy( (void*)in,buff + i * block_size, block_size );
			speex_encode_int(state, in, &bits);
			int nbBytes = speex_bits_write(&bits, cbits, MAX_FRAME_BYTES);
			dst.append( cbits, nbBytes );
		}
	}
Beispiel #27
0
int main(int argc, char *argv[])
{
   pa_simple *pa = NULL;
   pa_sample_spec paspec = { PA_SAMPLE_S16NE, 32000, 1 };
   void *state = NULL;
   SpeexBits bits;
   int quality = 3;
   int complexity = 1;
   int framesize = 0;
   int16_t *framein = NULL;
   char *frameout = NULL;
   int len;

   do {
      if(!(pa = pa_simple_new(NULL, "", PA_STREAM_RECORD, NULL, "", &paspec, NULL, NULL, NULL))) break;
      speex_bits_init(&bits);
      if(!(state = speex_encoder_init(&speex_uwb_mode))) break;
      if(speex_encoder_ctl(state, SPEEX_SET_QUALITY, &quality)) break;
      if(speex_encoder_ctl(state, SPEEX_SET_COMPLEXITY, &complexity)) break;
      if(speex_encoder_ctl(state, SPEEX_GET_FRAME_SIZE, &framesize) || !framesize) break;
      if(!(framein = calloc(framesize, sizeof(int16_t)))) break;
      if(!(frameout = calloc(framesize, sizeof(int16_t)))) break;

      while(1) {
         if(pa_simple_read(pa, framein, framesize * sizeof(int16_t), NULL)) break;
         speex_bits_reset(&bits);
         speex_encode_int(state, framein, &bits);
         if(!(len = speex_bits_write(&bits, frameout, framesize * sizeof(int16_t)))) break;
         fwrite(&len, sizeof(int), 1, stdout);
         fwrite(frameout, 1, len, stdout);
      }
   } while(0);
   if(framein) free(framein);
   if(frameout) free(frameout);
   if(state) speex_encoder_destroy(state);
   speex_bits_destroy(&bits);
   if(pa) pa_simple_free(pa);

   return 0;
}
Beispiel #28
0
JNIEXPORT jint Java_com_speex_Speex_encode(JNIEnv *env, jobject obj,
		jshortArray lin, jint offset, jbyteArray encoded, jint size) {

	jshort buffer[enc_frame_size];
	jbyte output_buffer[size];
	int nsamples = (size - 1) / enc_frame_size + 1;
	int i, tot_bytes = 0;

	if (!codec_open)
	return 0;

	speex_bits_reset(&ebits);

	// 把数据写入buffer
	for (i = 0; i < nsamples; i++) {
		// TODO
		if ((offset + i * enc_frame_size + enc_frame_size) > size) {
			env->GetShortArrayRegion(lin, offset + i * enc_frame_size,
					size - (offset + i * enc_frame_size), buffer);
		} else {
			env->GetShortArrayRegion(lin, offset + i * enc_frame_size,
					enc_frame_size, buffer);
		}
		env->GetShortArrayRegion(lin, offset + i * enc_frame_size,
							enc_frame_size, buffer);
		// 把buffer数据写入ebits
		speex_encode_int(enc_state, buffer, &ebits);
	}

	/*env->GetShortArrayRegion(lin, offset, enc_frame_size, buffer);
	speex_encode_int(enc_state, buffer, &ebits);*/

	// 把ebits数据写入output_buffer
	tot_bytes = speex_bits_write(&ebits, (char *) output_buffer, size);
	// 统计编码的大小
	env->SetByteArrayRegion(encoded, 0, tot_bytes, output_buffer);

	return (jint) tot_bytes;
}
Beispiel #29
0
extern "C" JNIEXPORT int Java_com_haitou_xiaoyoupai_imservice_support_audio_Speex_echoCancellationEncode(
    JNIEnv *env, jshortArray rec, jshortArray play, jbyteArray encoded) {

    jshort echo_buf[enc_frame_size];
    jshort ref_buf[enc_frame_size];
    jshort e_buf[enc_frame_size];
    jbyte output_buffer[enc_frame_size];

    env->GetShortArrayRegion(rec, 0, enc_frame_size, echo_buf);
    env->GetShortArrayRegion(play, 0, enc_frame_size, ref_buf);

    speex_echo_cancellation(echoState, echo_buf, ref_buf, e_buf);
    speex_preprocess_run(den, e_buf);

    speex_bits_reset(&ebits);

    speex_encode_int(enc_state, e_buf, &ebits);

    jint tot_bytes = speex_bits_write(&ebits, (char *) output_buffer,
                                      enc_frame_size);
    env->SetByteArrayRegion(encoded, 0, tot_bytes, output_buffer);

    return (jint) tot_bytes;
}
int main(int argc, char **argv)
{
   char *inFile, *outFile, *bitsFile;
   FILE *fin, *fout, *fbits=NULL;
   short in_short[FRAME_SIZE];
   short out_short[FRAME_SIZE];
   float sigpow,errpow,snr, seg_snr=0;
   int snr_frames = 0;
   char cbits[200];
   int nbBits;
   int i;
   void *st;
   void *dec;
   SpeexBits bits;
   spx_int32_t tmp;
   int bitCount=0;
   spx_int32_t skip_group_delay;
   SpeexCallback callback;

   sigpow = 0;
   errpow = 0;

   st = speex_encoder_init(speex_lib_get_mode(SPEEX_MODEID_WB));
   dec = speex_decoder_init(speex_lib_get_mode(SPEEX_MODEID_WB));

   callback.callback_id = SPEEX_INBAND_CHAR;
   callback.func = speex_std_char_handler;
   callback.data = stderr;
   speex_decoder_ctl(dec, SPEEX_SET_HANDLER, &callback);

   callback.callback_id = SPEEX_INBAND_MODE_REQUEST;
   callback.func = speex_std_mode_request_handler;
   callback.data = st;
   speex_decoder_ctl(dec, SPEEX_SET_HANDLER, &callback);

   tmp=1;
   speex_decoder_ctl(dec, SPEEX_SET_ENH, &tmp);
   tmp=0;
   speex_encoder_ctl(st, SPEEX_SET_VBR, &tmp);
   tmp=8;
   speex_encoder_ctl(st, SPEEX_SET_QUALITY, &tmp);
   tmp=3;
   speex_encoder_ctl(st, SPEEX_SET_COMPLEXITY, &tmp);
   /*tmp=3;
   speex_encoder_ctl(st, SPEEX_SET_HIGH_MODE, &tmp);
   tmp=6;
   speex_encoder_ctl(st, SPEEX_SET_LOW_MODE, &tmp);
*/

   speex_encoder_ctl(st, SPEEX_GET_LOOKAHEAD, &skip_group_delay);
   speex_decoder_ctl(dec, SPEEX_GET_LOOKAHEAD, &tmp);
   skip_group_delay += tmp;


   if (argc != 4 && argc != 3)
   {
      fprintf (stderr, "Usage: encode [in file] [out file] [bits file]\nargc = %d", argc);
      exit(1);
   }
   inFile = argv[1];
   fin = fopen(inFile, "rb");
   outFile = argv[2];
   fout = fopen(outFile, "wb+");
   if (argc==4)
   {
      bitsFile = argv[3];
      fbits = fopen(bitsFile, "wb");
   }
   speex_bits_init(&bits);
   while (!feof(fin))
   {
      fread(in_short, sizeof(short), FRAME_SIZE, fin);
      if (feof(fin))
         break;
      speex_bits_reset(&bits);

      speex_encode_int(st, in_short, &bits);
      nbBits = speex_bits_write(&bits, cbits, 200);
      bitCount+=bits.nbBits;

      if (argc==4)
         fwrite(cbits, 1, nbBits, fbits);
      speex_bits_rewind(&bits);

      speex_decode_int(dec, &bits, out_short);
      speex_bits_reset(&bits);

      fwrite(&out_short[skip_group_delay], sizeof(short), FRAME_SIZE-skip_group_delay, fout);
      skip_group_delay = 0;
   }
   fprintf (stderr, "Total encoded size: %d bits\n", bitCount);
   speex_encoder_destroy(st);
   speex_decoder_destroy(dec);
   speex_bits_destroy(&bits);

   rewind(fin);
   rewind(fout);

   while ( FRAME_SIZE == fread(in_short, sizeof(short), FRAME_SIZE, fin) 
           &&
           FRAME_SIZE ==  fread(out_short, sizeof(short), FRAME_SIZE,fout) )
   {
	float s=0, e=0;
        for (i=0;i<FRAME_SIZE;++i) {
            s += (float)in_short[i] * in_short[i];
            e += ((float)in_short[i]-out_short[i]) * ((float)in_short[i]-out_short[i]);
        }
	seg_snr += 10*log10((s+160)/(e+160));
	sigpow += s;
	errpow += e;
	snr_frames++;
   }
   fclose(fin);
   fclose(fout);

   snr = 10 * log10( sigpow / errpow );
   seg_snr /= snr_frames;
   fprintf(stderr,"SNR = %f\nsegmental SNR = %f\n",snr, seg_snr);

#ifdef FIXED_DEBUG
   printf ("Total: %f MIPS\n", (float)(1e-6*50*spx_mips/snr_frames));
#endif
   
   return 1;
}