Ejemplo n.º 1
1
JNIEXPORT jint JNICALL Java_org_thoughtcrime_redphone_codec_SpeexCodec_decode (JNIEnv *env, jobject obj, jbyteArray encArr, jshortArray decArr, jint encLen ){
  cenv = env;
  if( !initialized ) {
    logv(env, "tried to decode without initializing" );
    return -1;
  }

  if (decArr == NULL) {
    logv(env, "Speex decode passed a null decode buffer" );
    return -1;
  }

  jint dec_buffer_len = env->GetArrayLength( decArr );
  int dec_buffer_idx = 0;

  jbyte *jb_enc_stream;
  char *enc_stream;
  SpeexBits *dbits = NULL; //if this is null, speex will do PLC for us
  if( !env->IsSameObject( encArr, NULL ) ) {
    jb_enc_stream = env->GetByteArrayElements( encArr, NULL );
    enc_stream = (char *)jb_enc_stream;
    speex_bits_read_from( &dec_bits, enc_stream, encLen );
    env->ReleaseByteArrayElements( encArr, jb_enc_stream, JNI_ABORT );
    dbits = &dec_bits;
  } else {
    //    logv( env, "null encArr" );
  }

  while( 0 == speex_decode_int( dec, dbits, dec_buffer+dec_buffer_idx ) ) {
    dec_buffer_idx += dec_frame_size;
    if( dec_buffer_idx + dec_frame_size >= dec_buffer_len ) {
      logv( env, "out of space in the decArr buffer, idx=%d", dec_buffer_idx );
      break;
    }

    if( dec_buffer_idx + dec_frame_size >= dec_frame_size * MAX_DEC_FRAMES ) {
      logv( env, "out of space in the dec_buffer buffer, idx=%d", dec_buffer_idx );
      break;
    }

    if( dbits == NULL ) {
      //      logv(env, "did PLC" );
      break;//only generate one frame for PLC...
    }
  }
    
  env->SetShortArrayRegion( decArr, 0, dec_buffer_idx, dec_buffer );
  return dec_buffer_idx;
}
Ejemplo n.º 2
0
void ms_speex_dec_process(MSSpeexDec *obj)
{
	MSFifo *outf=obj->outf[0];
	MSQueue *inq=obj->inq[0];
	gint16 *output;
	gint gran=obj->frame_size*2;
	gint i;
	MSMessage *m;
	
	g_return_if_fail(inq!=NULL);
	g_return_if_fail(outf!=NULL);
	
	m=ms_queue_get(inq);
	g_return_if_fail(m!=NULL);
	speex_bits_reset(&obj->bits);
	ms_fifo_get_write_ptr(outf,gran,(void**)&output);
	g_return_if_fail(output!=NULL);
	if (m->data!=NULL){
		
		speex_bits_read_from(&obj->bits,m->data,m->size);
		/* decode */
		speex_decode_int(obj->speex_state,&obj->bits,(short*)output);
	}else{
		/* we have a missing packet */
		speex_decode_int(obj->speex_state,NULL,(short*)output);
	}
	ms_message_destroy(m);
	
}
Ejemplo n.º 3
0
void decode(int header) {
  FILE * fin = fopen("audiopacket2.spx", "r");
  FILE * fout = fopen("decoded_audio.raw", "w");
  int i;
  short out[FRAME_SIZE];
  float output[FRAME_SIZE];
  char cbits[331-20];

  SpeexBits bits;
  void * state;
  
  state = speex_decoder_init(&speex_nb_mode);
  speex_bits_init(&bits);

  while(1) {
    if(feof(fin))
      break;

    /* on lit 307 octets (un paquet) vers cbits */
    fread(cbits, 1, 331-20, fin);
    /* on le copie vers une structure bit-stream */
    speex_bits_read_from(&bits, cbits+header, 331-20-header);
    /* on decode */
    speex_decode(state, &bits, output);

    for(i=0 ; i< FRAME_SIZE ; i++)
      out[i]= output[i];

    fwrite(out, sizeof(short), FRAME_SIZE, fout);
  }
}
Ejemplo n.º 4
0
int main(int argc, char **argv)
{
   char *outFile;
   FILE *fout;
   /*Holds the audio that will be written to file (16 bits per sample)*/
   short out[FRAME_SIZE];
   /*Speex handle samples as float, so we need an array of floats*/
   float output[FRAME_SIZE];
   char cbits[200];
   int nbBytes;
   /*Holds the state of the decoder*/
   void *state;
   /*Holds bits so they can be read and written to by the Speex routines*/
   SpeexBits bits;
   int i, tmp;

   /*Create a new decoder state in narrowband mode*/
   state = speex_decoder_init(&speex_nb_mode);

   /*Set the perceptual enhancement on*/
   tmp=1;
   speex_decoder_ctl(state, SPEEX_SET_ENH, &tmp);

   outFile = argv[1];
   fout = fopen(outFile, "w");

   /*Initialization of the structure that holds the bits*/
   speex_bits_init(&bits);
   while (1)
   {
      /*Read the size encoded by sampleenc, this part will likely be
        different in your application*/
      fread(&nbBytes, sizeof(int), 1, stdin);
      fprintf (stderr, "nbBytes: %d\n", nbBytes);
      if (feof(stdin))
         break;

      /*Read the "packet" encoded by sampleenc*/
      fread(cbits, 1, nbBytes, stdin);
      /*Copy the data into the bit-stream struct*/
      speex_bits_read_from(&bits, cbits, nbBytes);

      /*Decode the data*/
      speex_decode(state, &bits, output);

      /*Copy from float to short (16 bits) for output*/
      for (i=0;i<FRAME_SIZE;i++)
         out[i]=output[i];

      /*Write the decoded audio to file*/
      fwrite(out, sizeof(short), FRAME_SIZE, fout);
   }

   /*Destroy the decoder state*/
   speex_decoder_destroy(state);
   /*Destroy the bit-stream truct*/
   speex_bits_destroy(&bits);
   fclose(fout);
   return 0;
}
Ejemplo n.º 5
0
static int libspeex_decode_frame(AVCodecContext *avctx,
                                 void *data, int *data_size,
                                 AVPacket *avpkt)
{
    const uint8_t *buf = avpkt->data;
    int buf_size = avpkt->size;
    LibSpeexContext *s = avctx->priv_data;
    int16_t *output = data, *end;
    int i, num_samples;

    num_samples = s->frame_size * avctx->channels;
    end = output + *data_size / sizeof(*output);

    speex_bits_read_from(&s->bits, buf, buf_size);

    for (i = 0; speex_bits_remaining(&s->bits) && output + num_samples < end; i++) {
        int ret = speex_decode_int(s->dec_state, &s->bits, output);
        if (ret <= -2) {
            av_log(avctx, AV_LOG_ERROR, "Error decoding Speex frame.\n");
            return -1;
        } else if (ret == -1)
            // end of stream
            break;

        if (avctx->channels == 2)
            speex_decode_stereo_int(output, s->frame_size, &s->stereo);

        output += num_samples;
    }

    avctx->frame_size = s->frame_size * i;
    *data_size = avctx->channels * avctx->frame_size * sizeof(*output);
    return buf_size;
}
Ejemplo n.º 6
0
int voice_play(const char *buf, int length, int codec)
{
	if (length <= 0)
		return 0;

	if (codec == EKG_CODEC_SPEEX) {
#if HAVE_SPEEX
		spx_int16_t speex_output[320];

		speex_bits_read_from(&speex_dec_bits, buf, length);
		speex_decode_int(voice_speex_dec, &speex_dec_bits, speex_output);		/* XXX, != 0 return? */

		if (write(voice_fd, speex_output, sizeof(speex_output)) != sizeof(speex_output))
			return -1;

		return 0;
#else
		printf("voice_play() received speex packet, but HAVE_SPEEX\n");
		return -1;
#endif
	}

	if (codec == EKG_CODEC_GSM) {
#if HAVE_GSM
		const int ramki_dwie = 33 + 33;
		gsm_signal gsm_output[160];

		const char *pos = buf;

		while (pos <= (buf + length - ramki_dwie)) {
			switch (codec) {
				case EKG_CODEC_GSM:
					if (gsm_decode(voice_gsm_dec, (unsigned char *) pos, gsm_output)) return -1;
					pos += 33;
					break;
			}

			if (write(voice_fd, gsm_output, 320) != 320)
				return -1;

			switch (codec) {
				case EKG_CODEC_GSM:
					if (gsm_decode(voice_gsm_dec, (unsigned char *) pos, gsm_output)) return -1;
					pos += 33;
					break;
			}


			if (write(voice_fd, gsm_output, 320) != 320)
				return -1;
		}
		return 0;
#else
		printf("voice_play() received gsm packet, but HAVE_GSM\n");
		return -1;
#endif
	}

	return -1;
}
Ejemplo n.º 7
0
signed short* decodeSPEEX(BYTE *data)
{
	speex_bits_read_from(&obits, (char*)data, SPEEX_SIZE);
	speex_decode_int(pDec, &obits, out_short);
	speex_bits_reset(&obits);
	return (signed short*)(&out_short[0]);
}
Ejemplo n.º 8
0
/*****************************************************************************
 * DecodePacket: decodes a Speex packet.
 *****************************************************************************/
