Exemple #1
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
}
//*****************************************************************************
//
//! 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);
}
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;
}
//*****************************************************************************
//
//! 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);
}
Exemple #5
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;
}
Exemple #6
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;
}
Exemple #7
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;
}
Exemple #8
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;
}
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;
}
Exemple #10
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;
	}
int spx_encode_frame(int handle ,short *const pcm_data ,char *speex_data){
   // char cbits[200];
    float input[FRAME_SIZE];
    speex_encode_union_t * speex_encode_u = (speex_encode_union_t *)handle;

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

    /*Encode the frame*/
   // memcpy(input,pcm_data,FRAME_SIZE*2);
    int i;
    for (i = 0; i < FRAME_SIZE; i++)
          input[i] = pcm_data[i];

    speex_encode(speex_encode_u->state, input, &speex_encode_u->bits);

    ////write rtp packet header!!!!!RTP HEADER
    //memcpy(speex_data ,&speex_encode_u->rtp_header ,RTP_HEADER_SIZE);
    ///*Copy the bits to an array of char that can be written*/
    //int nbBytes = speex_bits_write(&speex_encode_u->bits, &speex_data[RTP_HEADER_SIZE], 38);
    //fwrite(&speex_data[RTP_HEADER_SIZE] ,1 ,38 ,fp_speex_send);

	int nbBytes = speex_bits_write(&speex_encode_u->bits, speex_data, 38);
	fwrite(speex_data ,1 ,38 ,fp_speex_send);
	printf("after speex_encode ,write nbBytes = %d  to file !\n" ,nbBytes);
	return 0;
}
Exemple #13
0
void AudioInput::flushCheck() {
	if (bPreviousVoice && iFrames < g.s.iFramesPerPacket)
		return;

	int flags = 0;
	if (g.iAltSpeak > 0)
		flags += MessageSpeex::AltSpeak;
	if (g.s.lmLoopMode == Settings::Server)
		flags += MessageSpeex::LoopBack;

	if (! bPreviousVoice)
		flags += MessageSpeex::EndSpeech;

	flags += (iFrames - 1) << 4;

	int len = speex_bits_nbytes(&sbBits);
	QByteArray qba(len + 1, 0);
	qba[0] = static_cast<unsigned char>(flags);

	speex_bits_write(&sbBits, qba.data() + 1, len);

	MessageSpeex msPacket;
	msPacket.qbaSpeexPacket = qba;
	msPacket.iSeq = iFrameCounter;

	if (g.s.lmLoopMode == Settings::Local) {
		LoopPlayer::lpLoopy.addFrame(qba, msPacket.iSeq);
	} else if (g.sh) {
		g.sh->sendMessage(&msPacket);
	}

	iFrames = 0;
	speex_bits_reset(&sbBits);
}
Exemple #14
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;
}
int spx_encode_frame(int handle ,short *pcm_data ,char *speex_data){
   // char cbits[200];
    float input[FRAME_SIZE];
    speex_encode_union_t * speex_encode_u = (speex_encode_union_t *)handle;

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

    /*Encode the frame*/
   // memcpy(input,pcm_data,FRAME_SIZE*2);
    int i;
    for (i = 0; i < FRAME_SIZE; i++)
    			input[i] = pcm_data[i];
    speex_encode(speex_encode_u->state, input, &speex_encode_u->bits);
    /*Copy the bits to an array of char that can be written*/
//    nbBytes = speex_bits_write(&speex_encode_u->bits, cbits, 200);
    int nbBytes = speex_bits_write(&speex_encode_u->bits, speex_data, 38);
    printf("nbBytes = %d \n" ,nbBytes);
//    /*Write the size of the frame first. This is what sampledec expects but
//     it’s likely to be different in your own application*/
//    fwrite(&nbBytes, sizeof(int), 1, stdout);
//    printf("nbBytes = %d \n" ,nbBytes);
//    /*Write the compressed data*/
//    //fwrite(cbits, 1, nbBytes, stdout);
}
Exemple #16
0
int main(int argc, char **argv)
{
   char *inFile;
   FILE *fin;
   short in[FRAME_SIZE];
   float input[FRAME_SIZE];
   char cbits[2000];
   int nbBytes;
   /*Holds the state of the encoder*/
   void *state;
   /*Holds bits so they can be read and written to by the Speex routines*/
   SpeexBits bits;
   int i, tmp;

   /*Create a new encoder state in narrowband mode*/
   state = speex_encoder_init(&speex_nb_mode);
   //printf("inited\n");
   /*Set the quality to 8 (15 kbps)*/
   tmp=8;
   speex_encoder_ctl(state, SPEEX_SET_QUALITY, &tmp);

   inFile = argv[1];
   fin = fopen(inFile, "r");

   /*Initialization of the structure that holds the bits*/
   speex_bits_init(&bits);
   while (1)
   {
      /*Read a 16 bits/sample audio frame*/
      fread(in, sizeof(short), FRAME_SIZE, fin);
      if (feof(fin))
         break;
      /*Copy the 16 bits values to float so Speex can work on them*/
      for (i=0;i<FRAME_SIZE;i++)
         input[i]=in[i];

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

      /*Encode the frame*/
      speex_encode(state, input, &bits);
      /*Copy the bits to an array of char that can be written*/
      nbBytes = speex_bits_write(&bits, cbits, 2000);

      /*Write the size of the frame first. This is what sampledec expects but
       it's likely to be different in your own application*/
      fwrite(&nbBytes, sizeof(int), 1, stdout);
      /*Write the compressed data*/
      fwrite(cbits, 1, nbBytes, stdout);
      
   }
   
   /*Destroy the encoder state*/
   speex_encoder_destroy(state);
   /*Destroy the bit-packing struct*/
   speex_bits_destroy(&bits);
   fclose(fin);
   return 0;
}
Exemple #17
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;
}
Exemple #18
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;
}
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;
}
Exemple #20
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;
}
Exemple #21
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;
}
Exemple #23
0
    /* encode PCM data to speex frames */
static void speexout_encode(t_speexout *x)
{
    if ( x->x_bytesbuffered > x->x_framesize )
    {
      speex_bits_reset(&x->x_bits);
      
      {
        t_int sp=0, rp=0;
     
          while( sp < x->x_framesize )
          {
             rp=(x->x_outp+sp)%IN_BUFFER_SIZE;
             // post( "speexout~ : sp=%d : rp=%d", sp, rp );
             x->x_encchunk[ sp++ ] = *(x->x_inbuf+rp);
          }
          speex_encode(x->x_encstate, x->x_encchunk, &x->x_bits);
      }

      x->x_outp = (x->x_outp+x->x_framesize)%IN_BUFFER_SIZE;
      x->x_bytesbuffered -= x->x_framesize;
      x->x_encsize = speex_bits_write(&x->x_bits, x->x_outbuf+1, OUT_BUFFER_SIZE );
      if ( x->x_encsize < 127 )
      {
         *(x->x_outbuf) = (char)x->x_encsize; 
      }
      else
      {
         post( "speexout~ : encoding error : frame is more than 127 bytes" );
         x->x_encsize = -1;
      }
      x->x_bytesemitted += x->x_encsize;
#ifdef DATADEBUG
      {
        t_int si;

          printf( "speexout~ : encoded :  " );
          for ( si=0; si<x->x_encsize; si++ )
          {
              printf( "%d ", *(x->x_outbuf+si) );
          }
          printf( "\n" );
      }
#endif
    }
    else
    {
      x->x_encsize = -1;
    }
}
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);
}
Exemple #25
0
int main(int argc, char **argv)
{
    char *inFile;
    FILE *fin;
    short in[FRAME_SIZE];
    float input[FRAME_SIZE];
    char cbits[200];
    int nbBytes;
    /*保存编码的状态*/
    void *state;
    /*保存字节因此他们可以被speex常规读写*/
    SpeexBits bits;
    int i, tmp;
    //新建一个新的编码状态在窄宽(narrowband)模式下
    state = speex_encoder_init(&speex_nb_mode);
    //设置质量为8(15kbps)
    tmp=8;
    speex_encoder_ctl(state, SPEEX_SET_QUALITY, &tmp);
    inFile = argv[1];
    fin = fopen(inFile, "r");
    //初始化结构使他们保存数据
    speex_bits_init(&bits);
    while (1) {
        //读入一帧16bits的声音
        fread(in, sizeof(short), FRAME_SIZE, fin);
        if (feof(fin))
        break;
        //把16bits的值转化为float,以便speex库可以在上面工作
        for (i=0;i<FRAME_SIZE;i++)
        input[i]=in[i];
        //清空这个结构体里所有的字节,以便我们可以编码一个新的帧
        speex_bits_reset(&bits);
        //对帧进行编码
        speex_encode(state, input, &bits);
        //把bits拷贝到一个利用写出的char型数组
        nbBytes = speex_bits_write(&bits, cbits, 200);
        //首先写出帧的大小,这是sampledec文件需要的一个值,但是你的应用程序中可能不一样
        fwrite(&nbBytes, sizeof(int), 1, stdout);
        //写出压缩后的数组
        fwrite(cbits, 1, nbBytes, stdout);
    }
    //释放编码器状态量
    speex_encoder_destroy(state);
    //释放bit_packing结构
    speex_bits_destroy(&bits);
    fclose(fin);
    return 0;
}
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);

}
void gviSpursSpeexEncode(SpursSpeexTaskOutput *spuTaskOut)
{	
	short *inBuffer;
	float *speexBuffer;
	char *outBuffer;
	unsigned int i;
	spuTaskOut->mSpeexEncodedFrameSize = 0;
	spuTaskOut->mSpeexInitialized = 1;
	spuTaskOut->mSpeexSamplesPerFrame = 0;
	spuTaskOut->mSpeexReturnCode = 0;
	spuTaskOut->mSpeexOutBufferSize = 0;

	speexBuffer = (float *)memalign(16, gviSpursSpeexTaskDesc.mInputBufferSize * sizeof(float));
	inBuffer = (short *)memalign(16, gviSpursSpeexTaskDesc.mInputBufferSize * sizeof(short));
	outBuffer = (char *)memalign(16, gviSpursSpeexTaskDesc.mOutputBufferSize);
	
	memset(speexBuffer, 0, gviSpursSpeexTaskDesc.mInputBufferSize * sizeof(float));
	memset(inBuffer, 0, gviSpursSpeexTaskDesc.mInputBufferSize * sizeof(short));
	memset(outBuffer, 0, gviSpursSpeexTaskDesc.mOutputBufferSize);

	cellDmaGet(inBuffer, (uint64_t)gviSpursSpeexTaskDesc.mInputBuffer, gviSpursSpeexTaskDesc.mInputBufferSize * sizeof(short), DMA_TAG(1), 0,0);
	cellDmaWaitTagStatusAll(DMA_MASK(1));
		
	// convert the input to floats for encoding
	for(i = 0 ; i < gviSpursSpeexTaskDesc.mInputBufferSize ; i++)
		speexBuffer[i] = inBuffer[i];

	// (re)initialize the bits struct
	speex_bits_init_buffer(&gviSpursSpeexBits,gviSpursSpeexBitsBuffer,sizeof(gviSpursSpeexBitsBuffer));

	// flush the bits
	speex_bits_reset(&gviSpursSpeexBits);

	// encode the frame
	speex_encode(gviSpursSpeexStateBuffer, speexBuffer, &gviSpursSpeexBits);
	// write the bits to the output
	spuTaskOut->mSpeexOutBufferSize = speex_bits_write(&gviSpursSpeexBits, (char *)outBuffer, gviSpursSpeexTaskDesc.mEncodedFrameSize);
	//spuDebugPrintf("[Speex][SPU] transferring data back, output size should be: %d\n", gviSpursSpeexTaskDesc.mOutputBufferSize>16?gviSpursSpeexTaskDesc.mOutputBufferSize:16);
	cellDmaPut(outBuffer, (uint64_t)gviSpursSpeexTaskDesc.mOutputBuffer, gviSpursSpeexTaskDesc.mOutputBufferSize, DMA_TAG(1), 0, 0);
	cellDmaWaitTagStatusAll(DMA_MASK(1));
	//spuDebugPrintf("[Speex][SPU] done transferring data back\n");
	free(speexBuffer);
	free(inBuffer);
	free(outBuffer);
	spuTaskOut->mSpeexReturnCode = 0;
}
Exemple #28
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;
}
Exemple #29
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;
}
void gviSpeexEncode(GVByte * out, const GVSample * in)
{
	int bytesWritten;
	int i;

	// convert the input to floats for encoding
	for(i = 0 ; i < gviSpeexSamplesPerFrame ; i++)
		gviSpeexBuffer[i] = in[i];

	// flush the bits
	speex_bits_reset(&gviSpeexBits);

	// encode the frame
	speex_encode(gviSpeexEncoderState, gviSpeexBuffer, &gviSpeexBits);

	// write the bits to the output
	bytesWritten = speex_bits_write(&gviSpeexBits, (char *)out, gviSpeexEncodedFrameSize);
	GS_ASSERT(bytesWritten == gviSpeexEncodedFrameSize);
}