static block_t *DecodePacket( decoder_t *p_dec, ogg_packet *p_oggpacket )
{
    decoder_sys_t *p_sys = p_dec->p_sys;

    if( p_oggpacket->bytes )
    {
        /* Copy Ogg packet to Speex bitstream */
        speex_bits_read_from( &p_sys->bits, (char *)p_oggpacket->packet,
                              p_oggpacket->bytes );
        p_sys->i_frame_in_packet = 0;
    }

    /* Decode one frame at a time */
    if( p_sys->i_frame_in_packet < p_sys->p_header->frames_per_packet )
    {
        block_t *p_aout_buffer;
        if( p_sys->p_header->frame_size == 0 )
            return NULL;

        p_aout_buffer =
            decoder_NewAudioBuffer( p_dec, p_sys->p_header->frame_size );
        if( !p_aout_buffer )
        {
            return NULL;
        }

        switch( speex_decode_int( p_sys->p_state, &p_sys->bits,
                                  (int16_t *)p_aout_buffer->p_buffer ) )
        {
            case -2:
                msg_Err( p_dec, "decoding error: corrupted stream?" );
            case -1: /* End of stream */
                return NULL;
        }

        if( speex_bits_remaining( &p_sys->bits ) < 0 )
        {
            msg_Err( p_dec, "decoding overflow: corrupted stream?" );
        }

        if( p_sys->p_header->nb_channels == 2 )
            speex_decode_stereo_int( (int16_t *)p_aout_buffer->p_buffer,
                                     p_sys->p_header->frame_size,
                                     &p_sys->stereo );

        /* Date management */
        p_aout_buffer->i_pts = date_Get( &p_sys->end_date );
        p_aout_buffer->i_length =
            date_Increment( &p_sys->end_date, p_sys->p_header->frame_size )
            - p_aout_buffer->i_pts;

        p_sys->i_frame_in_packet++;

        return p_aout_buffer;
    }
    else
    {
        return NULL;
    }
}
Ejemplo n.º 9
0
int Speex_2_Pcm16( 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*) out_buf;
  int frames_out  = 0;

  ss = (SpeexState*) h_codec;
  if (!ss || channels!=1)
    return -1;
    
  speex_bits_read_from(&ss->decoder.bits, (char*)in_buf, size);

  /* We don't know where frame boundaries are,
     but the minimum frame size is 43 */
  while (speex_bits_remaining(&ss->decoder.bits)>40) {
    int ret;
	
    ret = speex_decode_int(ss->decoder.state, &ss->decoder.bits, pcm);
    pcm+= ss->frame_size;
	
    if (ret==-2) {
      ERROR("while calling speex_decode\n");
      return -1;
    }
	
    if (ret==-1) break;
	
    frames_out++;  
  }
    
  return frames_out*ss->frame_size*sizeof(short);
}
Ejemplo n.º 10
0
// renyang - 替音訊解碼
void Call::decodeAudioData(char *buf, int len)
{
#ifdef REN_DEBUG
	qWarning("Call::decodeAudioData()");
#endif
	if (dec_state)
	{
		// renyang - Initializes the bit-stream from the data in an area of memory
		// renyang - 把一連串的buf轉到bit-stream
		speex_bits_read_from(&bits, buf, len);
		// renyang - 把bits解碼到outBuffer(為float型態)
		// renyang - 當<0表示解碼失敗
		if (speex_decode(dec_state, &bits, outBuffer) < 0)
		{
			emit warning("Warning: wrong decryption key or stream corrupted!");
			disableDecrypt();
		}
		else
		{
			// renyang - 來到這裡表示解碼成功
			// renyang - 把解碼之後的音訊(outBuffer)放到soundBuffer中
			putData(outBuffer, frame_size);
		}
	}
}
Ejemplo n.º 11
0
int speex_jitter_get(SpeexJitter *jitter, spx_int16_t *out, int *current_timestamp, void** userData)
{
   int i;
   int jbRet;	/* results returned by the JB */
   int ourRet;	/* result that we will return */
   spx_int32_t activity;
   char data[2048];
   JitterBufferPacket packet;
   packet.data = data;
   packet.len = 2048;  /* AAAAARGH: it took a week to find and add this missing line */
   
   if (jitter->valid_bits)
   {
      /* Try decoding last received packet */
      jbRet = speex_decode_int(jitter->dec, &jitter->current_packet, out);
      if (jbRet == 0)
      {
         jitter_buffer_tick(jitter->packets);
         return 1;
      } else {
         jitter->valid_bits = 0;
      }
   }

   jbRet = jitter_buffer_get(jitter->packets, &packet, jitter->frame_size, NULL);
   
   if (jbRet != JITTER_BUFFER_OK)
   {
	  /* no packet found, so no corresponding user-data */
      *userData = NULL;

      /* No packet found... extrapolate one */

      /*fprintf (stderr, "lost/late frame\n");*/
      /*Packet is late or lost*/
      speex_decode_int(jitter->dec, NULL, out);
	  
	  ourRet = 2;
   } else {
	  /* found a packet, so there is corresponding user-data */
	  *userData = (void*)(packet.user_data);
   
      speex_bits_read_from(&jitter->current_packet, packet.data, packet.len);
      /* Decode packet */
      jbRet = speex_decode_int(jitter->dec, &jitter->current_packet, out);
      if (jbRet == 0) {
         ourRet = 0;		
         jitter->valid_bits = 1;
      } else {
         /* Error while decoding */
         ourRet = 3;
         for (i=0;i<jitter->frame_size;i++) out[i]=0;
      }
   }
   speex_decoder_ctl(jitter->dec, SPEEX_GET_ACTIVITY, &activity);
   if (activity < jitter->activity_threshold) 
      jitter_buffer_update_delay(jitter->packets, &packet, NULL); 
   jitter_buffer_tick(jitter->packets);
   return ourRet;
}
Ejemplo n.º 12
0
static switch_status_t switch_speex_decode(switch_codec_t *codec,
										   switch_codec_t *other_codec,
										   void *encoded_data,
										   uint32_t encoded_data_len,
										   uint32_t encoded_rate, void *decoded_data, uint32_t *decoded_data_len, uint32_t *decoded_rate,
										   unsigned int *flag)
{
	struct speex_context *context = codec->private_info;
	short *buf;

	if (!context) {
		return SWITCH_STATUS_FALSE;
	}


	buf = decoded_data;
	if (*flag & SWITCH_CODEC_FLAG_SILENCE) {
		speex_decode_int(context->decoder_state, NULL, buf);
	} else {
		speex_bits_read_from(&context->decoder_bits, (char *) encoded_data, (int) encoded_data_len);
		speex_decode_int(context->decoder_state, &context->decoder_bits, buf);
	}
	*decoded_data_len = codec->implementation->decoded_bytes_per_packet;

	return SWITCH_STATUS_SUCCESS;
}
Ejemplo n.º 13
0
static int decode_audio(sh_audio_t *sh, unsigned char *buf,
                        int minlen, int maxlen) {
  double pts;
  context_t *ctx = sh->context;
  int len, framelen, framesamples;
  char *packet;
  int i, err;
  speex_decoder_ctl(ctx->dec_context, SPEEX_GET_FRAME_SIZE, &framesamples);
  framelen = framesamples * ctx->hdr->nb_channels * sizeof(short);
  if (maxlen < ctx->hdr->frames_per_packet * framelen) {
    mp_msg(MSGT_DECAUDIO, MSGL_V, "maxlen too small in decode_audio\n");
    return -1;
  }
  len = ds_get_packet_pts(sh->ds, (unsigned char **)&packet, &pts);
  if (len <= 0) return -1;
  if (sh->pts == MP_NOPTS_VALUE)
    sh->pts = 0;
  if (pts != MP_NOPTS_VALUE) {
    sh->pts = pts;
    sh->pts_bytes = 0;
  }
  speex_bits_read_from(&ctx->bits, packet, len);
  i = ctx->hdr->frames_per_packet;
  do {
    err = speex_decode_int(ctx->dec_context, &ctx->bits, (short *)buf);
    if (err == -2)
      mp_msg(MSGT_DECAUDIO, MSGL_ERR, "Error decoding file.\n");
    if (ctx->hdr->nb_channels == 2)
      speex_decode_stereo_int((short *)buf, framesamples, &ctx->stereo);
    buf = &buf[framelen];
  } while (--i > 0);
  sh->pts_bytes += ctx->hdr->frames_per_packet * framelen;
  return ctx->hdr->frames_per_packet * framelen;
}
Ejemplo n.º 14
0
int qSpeexDecode(QSpeexCodecPtr handle, void* inputBytes, int inputSize, void* outputSamples, int outputSize)
{
	int offset, remaining;
	short *out = (short*)outputSamples;
	
	/* If there is no input to read, we certainly can't read it. */
	if (inputBytes != NULL) {
		speex_bits_read_from(&handle->decBits, inputBytes, inputSize);
	}
	
	for (offset=0; offset<outputSize; offset+=handle->frameSize) {
		if (inputBytes != NULL) {
			if (!speex_bits_remaining(&handle->decBits)) {
				// Ran out of input data
				return 2;
			}
			speex_decode_int(handle->decState, &handle->decBits, out+offset);
		}
		else {
			/* Extrapolate output-buffer based on current decoder state. */
			speex_decode_int(handle->decState, NULL, out+offset);		
		}
	}
	remaining = speex_bits_remaining(&handle->decBits);
	if (remaining >= 8) {
		/* If less than a byte is left over, that's OK. */
		fprintf(stderr, "qSpeexDecode(): %d bits left over\n", remaining);
		return 1; // Still have encoded bits left over
	}
	else return 0; // A-OK!!
}
Ejemplo n.º 15
0
/*! \brief convert and store into outbuf */
static int speextolin_framein(struct ast_trans_pvt *pvt, struct ast_frame *f)
{
	struct speex_coder_pvt *tmp = pvt->pvt;

	/* Assuming there's space left, decode into the current buffer at
	   the tail location.  Read in as many frames as there are */
	int x;
	int res;
	int16_t *dst = pvt->outbuf.i16;
	/* XXX fout is a temporary buffer, may have different types */
#ifdef _SPEEX_TYPES_H
	spx_int16_t fout[1024];
#else
	float fout[1024];
#endif

	if (f->datalen == 0) {  /* Native PLC interpolation */
		if (pvt->samples + tmp->framesize > BUFFER_SAMPLES) {
			ast_log(LOG_WARNING, "Out of buffer space\n");
			return -1;
		}
#ifdef _SPEEX_TYPES_H
		speex_decode_int(tmp->speex, NULL, dst + pvt->samples);
#else
		speex_decode(tmp->speex, NULL, fout);
		for (x=0;x<tmp->framesize;x++) {
			dst[pvt->samples + x] = (int16_t)fout[x];
		}
#endif
		pvt->samples += tmp->framesize;
		pvt->datalen += 2 * tmp->framesize; /* 2 bytes/sample */
		return 0;
	}

	/* Read in bits */
	speex_bits_read_from(&tmp->bits, f->data.ptr, f->datalen);
	for (;;) {
#ifdef _SPEEX_TYPES_H
		res = speex_decode_int(tmp->speex, &tmp->bits, fout);
#else
		res = speex_decode(tmp->speex, &tmp->bits, fout);
#endif
		if (res < 0)
			break;
		if (pvt->samples + tmp->framesize > BUFFER_SAMPLES) {
			ast_log(LOG_WARNING, "Out of buffer space\n");
			return -1;
		}
		for (x = 0 ; x < tmp->framesize; x++)
			dst[pvt->samples + x] = (int16_t)fout[x];
		pvt->samples += tmp->framesize;
		pvt->datalen += 2 * tmp->framesize; /* 2 bytes/sample */
	}
	return 0;
}
Ejemplo n.º 16
0
int ph_speexwb_decode(void *ctx, const void *src, int srcsize, void *dst, int dstsize)
{
  int i;
  struct speexdec *speex = (struct speexdec *)ctx; 

  speex_bits_read_from(&speex->bits, src, srcsize);
  speex_decode_int(speex->st, &speex->bits, dst);
  speex_bits_reset(&speex->bits);

  return SPEEX_WB_FRAME_SAMPLES*2;

}
Ejemplo n.º 17
0
JNIEXPORT jint JNICALL Java_com_speex_Speex_decode(JNIEnv *env,
		jobject obj, jbyteArray encoded, jshortArray lin, jint size) {

	jbyte buffer[dec_frame_size];
	jshort output_buffer[size];
	jsize encoded_length = size;
	int nsamples = (size - 1) / dec_frame_size + 1;
    int i, offset = 0, tot_shorts = 0;

	if (!codec_open)
	return 0;

	speex_bits_reset(&dbits);

	// 把数据写入buffer
    for(i = 0; i < nsamples; i++){
        if(offset + i * dec_frame_size + dec_frame_size > size) {
        	env->GetByteArrayRegion(encoded, offset + i * dec_frame_size,
        			size - (offset + i * dec_frame_size), buffer);
        	speex_bits_read_from(&dbits, (char *) buffer, size - (offset + i * dec_frame_size));
        } else {
        	env->GetByteArrayRegion(encoded, offset + i * dec_frame_size,
        			dec_frame_size, buffer);
        	speex_bits_read_from(&dbits, (char *) buffer, dec_frame_size);
        }
    }
//	env->GetByteArrayRegion(encoded, 0, encoded_length, buffer);
//	// buffer数据写入dbits
//	speex_bits_read_fdrom(&dbits, (char *) buffer, encoded_length);

    // dbits数据写入output_buffer
	speex_decode_int(dec_state, &dbits, output_buffer);
	// TODO
	env->SetShortArrayRegion(lin, 0, encoded_length, output_buffer);
	/*env->SetShortArrayRegion(lin, 0, dec_frame_size, output_buffer);*/

	/*return (jint) dec_frame_size;*/
	/*return (jint) encoded_length;*/
	return (jint) encoded_length;
}
Ejemplo n.º 18
0
Boolean CASpeexDecoder::GenerateFrames()
{
    Boolean ret = true;
    int result;

    mBDCStatus = kBDCStatusOK;
    SpeexFramePacket &sfp = mSpeexFPList.front();

    speex_bits_read_from(&mSpeexBits, reinterpret_cast<char*> (mBDCBuffer.GetData()), sfp.bytes);

    if (sfp.frames > 0 && (sfp.frames - mSpeexHeader.frame_size * mSpeexHeader.frames_per_packet > 0)) {
        UInt32 zeroBytes = mOutputFormat.FramesToBytes(sfp.frames - mSpeexHeader.frame_size * mSpeexHeader.frames_per_packet);
        memset(mOutBuffer + mOutBufferUsedSize, 0, zeroBytes);
        mOutBufferUsedSize += zeroBytes;
    }

    for (SInt32 i = 0; i < mSpeexHeader.frames_per_packet; i++) {
        if (mOutputFormat.mFormatFlags & kAudioFormatFlagsNativeFloatPacked != 0)
            result = speex_decode(mSpeexDecoderState, &mSpeexBits, reinterpret_cast<float*> (mOutBuffer + mOutBufferUsedSize));
        else
            result = speex_decode_int(mSpeexDecoderState, &mSpeexBits, reinterpret_cast<spx_int16_t*> (mOutBuffer + mOutBufferUsedSize));

        if (result < 0) {
            mBDCStatus = kBDCStatusAbort;
            return false;
        }

        if (mSpeexHeader.nb_channels == 2) {
            if (mOutputFormat.mFormatFlags & kAudioFormatFlagsNativeFloatPacked != 0)
                speex_decode_stereo(reinterpret_cast<float*> (mOutBuffer + mOutBufferUsedSize), mSpeexHeader.frame_size, &mSpeexStereoState);
            else
                speex_decode_stereo_int(reinterpret_cast<spx_int16_t*> (mOutBuffer + mOutBufferUsedSize), mSpeexHeader.frame_size, &mSpeexStereoState);
        }
        mOutBufferUsedSize += mOutputFormat.FramesToBytes(mSpeexHeader.frame_size);
    }

    if (sfp.frames == 0) {
        mNumFrames += mSpeexHeader.frame_size * mSpeexHeader.frames_per_packet;
    } else if (sfp.frames > 0) {
        mNumFrames += sfp.frames;
        if (mSpeexHeader.frame_size * mSpeexHeader.frames_per_packet - sfp.frames != 0)
            mOutBufferStart += mOutputFormat.FramesToBytes(mSpeexHeader.frame_size * mSpeexHeader.frames_per_packet - sfp.frames);
    } else {
        mNumFrames -= sfp.frames;
    }

    mBDCBuffer.Zap(sfp.bytes);
    mSpeexFPList.erase(mSpeexFPList.begin());

    return ret;
}
Ejemplo n.º 19
0
void *os_sound_start_thread(void *_ca)
{
  jcall_t *ca = (jcall_t*)_ca;
  char data_in[160];
  short sp_data_in_s[640];
  float sp_data_in_f[640];
  int have_more;
  int timestamp = 0;
  int i;

  while (ca->enable_audio != -1)
    {
      memset(data_in, 0, 160);
      /* receive ONE packet */
      i = rtp_session_recv_with_ts(ca->rtp_session, data_in, 160, timestamp, &have_more);

      speex_bits_reset(&ca->dec_speex_bits);
      speex_bits_read_from(&ca->dec_speex_bits, data_in, i);

      while(1)
	{
	  int k;
	  k = speex_decode(ca->speex_dec, &ca->dec_speex_bits, sp_data_in_f);
	  if (k==-2)
	    {
	      exit(0);
	    }
	  else if (k==-1)
	    {
	      break;
	    }
	  else if (k==0)
	    {
	      int j;
	      for (j=0;j<ca->speex_fsize;j++)
		{
		  if (sp_data_in_f[j]>32767)
		    sp_data_in_f[j]=32767;
		  if (sp_data_in_f[j]<-32767)
		    sp_data_in_f[j]=-32767;
		  sp_data_in_s[j] = (short) sp_data_in_f[j];
		}
	      write(fd, sp_data_in_s, ca->speex_fsize);
	    }
	}
      timestamp += 160;
    }
  return NULL;
}
Ejemplo n.º 20
0
void gviSpeexDecodeSet(GVSample * out, const GVByte * in, GVDecoderData data)
{
	int rcode;
	int i;

	// read the data into the bits
	speex_bits_read_from(&gviSpeexBits, (char *)in, gviSpeexEncodedFrameSize);

	// decode it
	rcode = speex_decode((void *)data, &gviSpeexBits, gviSpeexBuffer);
	GS_ASSERT(rcode == 0);

	// convert the output from floats
	for(i = 0 ; i < gviSpeexSamplesPerFrame ; i++)
		out[i] = (GVSample)gviSpeexBuffer[i];
}
Ejemplo n.º 21
0
static int decode(struct audec_state *st, int16_t *sampv,
		  size_t *sampc, const uint8_t *buf, size_t len)
{
	const size_t n = st->channels * st->frame_size;
	size_t i = 0;

	/* Read into bit-stream */
	speex_bits_read_from(&st->bits, (char *)buf, (int)len);

	/* Handle multiple Speex frames in one RTP packet */
	while (speex_bits_remaining(&st->bits) >= MIN_FRAME_SIZE) {
		int ret;

		if (*sampc < n)
			return ENOMEM;

		ret = speex_decode_int(st->dec, &st->bits,
				       (int16_t *)&sampv[i]);
		if (ret < 0) {
			if (-1 == ret) {
			}
			else if (-2 == ret) {
				warning("speex: decode: corrupt stream\n");
			}
			else {
				warning("speex: decode: speex_decode_int:"
					" ret=%d\n", ret);
			}
			break;
		}

		/* Transforms a mono frame into a stereo frame
		   using intensity stereo info */
		if (2 == st->channels) {
			speex_decode_stereo_int((int16_t *)&sampv[i],
						st->frame_size,
						&st->stereo);
		}

		i      += n;
		*sampc -= n;
	}

	*sampc = i;

	return 0;
}
Ejemplo n.º 22
0
static int libspeex_decode_frame(AVCodecContext *avctx, void *data,
                                 int *got_frame_ptr, AVPacket *avpkt)
{
    uint8_t *buf = avpkt->data;
    int buf_size = avpkt->size;
    LibSpeexContext *s = avctx->priv_data;
    AVFrame *frame     = data;
    int16_t *output;
    int ret, consumed = 0;

    /* get output buffer */
    frame->nb_samples = s->frame_size;
    if ((ret = ff_get_buffer(avctx, frame, 0)) < 0) {
        av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
        return ret;
    }
    output = (int16_t *)frame->data[0];

    /* if there is not enough data left for the smallest possible frame or the
       next 5 bits are a terminator code, reset the libspeex buffer using the
       current packet, otherwise ignore the current packet and keep decoding
       frames from the libspeex buffer. */
    if (speex_bits_remaining(&s->bits) < 5 ||
        speex_bits_peek_unsigned(&s->bits, 5) == 0xF) {
        /* check for flush packet */
        if (!buf || !buf_size) {
            *got_frame_ptr = 0;
            return buf_size;
        }
        /* set new buffer */
        speex_bits_read_from(&s->bits, buf, buf_size);
        consumed = buf_size;
    }

    /* decode a single frame */
    ret = speex_decode_int(s->dec_state, &s->bits, output);
    if (ret <= -2) {
        av_log(avctx, AV_LOG_ERROR, "Error decoding Speex frame.\n");
        return AVERROR_INVALIDDATA;
    }
    if (avctx->channels == 2)
        speex_decode_stereo_int(output, s->frame_size, &s->stereo);

    *got_frame_ptr = 1;

    return consumed;
}
Ejemplo n.º 23
0
NS_IMETHODIMP
otSpeexDecoder::AcceptData(const char* data, PRInt32 len)
{
  DEBUG_DUMP1("otSpeexDecoder::AcceptData %d", len);
  char buf[2048];
  //memset(buf, 0, mFrameSize);

  //return mTarget->AcceptData(data ? data : buf, data ? len : mFrameSize);

  if (data) {
    speex_bits_read_from(mSpeexBits, (char*)data, len);
    speex_decode_int(mSpeexState, mSpeexBits, (spx_int16_t*)buf);
  } else
    speex_decode_int(mSpeexState, nsnull, (spx_int16_t*)buf);

  return mTarget->AcceptData(buf, mFrameSize);
}
Ejemplo n.º 24
0
void gviSpursSpeexDecodeAdd(SpursSpeexTaskOutput *spuTaskOut)
{
	char *inBuffer;
	float *speexBuffer;
	short *outBuffer;
	int rcode;
	unsigned int i;
	
	//spuDebugPrintf("[Speex][SPU] allocating buffers for decoding\n");
	speexBuffer = (float *)memalign(16, gviSpursSpeexTaskDesc.mOutputBufferSize * sizeof(float));
	outBuffer = (short *)memalign(16, gviSpursSpeexTaskDesc.mOutputBufferSize * sizeof(short));
	inBuffer = (char *)memalign(16, gviSpursSpeexTaskDesc.mInputBufferSize);

	memset(speexBuffer, 0, gviSpursSpeexTaskDesc.mOutputBufferSize * sizeof(float));
	memset(outBuffer, 0, gviSpursSpeexTaskDesc.mOutputBufferSize);
	memset(inBuffer, 0, gviSpursSpeexTaskDesc.mInputBufferSize * sizeof(short));
	
	
	//spuDebugPrintf("[Speex][SPU] done allocating, getting input data, inbuffer size: %d\n", gSpuSampleTaskDesc.mInputBufferSize);
	cellDmaGet(inBuffer, (uint64_t)gviSpursSpeexTaskDesc.mInputBuffer, gviSpursSpeexTaskDesc.mInputBufferSize, DMA_TAG(1), 0,0);
	cellDmaWaitTagStatusAll(DMA_MASK(1));
	// spuDebugPrintf("[Speex][SPU] done getting input data, preparing for speex to decode\n");
	// read the data into the bits
	// (re)initialize the bits struct
	speex_bits_init_buffer(&gviSpursSpeexBits,gviSpursSpeexBitsBuffer,sizeof(gviSpursSpeexBitsBuffer));

	speex_bits_read_from(&gviSpursSpeexBits, (char *)inBuffer, gviSpursSpeexTaskDesc.mEncodedFrameSize);

	// decode it
	rcode = speex_decode((void *)gviSpursSpeexStateBuffer, &gviSpursSpeexBits, speexBuffer);
	assert(rcode == 0);
	//spuDebugPrintf("[Speex][SPU] done with speex decode\n");
	// convert the output from floats
	for(i = 0 ; i < gviSpursSpeexTaskDesc.mOutputBufferSize ; i++)
		outBuffer[i] = (short)speexBuffer[i];
	
	//spuDebugPrintf("[Speex][SPU] transferring data back\n");
	cellDmaPut(outBuffer, (uint64_t)gviSpursSpeexTaskDesc.mOutputBuffer, gviSpursSpeexTaskDesc.mOutputBufferSize * sizeof(short), 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;
}
Ejemplo n.º 25
0
void speex_jitter_get(SpeexJitter *jitter, short *out, int *current_timestamp)
{
   int i;
   int ret;
   char data[2048];
   JitterBufferPacket packet;
   packet.data = data;
   
   if (jitter->valid_bits)
   {
      /* Try decoding last received packet */
      ret = speex_decode_int(jitter->dec, &jitter->current_packet, out);
      if (ret == 0)
      {
         jitter_buffer_tick(jitter->packets);
         return;
      } else {
         jitter->valid_bits = 0;
      }
   }

   ret = jitter_buffer_get(jitter->packets, &packet, NULL);
   
   if (ret != JITTER_BUFFER_OK)
   {
      /* No packet found */

      /*fprintf (stderr, "lost/late frame\n");*/
      /*Packet is late or lost*/
      speex_decode_int(jitter->dec, NULL, out);
   } else {
      speex_bits_read_from(&jitter->current_packet, packet.data, packet.len);
      /* Decode packet */
      ret = speex_decode_int(jitter->dec, &jitter->current_packet, out);
      if (ret == 0)
      {
         jitter->valid_bits = 1;
      } else {
         /* Error while decoding */
         for (i=0;i<jitter->frame_size;i++)
            out[i]=0;
      }
   }
   jitter_buffer_tick(jitter->packets);
}
Ejemplo n.º 26
0
JNIEXPORT jint Java_com_speex_encode_Speex_decode
    (JNIEnv *env, jobject obj, jbyteArray encoded, jshortArray lin, jint size) {

        jbyte buffer[dec_frame_size];
        jshort output_buffer[dec_frame_size];
        jsize encoded_length = size;

	if (!codec_open)
		return 0;

	env->GetByteArrayRegion(encoded, 0, encoded_length, buffer);
	speex_bits_read_from(&dbits, (char *)buffer, encoded_length);
	speex_decode_int(dec_state, &dbits, output_buffer);
	env->SetShortArrayRegion(lin, 0, dec_frame_size,
				 output_buffer);

	return (jint)dec_frame_size;
}
Ejemplo n.º 27
0
//*****************************************************************************
//
//! This function decodes a single frame of Speex encoded audio.
//!
//! /param pucInBuffer is the buffer that contains the Speex encoded audio.
//! /param ulInSize is the number of valid bytes in the pucInBuffer buffer.
//! /param pucOutBuffer is a pointer to the buffer to store decoded audio.
//! /param ulOutSize is the size of the buffer pointed to by the pucOutBuffer
//! pointer.
//!
//! This function will take a buffer of Speex encoded audio and decode it into
//! raw PCM audio.  The /e pusInBuffer parameter should contain a single frame
//! encoded Speex audio.  The /e pucOutBuffer will contain the decoded
//! audio after returning from this function.
//!
//! /return This function returns the number of decoded bytes in the
//! /e pucOutBuffer buffer.
//
//*****************************************************************************
int
SpeexDecode(unsigned char *pucInBuffer, unsigned long ulInSize,
            unsigned char *pucOutBuffer, unsigned long ulOutSize)
{
    int iBytes;

    //
    // Read in the bit stream to the Speex library.
    //
    speex_bits_read_from(&g_sSpeexDecoder.sBits, (char *)pucInBuffer, ulInSize);

    //
    // Decode one frame of data.
    //
    iBytes = speex_decode_int(g_sSpeexDecoder.State, &g_sSpeexDecoder.sBits,
                              (short *)pucOutBuffer);

    return(iBytes);
}
Ejemplo n.º 28
0
	void oper_one( const string& src, string& dst )
	{
		int block_size = dec_block_size( QUALITY, frame_size );
		int src_len = src.size();
		if( 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_read_from(&bits, (char*)(buff + i * block_size), block_size );
			speex_decode_int(state, &bits, out);

			dst.append( (char*)out, frame_size * sizeof(short) );
		}
	}
Ejemplo n.º 29
0
hsBool plSpeex::Decode(uint8_t *data, int size, int numFrames, int *numOutputBytes, short *out)
{
    if(!fInitialized) return false;
    *numOutputBytes = 0;

    hsReadOnlyStream stream( size, data );
    float *speexOutput = new float[fFrameSize];     // holds output from speex
    short *pOut = out;                              // pointer to output short buffer
    
    // create buffer for input data
    uint8_t *frameData = new uint8_t[fFrameSize];         // holds the current frames data to be decoded
    uint8_t frameLen;                                  // holds the length of the current frame being decoded.
    

    // Decode data
    for (int i = 0; i < numFrames; i++)
    {
        stream.ReadLE( &frameLen );           // read the length of the current frame to be decoded
        stream.Read( frameLen, frameData );     // read the data

        memset(speexOutput, 0, fFrameSize * sizeof(float));
        speex_bits_read_from(fBits, (char *)frameData, frameLen);   // give data to speex
        speex_decode(fDecoderState, fBits, speexOutput);                    // decode data 

        for(int j = 0; j < fFrameSize; j++)
        {
            pOut[j] = (short)(speexOutput[j]);          // convert floats to shorts
        }
        
        pOut += fFrameSize;                  
    }
    
    delete[] frameData;
    delete[] speexOutput;
    
    *numOutputBytes = (numFrames * fFrameSize) * sizeof(short);     // length of decoded voice data(out) in bytes
    if(*numOutputBytes == 0) 
        return false;

    return true;
}
//*****************************************************************************
//
//! This function decodes a single frame of Speex encoded audio.
//!
//! \param pui8InBuffer is the buffer that contains the Speex encoded audio.
//! \param ui32InSize is the number of valid bytes in the \e pui8InBuffer
//! buffer.
//! \param pui8OutBuffer is a pointer to the buffer to store decoded audio.
//! \param ui32OutSize is the size of the buffer pointed to by the
//! \e pui8OutBuffer pointer.
//!
//! This function will take a buffer of Speex encoded audio and decode it into
//! raw PCM audio.  The \e pui16InBuffer parameter should contain a single
//! frame encoded Speex audio.  The \e pui8OutBuffer will contain the decoded
//! audio after returning from this function.
//!
//! \return This function returns the number of decoded bytes in the
//! \e pui8OutBuffer buffer.
//
//*****************************************************************************
int32_t
SpeexDecode(uint8_t *pui8InBuffer, uint32_t ui32InSize, uint8_t *pui8OutBuffer,
            uint32_t ui32OutSize)
{
    int32_t i32Bytes;

    //
    // Read in the bit stream to the Speex library.
    //
    speex_bits_read_from(&g_sSpeexDecoder.sBits, (char *)pui8InBuffer,
                         ui32InSize);

    //
    // Decode one frame of data.
    //
    i32Bytes = speex_decode_int(g_sSpeexDecoder.pvState,
                                &g_sSpeexDecoder.sBits,
                                (int16_t *)pui8OutBuffer);

    return(i32Bytes);
}