Ejemplo n.º 1
0
JNIEXPORT jint JNICALL Java_org_sipdroid_codecs_SILK8_open
  (JNIEnv *env, jobject obj, jint compression) {
	int ret;

	if (codec_open++ != 0)
		return (jint)0;

	/* Set the samplingrate that is requested for the output */
    DecControl.sampleRate = 8000;
		
    /* Create decoder */
    ret = SKP_Silk_SDK_Get_Decoder_Size( &decSizeBytes );
    if( ret ) {
		__android_log_print(ANDROID_LOG_DEBUG, LOG_TAG, 
            "\n!!!!!!!! SKP_Silk_SDK_Get_Decoder_Size returned %d", ret );		
    }
#ifdef DEBUG_SILK8
    __android_log_print(ANDROID_LOG_DEBUG, LOG_TAG, 
            "### INIT Decoder decSizeBytes = %d\n", decSizeBytes); 		
#endif	
    psDec = malloc( decSizeBytes );

    /* Reset decoder */
    ret = SKP_Silk_SDK_InitDecoder( psDec );
    if( ret ) {
		__android_log_print(ANDROID_LOG_DEBUG, LOG_TAG, 
            "\n!!!!!!!! SKP_Silk_InitDecoder returned %d", ret );	
    }


    /* Create Encoder */
    ret = SKP_Silk_SDK_Get_Encoder_Size( &encSizeBytes );
    if( ret ) {
		__android_log_print(ANDROID_LOG_DEBUG, LOG_TAG, 
            "\n!!!!!!!! SKP_Silk_SDK_Get_Encoder_Size returned %d", ret );	
    }
#ifdef DEBUG_SILK8
    __android_log_print(ANDROID_LOG_DEBUG, LOG_TAG, 
            "### INIT Encoder encSizeBytes = %d\n", encSizeBytes); 		
#endif		
    psEnc = malloc( encSizeBytes );
    
    /* Reset Encoder */
    ret = SKP_Silk_SDK_InitEncoder( psEnc, &encControl );
    if( ret ) {
		__android_log_print(ANDROID_LOG_DEBUG, LOG_TAG, 
            "\n!!!!!!!! SKP_Silk_SDK_InitEncoder returned %d", ret );	
	}
    
    /* Set Encoder parameters */
    encControl.sampleRate           = fs_kHz * 1000;
    encControl.packetSize           = packetSize_ms * fs_kHz;
    encControl.packetLossPercentage = packetLoss_perc;
    encControl.useInBandFEC         = INBandFec_enabled;
    encControl.useDTX               = DTX_enabled;
    encControl.complexity           = compression;
    encControl.bitRate              = targetRate_bps;		
	
	return (jint)0;
}
Ejemplo n.º 2
0
//initialize SILK codec 
//sets number of 20mS(160 samples) frames per packet (1-5)
void SILK8_open(int fpp)
{
	//set number of 20 mS (160 samoles) frames per packet (1-5)
	if ((fpp <= MAX_INPUT_FRAMES) && (fpp > 0))
		skp_frames_pp = fpp;
	packetSize_ms = skp_frames_pp * 20;

	// Set the samplingrate that is requested for the output
	DecControl.sampleRate = 8000;

	// Create decoder 
	SKP_Silk_SDK_Get_Decoder_Size(&decSizeBytes);
	psDec = malloc(decSizeBytes);

	// Reset decoder 
	SKP_Silk_SDK_InitDecoder(psDec);

	// Create Encoder 
	SKP_Silk_SDK_Get_Encoder_Size(&encSizeBytes);
	psEnc = malloc(encSizeBytes);

	// Reset Encoder 
	SKP_Silk_SDK_InitEncoder(psEnc, &encControl);

	// Set Encoder parameters 
	encControl.sampleRate = 8000;
	encControl.packetSize = packetSize_ms * 8;	//samples per packet
	encControl.packetLossPercentage = packetLoss_perc;
	encControl.useInBandFEC = INBandFec_enabled;
	encControl.useDTX = DTX_enabled;
	encControl.complexity = compression;
	encControl.bitRate = targetRate_bps;
}
Ejemplo n.º 3
0
static int encode_update(struct auenc_state **aesp,
			 const struct aucodec *ac,
			 struct auenc_param *prm, const char *fmtp)
{
	struct auenc_state *st;
	int ret, err = 0;
	int32_t enc_size;
	(void)fmtp;

	if (!aesp || !ac || !prm)
		return EINVAL;
	if (*aesp)
		return 0;

	ret = SKP_Silk_SDK_Get_Encoder_Size(&enc_size);
	if (ret || enc_size <= 0)
		return EINVAL;

	st = mem_alloc(sizeof(*st), encode_destructor);
	if (!st)
		return ENOMEM;

	st->enc = mem_alloc(enc_size, NULL);
	if (!st->enc) {
		err = ENOMEM;
		goto out;
	}

	ret = SKP_Silk_SDK_InitEncoder(st->enc, &st->encControl);
	if (ret) {
		err = EPROTO;
		goto out;
	}

	st->encControl.API_sampleRate = ac->srate;
	st->encControl.maxInternalSampleRate = ac->srate;
	st->encControl.packetSize = prm->ptime * ac->srate / 1000;
	st->encControl.bitRate = 64000;
	st->encControl.complexity = 2;
	st->encControl.useInBandFEC = 0;
	st->encControl.useDTX = 0;

	re_printf("SILK encoder: %dHz, psize=%d, bitrate=%d, complex=%d,"
		  " fec=%d, dtx=%d\n",
		  st->encControl.API_sampleRate,
		  st->encControl.packetSize,
		  st->encControl.bitRate,
		  st->encControl.complexity,
		  st->encControl.useInBandFEC,
		  st->encControl.useDTX);

 out:
	if (err)
		mem_deref(st);
	else
		*aesp = st;

	return err;
}
Ejemplo n.º 4
0
bool VoiceEncoder_Silk::ResetState() {
	if (m_pEncoder)
		SKP_Silk_SDK_InitEncoder(m_pEncoder, &this->m_encControl);

	if (m_pDecoder)
		SKP_Silk_SDK_InitDecoder(m_pDecoder);

	m_bufOverflowBytes.Clear();
	return true;
}
Ejemplo n.º 5
0
bool VoiceEncoder_Silk::Init(int quality) {
	m_targetRate_bps = 25000;
	m_packetLoss_perc = 0;

	int encSizeBytes;
	SKP_Silk_SDK_Get_Encoder_Size(&encSizeBytes);
	m_pEncoder = malloc(encSizeBytes);
	SKP_Silk_SDK_InitEncoder(m_pEncoder, &this->m_encControl);

	int decSizeBytes;
	SKP_Silk_SDK_Get_Decoder_Size(&decSizeBytes);
	m_pDecoder = malloc(decSizeBytes);
	SKP_Silk_SDK_InitDecoder(m_pDecoder);

	return true;
}
Ejemplo n.º 6
0
    virtual bool Construct()
    {
      SKP_int32 sizeBytes = 0;
      if (SKP_Silk_SDK_Get_Encoder_Size(&sizeBytes) != 0)
        return false;

      m_state = malloc(sizeBytes);
      if (m_state == NULL)
        return false;

      if (SKP_Silk_SDK_InitEncoder(m_state, &m_control) != 0)
        return false;

      m_control.API_sampleRate = m_control.maxInternalSampleRate = m_definition->sampleRate;
      return true;
    }
Ejemplo n.º 7
0
static void * SILKEncoderCreate (const struct PluginCodec_Definition * codec)
{

    SKP_int ret;
    SKP_int32 encSizeBytes;

    struct SILKEncoderControl * ctxt;

    /* Create Encoder */
    ret = SKP_Silk_SDK_Get_Encoder_Size( &encSizeBytes );
    if( ret ) {
        printf( "SKP_Silk_create_encoder returned %d", ret );
    }

    ctxt = (struct SILKEncoderControl*)malloc(1*(sizeof(struct SILKEncoderControl)+encSizeBytes));
    ctxt->context = malloc( encSizeBytes );
    ctxt->mutex = new CriticalSection();

    // printf("\nbitrate in SILKEncoderCreate %d\n", codec->bitsPerSec);

    // printf( "\nSilky Encoder created");

    ret = SKP_Silk_SDK_InitEncoder(ctxt->context, &ctxt->control );

    if( ret ) {
        printf( "\nSKP_Silk_reset_encoder returned %d", ret );
    }
    else {
        ctxt->control.API_sampleRate       = codec->sampleRate;
        ctxt->control.packetSize           = codec->parm.audio.samplesPerFrame;
        ctxt->control.maxInternalSampleRate = codec->sampleRate;
        ctxt->control.packetLossPercentage = 0;
        ctxt->control.useInBandFEC         = 0;
        ctxt->control.useDTX               = 0;
        ctxt->control.complexity           = 2;
        ctxt->control.bitRate              = codec->bitsPerSec;
    }
    return ctxt;
}
Ejemplo n.º 8
0
Archivo: silk.c Proyecto: 46labs/sems
static int create_SILK_encoder(SILK_state* st, 
			       unsigned int rtp_Hz,
			       unsigned int avg_bit_rate)
{
  SKP_int32 ret,encSizeBytes;

  /* Create Encoder */
  ret = SKP_Silk_SDK_Get_Encoder_Size( &encSizeBytes );
  if( ret ) {
    ERROR( "SKP_Silk_create_encoder returned %d", ret );
    return ret;
  }

  st->psEnc = malloc( encSizeBytes );
  if(st->psEnc == NULL) {
    ERROR( "could not allocate SILK encoder state" );
    return -1;
  }
  
  /* Reset Encoder */
  ret = SKP_Silk_SDK_InitEncoder( st->psEnc, &st->encControl );
  if( ret ) {
    ERROR( "SKP_Silk_SDK_InitEncoder returned %d", ret );
    return ret;
  }
  
  /* Set Encoder parameters */
  st->encControl.API_sampleRate        = rtp_Hz;
  st->encControl.maxInternalSampleRate = rtp_Hz;
  st->encControl.packetSize            = ( 20 * rtp_Hz ) / 1000;
  st->encControl.packetLossPercentage  = 0;
  st->encControl.useInBandFEC          = 0;
  st->encControl.useDTX                = 0;
  st->encControl.complexity            = 2;
  st->encControl.bitRate               = avg_bit_rate;
  
  return 0;
}
Ejemplo n.º 9
0
/*
 * Open codec.
 */
static pj_status_t silk_codec_open(pjmedia_codec *codec,
				   pjmedia_codec_param *attr )
{

    silk_private *silk;
    silk_param *sp;
    SKP_int st_size, err;
    pj_bool_t enc_use_fec;
    unsigned enc_bitrate, i;

    PJ_ASSERT_RETURN(codec && attr, PJ_EINVAL);

    silk = (silk_private*)codec->codec_data;
    sp = &silk_factory.silk_param[silk->mode];

    /* Already opened? */
    if (silk->enc_ready || silk->dec_ready)
	return PJ_SUCCESS;

    /* Allocate and initialize encoder */
    err = SKP_Silk_SDK_Get_Encoder_Size(&st_size);
    if (err) {
        PJ_LOG(3,(THIS_FILE, "Failed to get encoder state size (err=%d)",
		  err));
	return PJMEDIA_CODEC_EFAILED;
    }
    silk->enc_st = pj_pool_zalloc(silk->pool, st_size);
    err = SKP_Silk_SDK_InitEncoder(silk->enc_st, &silk->enc_ctl);
    if (err) {
        PJ_LOG(3,(THIS_FILE, "Failed to init encoder (err=%d)", err));
	return PJMEDIA_CODEC_EFAILED;
    }

    /* Check fmtp params */
    enc_use_fec = PJ_TRUE;
    enc_bitrate = sp->bitrate;
    for (i = 0; i < attr->setting.enc_fmtp.cnt; ++i) {
	pjmedia_codec_fmtp *fmtp = &attr->setting.enc_fmtp;
	const pj_str_t STR_USEINBANDFEC = {"useinbandfec", 12};
	const pj_str_t STR_MAXAVERAGEBITRATE = {"maxaveragebitrate", 17};

	if (!pj_stricmp(&fmtp->param[i].name, &STR_USEINBANDFEC)) {
	    enc_use_fec = pj_strtoul(&fmtp->param[i].val) != 0;
	} else if (!pj_stricmp(&fmtp->param[i].name, &STR_MAXAVERAGEBITRATE)) {
	    enc_bitrate = pj_strtoul(&fmtp->param[i].val);
	    if (enc_bitrate > sp->max_bitrate) {
		enc_bitrate = sp->max_bitrate;
	    }
	}
    }

    /* Setup encoder control for encoding process */
    silk->enc_ready = PJ_TRUE;
    silk->samples_per_frame = FRAME_LENGTH_MS *
			      attr->info.clock_rate / 1000;
    silk->pcm_bytes_per_sample = attr->info.pcm_bits_per_sample / 8;

    silk->enc_ctl.API_sampleRate        = attr->info.clock_rate;
    silk->enc_ctl.maxInternalSampleRate = attr->info.clock_rate;
    silk->enc_ctl.packetSize            = attr->setting.frm_per_pkt *
                                          silk->samples_per_frame;
    /* For useInBandFEC setting to be useful, we need to set
     * packetLossPercentage greater than LBRR_LOSS_THRES (1)
     */
    silk->enc_ctl.packetLossPercentage  = SILK_ENC_CTL_PACKET_LOSS_PCT;
    silk->enc_ctl.useInBandFEC          = enc_use_fec;
    silk->enc_ctl.useDTX                = attr->setting.vad;
    silk->enc_ctl.complexity            = sp->complexity;
    silk->enc_ctl.bitRate               = enc_bitrate;
    

    /* Allocate and initialize decoder */
    err = SKP_Silk_SDK_Get_Decoder_Size(&st_size);
    if (err) {
        PJ_LOG(3,(THIS_FILE, "Failed to get decoder state size (err=%d)",
		  err));
	return PJMEDIA_CODEC_EFAILED;
    }
    silk->dec_st = pj_pool_zalloc(silk->pool, st_size);
    err = SKP_Silk_SDK_InitDecoder(silk->dec_st);
    if (err) {
        PJ_LOG(3,(THIS_FILE, "Failed to init decoder (err=%d)", err));
	return PJMEDIA_CODEC_EFAILED;
    }

    /* Setup decoder control for decoding process */
    silk->dec_ctl.API_sampleRate        = attr->info.clock_rate;
    silk->dec_ctl.framesPerPacket	= 1; /* for proper PLC at start */
    silk->dec_ready = PJ_TRUE;
    silk->dec_buf_sz = attr->info.clock_rate * attr->info.channel_cnt *
                       attr->info.frm_ptime / 1000 *
                       silk->pcm_bytes_per_sample;

    /* Inform the stream to prepare a larger buffer since we cannot parse
     * SILK packets and split it into individual frames.
     */
    attr->info.max_rx_frame_size = attr->info.max_bps * 
			           attr->info.frm_ptime / 8 / 1000;
    if ((attr->info.max_bps * attr->info.frm_ptime) % 8000 != 0)
    {
	++attr->info.max_rx_frame_size;
    }
    attr->info.max_rx_frame_size *= SILK_MAX_FRAMES_PER_PACKET;

    return PJ_SUCCESS;
}
Ejemplo n.º 10
0
static switch_status_t switch_silk_init(switch_codec_t *codec, 
										switch_codec_flag_t freeswitch_flags, 
										const switch_codec_settings_t *codec_settings)
{
	struct silk_context *context = NULL;
	switch_codec_fmtp_t codec_fmtp;
	silk_codec_settings_t silk_codec_settings;
	SKP_int32 encSizeBytes;
	SKP_int32 decSizeBytes;
	int encoding = (freeswitch_flags & SWITCH_CODEC_FLAG_ENCODE);
	int decoding = (freeswitch_flags & SWITCH_CODEC_FLAG_DECODE);

	if (!(encoding || decoding) || (!(context = switch_core_alloc(codec->memory_pool, sizeof(*context))))) {
		return SWITCH_STATUS_FALSE;
	}

	memset(&codec_fmtp, '\0', sizeof(struct switch_codec_fmtp));
	codec_fmtp.private_info = &silk_codec_settings;
	switch_silk_fmtp_parse(codec->fmtp_in, &codec_fmtp);
	
	codec->fmtp_out = switch_core_sprintf(codec->memory_pool, "useinbandfec=%s; usedtx=%s; maxaveragebitrate=%d",
										  silk_codec_settings.useinbandfec ? "1" : "0",
										  silk_codec_settings.usedtx ? "1" : "0",
										  silk_codec_settings.maxaveragebitrate ? silk_codec_settings.maxaveragebitrate : codec->implementation->bits_per_second);

	if (encoding) {
		if (SKP_Silk_SDK_Get_Encoder_Size(&encSizeBytes)) {
			return SWITCH_STATUS_FALSE;
		}
		
		context->enc_state = switch_core_alloc(codec->memory_pool, encSizeBytes);

		if (SKP_Silk_SDK_InitEncoder(context->enc_state, &context->encoder_object)) {
			return SWITCH_STATUS_FALSE;
		}
		

		context->encoder_object.API_sampleRate = codec->implementation->actual_samples_per_second;
		context->encoder_object.maxInternalSampleRate = codec->implementation->actual_samples_per_second;
		context->encoder_object.packetSize = codec->implementation->samples_per_packet;
		context->encoder_object.useInBandFEC = silk_codec_settings.useinbandfec;
		context->encoder_object.complexity = 0;
		context->encoder_object.bitRate = silk_codec_settings.maxaveragebitrate ? silk_codec_settings.maxaveragebitrate : codec->implementation->bits_per_second;
		context->encoder_object.useDTX = silk_codec_settings.usedtx;
		context->encoder_object.packetLossPercentage = silk_codec_settings.plpct;
	}

	if (decoding) {
		if (SKP_Silk_SDK_Get_Decoder_Size(&decSizeBytes)) {
			return SWITCH_STATUS_FALSE;
		}
		context->dec_state = switch_core_alloc(codec->memory_pool, decSizeBytes);

		if (SKP_Silk_SDK_InitDecoder(context->dec_state)) {
			return SWITCH_STATUS_FALSE;
		}
		context->decoder_object.API_sampleRate = codec->implementation->actual_samples_per_second;
	}

	codec->private_info = context;

	return SWITCH_STATUS_SUCCESS;
}
Ejemplo n.º 11
0
/*
 * Open codec.
 */
static pj_status_t silk_codec_open(pjmedia_codec *codec,
				   pjmedia_codec_param *attr )
{

    pj_status_t status;
    struct silk_private *silk;
    int id, ret = 0;
    unsigned i;
    struct silk_param params;
    SKP_int32 encSizeBytes, decSizeBytes, API_fs_Hz, max_internal_fs_Hz, maxBitRate;
	// useinbandfec: specifies that SILK in-band FEC is supported by the decoder and MAY be used during a session.
    // [...] If no value is specified, useinbandfec is assumed to be 1.
    SKP_int useInBandFEC = 1;
    const pj_str_t STR_FMTP_USE_INBAND_FEC = {"useinbandfec", 12};
    const pj_str_t STR_FMTP_MAX_AVERAGE_BITRATE = {"maxaveragebitrate", 17};

    silk = (struct silk_private*) codec->codec_data;
    id = silk->param_id;

    pj_assert(silk != NULL);
    pj_assert(silk->enc_ready == PJ_FALSE &&
   	      silk->dec_ready == PJ_FALSE);


    params = silk_factory.silk_param[id];

    //PJ_LOG(4, (THIS_FILE, "Open silk codec @ %d", params.clock_rate));
    /* default settings */
	API_fs_Hz = params.clock_rate;
	max_internal_fs_Hz = params.clock_rate;
	maxBitRate = ( params.bitrate > 0 ? params.bitrate : 0 );
    /* Check fmtp params */
    for (i = 0; i < attr->setting.enc_fmtp.cnt; ++i) {
		if (pj_stricmp(&attr->setting.enc_fmtp.param[i].name,
				   &STR_FMTP_USE_INBAND_FEC) == 0)	{
			useInBandFEC = (pj_uint8_t)
				  (pj_strtoul(&attr->setting.enc_fmtp.param[i].val));
			break;
		}else if(pj_stricmp(&attr->setting.enc_fmtp.param[i].name,
				   &STR_FMTP_MAX_AVERAGE_BITRATE) == 0)	{
			SKP_int32 remoteBitRate = (SKP_int32)(pj_strtoul(&attr->setting.enc_fmtp.param[i].val));
			if(remoteBitRate < maxBitRate || maxBitRate == 0){
				maxBitRate = remoteBitRate;
			}
		}
    }

    /* Create Encoder */
    ret = SKP_Silk_SDK_Get_Encoder_Size( &encSizeBytes );
    if(ret){
        PJ_LOG(1, (THIS_FILE, "Unable to get encoder size : %d", ret));
        return PJ_EINVAL;
    }
    silk->psEnc = pj_pool_zalloc(silk->pool, encSizeBytes);
    /* Reset Encoder */
    ret = SKP_Silk_SDK_InitEncoder( silk->psEnc, &silk->enc );
    if(ret){
		PJ_LOG(1, (THIS_FILE, "Unable to init encoder : %d", ret));
		return PJ_EINVAL;
	}

    /* Set Encoder parameters */
    silk->enc.API_sampleRate        = API_fs_Hz;
    silk->enc.maxInternalSampleRate = max_internal_fs_Hz;
    silk->enc.packetSize            = ( params.packet_size_ms * API_fs_Hz ) / 1000;
    // TODO : our packet loss percentage is probably not always 0...
    // Should this be configurable? Or set to some value so that FEC works? Well ... if we can get it working...
    silk->enc.packetLossPercentage  = 0;
    silk->enc.useInBandFEC          = useInBandFEC;
    silk->enc.useDTX                = 0;
    silk->enc.complexity            = params.complexity;
    silk->enc.bitRate               = maxBitRate;

    silk->enc_ready = PJ_TRUE;

    //Decoder
    /* Create decoder */
	ret = SKP_Silk_SDK_Get_Decoder_Size( &decSizeBytes );
	if(ret){
		PJ_LOG(1, (THIS_FILE, "Unable to get dencoder size : %d", ret));
		return PJ_EINVAL;
	}
	silk->psDec = pj_pool_zalloc(silk->pool, decSizeBytes);
	/* Reset decoder */
	ret = SKP_Silk_SDK_InitDecoder( silk->psDec );
	if(ret){
		PJ_LOG(1, (THIS_FILE, "Unable to init dencoder : %d", ret));
		return PJ_EINVAL;
	}
    /* Set Decoder parameters */
    silk->dec.API_sampleRate = API_fs_Hz;

    silk->dec_ready = PJ_TRUE;

    return PJ_SUCCESS;
}
Ejemplo n.º 12
0
bool MIPSILKEncoder::init(int samplingRate, MIPTime interval, int targetBitrate, int encoderSamplingRate)
{
	if (m_init)
	{
		setErrorString(MIPSILKENCODER_ERRSTR_ALREADYINIT);
		return false;
	}

	if (!(samplingRate == 8000 || samplingRate == 12000 || samplingRate == 16000 || samplingRate == 24000 ||
              samplingRate == 32000 || samplingRate == 44100 || samplingRate == 48000 ))
	{
		setErrorString(MIPSILKENCODER_ERRSTR_INVALIDINPUTSAMPLINGRATE);
		return false;
	}

	if (!(encoderSamplingRate == 8000 || encoderSamplingRate == 12000 || encoderSamplingRate == 16000 ||
	      encoderSamplingRate == 24000 ))
	{
		setErrorString(MIPSILKENCODER_ERRSTR_INVALIDENCODERSAMPLINGRATE);
		return false;
	}

	if (targetBitrate < 0)
		targetBitrate = 0;

	/*
	if (targetBitrate < 5000 || targetBitrate > 100000)
	{
		setErrorString(MIPSILKENCODER_ERRSTR_INVALIDBITRATE);
		return false;
	}
	*/

	int intervalMs = (int)(interval.getValue()*1000.0 + 0.5);

	if (!(intervalMs == 20 || intervalMs == 40 || intervalMs == 60 || intervalMs == 80 || intervalMs == 100 ))
	{
		setErrorString(MIPSILKENCODER_ERRSTR_INVALIDINTERVAL);
		return false;
	}

	int frameSize = (samplingRate*intervalMs)/1000;
	int frameSize2 = (int)((double)samplingRate * interval.getValue() + 0.5);

	if (frameSize2 != frameSize)
	{
		setErrorString(MIPSILKENCODER_ERRSTR_INVALIDINTERVAL);
		return false;
	}

	int32_t encSize = 0;
	int status = SKP_Silk_SDK_Get_Encoder_Size(&encSize);

	if (status != 0)
	{
		setErrorString(MIPSILKENCODER_ERRSTR_CANTGETENCODERSIZE);
		return false;
	}

	m_pState = new uint8_t[encSize];
	m_pEncoderControlStruct = new SKP_SILK_SDK_EncControlStruct;

	SKP_SILK_SDK_EncControlStruct *pCtrl = (SKP_SILK_SDK_EncControlStruct *)m_pEncoderControlStruct;

	status = SKP_Silk_SDK_InitEncoder(m_pState, pCtrl);
	if (status != 0)
	{
		setErrorString(MIPSILKENCODER_ERRSTR_CANTINITENCODER);
		delete [] m_pState;
		delete pCtrl;
		return false;
	}

	pCtrl->API_sampleRate = samplingRate;
	pCtrl->maxInternalSampleRate = encoderSamplingRate;
	pCtrl->packetSize = frameSize;
	pCtrl->bitRate = targetBitrate;
	pCtrl->packetLossPercentage = 0;
	pCtrl->complexity = 2;
	pCtrl->useInBandFEC = 0;
	pCtrl->useDTX = 0; // TODO: when this is 1, output size can be 0!

	m_inputSamplingRate = samplingRate;
	m_maxInternalSamplingRate = samplingRate;
	m_frameSize = frameSize;
	m_targetBitrate = targetBitrate;

	m_prevIteration = -1;
	m_msgIt = m_messages.begin();
	
	m_init = true;
	
	return true;
}
Ejemplo n.º 13
0
static int lintosilk_new(struct ast_trans_pvt *pvt)
{

  SKP_int32 ret;
  int silk_samplerate = 8000;
  int slin_samplerate = 8000;
  struct silk_coder_pvt *coder = pvt->pvt;
  char format_string[100];
  char* pointer = format_string;
  char* format;
  struct ast_format format_struct;
  struct ast_format* format_def = &format_struct;
  int attr_dtx = 0,
      attr_fec = 0,
      attr_pktloss_pct = 0,
      attr_max_bitrate = 0,
      attr_samp_rate = 0;

  /* init the silk encoder */
  coder->psEnc = malloc(encSizeBytes);
  ret = SKP_Silk_SDK_InitEncoder(coder->psEnc, &coder->encControl);
  if (ret) {
    ast_log(LOG_WARNING, "SKP_Silk_SDK_InitEncoder returned %d\n", ret);
  }

  /* Get the names of the silk codecs */
  ast_getformatname_multiple_byid(format_string, sizeof(format_string), AST_FORMAT_SILK);
  /* The destination sample rate is set explicitly */
  ret = ast_format_get_value(&pvt->explicit_dst, SILK_ATTR_KEY_SAMP_RATE, &attr_samp_rate);
  switch(attr_samp_rate){
    case SILK_ATTR_VAL_SAMP_8KHZ: silk_samplerate = 8000; break;
    case SILK_ATTR_VAL_SAMP_12KHZ: silk_samplerate = 12000; break;
    case SILK_ATTR_VAL_SAMP_16KHZ: silk_samplerate = 16000; break;
    case SILK_ATTR_VAL_SAMP_24KHZ: silk_samplerate = 24000; break;
  }
  /* get the source rate */
  switch(pvt->t->src_format.id){
    case AST_FORMAT_SLINEAR: slin_samplerate = 8000; break;
    case AST_FORMAT_SLINEAR12: slin_samplerate = 12000; break;
    case AST_FORMAT_SLINEAR16: slin_samplerate = 16000; break;
    case AST_FORMAT_SLINEAR24: slin_samplerate = 24000; break;
    default: slin_samplerate = 8000; break;
  }

  /* SILK Docs say that internal sampling rate > API Sampling rate is not allowed */
  if(slin_samplerate < silk_samplerate){
    silk_samplerate = slin_samplerate;
  }
  /* set the parameters for the coder */
  coder->encControl.API_sampleRate = (SKP_int32)slin_samplerate; /* lin input rate */
  coder->encControl.maxInternalSampleRate = (SKP_int32)silk_samplerate; /* silk output rate */
  coder->encControl.packetSize = (packetSize_ms * slin_samplerate) / 1000;
  coder->encControl.complexity = complexity;

  while ((format = strsep(&pointer, "(|)"))){
    if(strlen(format) > 0){
      if((format_def = ast_getformatbyname(format, format_def))){
        /* now pull out the format attributes */
        ret = ast_format_get_value(format_def, SILK_ATTR_KEY_DTX, &attr_dtx);
        coder->encControl.useDTX = !ret ? (SKP_int32)attr_dtx : useDTX;
        ret = ast_format_get_value(format_def, SILK_ATTR_KEY_FEC, &attr_fec);
        coder->encControl.useInBandFEC = !ret ? (SKP_int32)attr_fec : useInBandFEC;
        ret = ast_format_get_value(format_def, SILK_ATTR_KEY_PACKETLOSS_PERCENTAGE, &attr_pktloss_pct);
        coder->encControl.packetLossPercentage = !ret ? (SKP_int32)attr_pktloss_pct : packetLossPercentage;
        ret = ast_format_get_value(format_def, SILK_ATTR_KEY_MAX_BITRATE, &attr_max_bitrate);
        coder->encControl.bitRate = !ret ? (SKP_int32)attr_max_bitrate : bitRate;
        break;
      }
    }
  }

  return 0;
}
Ejemplo n.º 14
0
Archivo: mic.c Proyecto: naeems/bkvoice
void init_silk_encoder()
{    
    /* If no max internal is specified, set to minimum of API fs and 24 kHz */
    if( max_internal_fs_Hz == 0 ) {
        max_internal_fs_Hz = 8000;
        if( API_fs_Hz < max_internal_fs_Hz ) {
            max_internal_fs_Hz = API_fs_Hz;
        }
    }


    /* Print options */
    if( !quiet ) {
        printf("******************* Silk Encoder v %s ****************\n", SKP_Silk_SDK_get_version());
        printf("******************* Compiled for %d bit cpu ********* \n", (int)sizeof(void*) * 8 );
        printf( "Input:                          %s\n",     speechInFileName );
        printf( "Output:                         %s\n",     bitOutFileName );
        printf( "API sampling rate:              %d Hz\n",  API_fs_Hz );
        printf( "Maximum internal sampling rate: %d Hz\n",  max_internal_fs_Hz );
        printf( "Packet interval:                %d ms\n",  packetSize_ms );
        printf( "Inband FEC used:                %d\n",     INBandFEC_enabled );
        printf( "DTX used:                       %d\n",     DTX_enabled );
        printf( "Complexity:                     %d\n",     complexity_mode );
        printf( "Target bitrate:                 %d bps\n", targetRate_bps );
    }

    /* Create Encoder */
    ret = SKP_Silk_SDK_Get_Encoder_Size( &encSizeBytes );
    if( ret ) {
        printf( "\nSKP_Silk_create_encoder returned %d", ret );
    }

    printf("encSizeBytes: %d\n", encSizeBytes);
    psEnc = malloc(encSizeBytes);

    /* Reset Encoder */
    ret = SKP_Silk_SDK_InitEncoder( psEnc, &encControl );
    if(ret) 
    {
        printf( "\nSKP_Silk_reset_encoder returned %d", ret );
    }
    
    //printf("111111111111\n");
    /* Set Encoder parameters */
    encControl.API_sampleRate        = API_fs_Hz;
    encControl.maxInternalSampleRate = max_internal_fs_Hz;
    encControl.packetSize            = ( packetSize_ms * API_fs_Hz ) / 1000;
    encControl.packetLossPercentage  = packetLoss_perc;
    encControl.useInBandFEC          = INBandFEC_enabled;
    encControl.useDTX                = DTX_enabled;
    encControl.complexity            = complexity_mode;
    encControl.bitRate               = ( targetRate_bps > 0 ? targetRate_bps : 0 );

    if( API_fs_Hz > MAX_API_FS_KHZ * 1000 || API_fs_Hz < 0 ) {
        printf( "\nError: API sampling rate = %d out of range, valid range 8000 - 48000 \n \n", API_fs_Hz );
        exit( 0 );
    }

    //printf("22222222\n");
    totPackets           = 0;
    totActPackets        = 0;
    smplsSinceLastPacket = 0;
    sumBytes             = 0.0;
    sumActBytes          = 0.0;


}  
Ejemplo n.º 15
0
int main( int argc, char* argv[] )
{
	unsigned long int temp=0;
	clock_t start_cycles,stop_cycles;
    double    filetime;
    size_t    counter;
    SKP_int32  args, totPackets, ret, nBytes;
    double    sumBytes,avg_rate;
    SKP_int16 in[ MAX_FRAME_LENGTH_MS * MAX_API_FS_KHZ * MAX_INPUT_FRAMES ];
    char      speechInFileName[ 150 ], bitOutFileName[ 150 ];
    FILE      *bitOutFile, *speechInFile;
    SKP_int32 encSizeBytes;
    void      *psEnc;

    SKP_uint8      range_buf[ MAX_BYTES_PER_FRAME * MAX_INPUT_FRAMES ];
    ec_enc         range_enc_celt_state;

    /* default settings */
    SKP_int32 API_fs_Hz = 48000;
    SKP_int32 max_internal_fs_Hz = 16000;
    SKP_int32 min_internal_fs_Hz = 8000;
    SKP_int32 targetRate_bps = 64000;
    SKP_int32 packetSize_ms = 20;
    SKP_int32 frameSizeReadFromFile_ms = 10;
    SKP_int32 complexity_mode = 2, smplsSinceLastPacket;
    SKP_int32 quiet = 0;
    SKP_SILK_SDK_EncControlStruct encControl; // Struct for input to encoder

        
    if( argc < 3 ) {
        print_usage( argv );
        exit( 0 );
    } 
    
    /* get arguments */
    args = 1;
    strcpy( speechInFileName, argv[ args ] );
    args++;
    strcpy( bitOutFileName,   argv[ args ] );
    args++;
    while( args < argc ) {
        if( SKP_STR_CASEINSENSITIVE_COMPARE( argv[ args ], "-Fs" ) == 0 ) {
            sscanf( argv[ args + 1 ], "%d", &API_fs_Hz );
            args += 2;
        } else if( SKP_STR_CASEINSENSITIVE_COMPARE( argv[ args ], "-Fs_maxInternal" ) == 0 ) {
            sscanf( argv[ args + 1 ], "%d", &max_internal_fs_Hz );
            args += 2;
        } else if( SKP_STR_CASEINSENSITIVE_COMPARE( argv[ args ], "-plength" ) == 0 ) {
            sscanf( argv[ args + 1 ], "%d", &packetSize_ms );
            args += 2;
        } else if( SKP_STR_CASEINSENSITIVE_COMPARE( argv[ args ], "-rate" ) == 0 ) {
            sscanf( argv[ args + 1 ], "%d", &targetRate_bps );
            args += 2;
        } else if( SKP_STR_CASEINSENSITIVE_COMPARE( argv[ args ], "-complexity" ) == 0 ) {
            sscanf( argv[ args + 1 ], "%d", &complexity_mode );
            args += 2;
        }else if( SKP_STR_CASEINSENSITIVE_COMPARE( argv[ args ], "-quiet" ) == 0 ) {
            quiet = 1;
            args++;
        } else {
            printf( "Error: unrecognized setting: %s\n\n", argv[ args ] );
            print_usage( argv );
            exit( 0 );
        }
    }

    /* If no max internal set set to API fs */
    if( max_internal_fs_Hz == 0 ) {
        max_internal_fs_Hz = API_fs_Hz;
    }

    /* Print options */
    if( !quiet ) {
        printf("******************* Compiled for %d bit cpu ********* \n", (int)sizeof(void*) * 8 );
        printf( "Input:                          %s\n",     speechInFileName );
        printf( "Output:                         %s\n",     bitOutFileName );
        printf( "API sampling rate:              %d Hz\n",  API_fs_Hz );
        printf( "Maximum internal sampling rate: %d Hz\n",  max_internal_fs_Hz );
        printf( "Packet interval:                %d ms\n",  packetSize_ms );
        printf( "Complexity:                     %d\n",     complexity_mode );
        printf( "Target bitrate:                 %d bps\n", targetRate_bps );
    }

    /* Open files */
    speechInFile = fopen( speechInFileName, "rb" );
    if( speechInFile == NULL ) {
        printf( "Error: could not open input file %s\n", speechInFileName );
        exit( 0 );
    }
    bitOutFile = fopen( bitOutFileName, "wb" );
    if( bitOutFile == NULL ) {
        printf( "Error: could not open output file %s\n", bitOutFileName );
        exit( 0 );
    }

    /* Create Encoder */
    ret = SKP_Silk_SDK_Get_Encoder_Size( &encSizeBytes );
    if( ret ) {
        printf( "\nSKP_Silk_create_encoder returned %d", ret );
    }

    psEnc = malloc( encSizeBytes );

    /* Reset Encoder */
    ret = SKP_Silk_SDK_InitEncoder( psEnc, &encControl );
    if( ret ) {
        printf( "\nSKP_Silk_reset_encoder returned %d", ret );
    }
    
    /* Set Encoder parameters */
    encControl.API_sampleRate        = API_fs_Hz;
    encControl.maxInternalSampleRate = max_internal_fs_Hz;
    encControl.minInternalSampleRate = min_internal_fs_Hz;
    encControl.payloadSize_ms        = packetSize_ms;
    encControl.complexity            = complexity_mode;
    encControl.bitRate               = ( targetRate_bps > 0 ? targetRate_bps : 0 );

    if( API_fs_Hz > MAX_API_FS_KHZ * 1000 || API_fs_Hz < 0 ) {
        printf( "\nError: API sampling rate = %d out of range, valid range 8000 - 48000 \n \n", API_fs_Hz );
        exit( 0 );
    }
     /*Reset init */
    totPackets           = 0;
 //   totActPackets        = 0;
    smplsSinceLastPacket = 0;
    sumBytes             = 0.0;
   // sumActBytes          = 0.0;
    
    while( 1 ) {
        if( smplsSinceLastPacket == 0 ) {
            /* Init range coder */
            ec_enc_init( &range_enc_celt_state, range_buf, MAX_BYTES_PER_FRAME * MAX_INPUT_FRAMES );
        }

        /* Read input from file */
        counter = fread( in, sizeof( SKP_int16 ), ( frameSizeReadFromFile_ms * API_fs_Hz ) / 1000, speechInFile );
        /*check end of input file*/
        if( (SKP_int)counter < ( ( frameSizeReadFromFile_ms * API_fs_Hz ) / 1000 ) ) {
            break;
        }

        /* max payload size */
        nBytes = MAX_BYTES_PER_FRAME * MAX_INPUT_FRAMES;

        /////////////* Silk Encoder */////////////////////
        start_cycles = clock();
        ret = SKP_Silk_SDK_Encode( psEnc, &encControl, in, (SKP_int16)counter, &range_enc_celt_state, &nBytes, 0 );
        stop_cycles = clock();
        temp = temp + (stop_cycles - start_cycles);
        if( ret ) {
            printf( "\nSKP_Silk_Encode returned %d", ret );
            break;
        }
        //////////////////////////////////////////////////


        /* Get packet size */
        packetSize_ms = encControl.payloadSize_ms;

        smplsSinceLastPacket += ( SKP_int )counter;
        
        if( ( ( 1000 * smplsSinceLastPacket ) / API_fs_Hz ) == packetSize_ms ) {
            
            /* Finish up the range coder */
            ec_enc_done( &range_enc_celt_state );
            
            /* Sends a dummy zero size packet in case of DTX period  */
            /* to make it work with the decoder test program.        */
            /* In practice should be handled by RTP sequence numbers */
            totPackets++;
            sumBytes += nBytes;

            /* Write payload size */

            fwrite( &nBytes, sizeof( SKP_int32 ), 1, bitOutFile );


            /* Write payload */
            fwrite( range_buf, sizeof( SKP_uint8 ), nBytes, bitOutFile );
        

            smplsSinceLastPacket = 0;
        }
    }

    /* Write dummy because it can not end with 0 bytes */
    nBytes = -1;

    /* Write payload size */
    fwrite( &nBytes, sizeof( SKP_int32 ), 1, bitOutFile );

    /* Free Encoder */
    free( psEnc );

    fclose( speechInFile );
    fclose( bitOutFile   );

    filetime  = totPackets * 1e-3 * packetSize_ms;
    avg_rate  = 8.0 / packetSize_ms * sumBytes       / totPackets;
  //  act_rate  = 8.0 / packetSize_ms * sumActBytes    / totActPackets;
    if( !quiet ) {
    	printf( "Took %ld cycles to decode...\n", temp);
        printf( "\nFile length:                 %.3f s\n", filetime );
        printf( "\nAverage bitrate:             %.3f kbps\n", avg_rate  );
        printf( "\rPackets encoded:              %d\n", totPackets );
      //  printf( "\nActive bitrate:              %.3f kbps", act_rate  );

        printf( "\n\n" );
    }

    return 0;
}
Ejemplo n.º 16
0
int main( int argc, char* argv[] )
{
    unsigned long tottime, starttime;
    double    filetime;
    size_t    counter;
    SKP_int32 k, args, totPackets, totActPackets, ret;
    SKP_int16 nBytes;
    double    sumBytes, sumActBytes, avg_rate, act_rate, nrg;
    SKP_uint8 payload[ MAX_BYTES_PER_FRAME * MAX_INPUT_FRAMES ];
    SKP_int16 in[ FRAME_LENGTH_MS * MAX_API_FS_KHZ * MAX_INPUT_FRAMES ];
    char      speechInFileName[ 150 ], bitOutFileName[ 150 ];
    FILE      *bitOutFile, *speechInFile;
    SKP_int32 encSizeBytes;
    void      *psEnc;
#ifdef _SYSTEM_IS_BIG_ENDIAN
    SKP_int16 nBytes_LE;
#endif

    /* default settings */
    SKP_int32 API_fs_Hz = 24000;
    SKP_int32 max_internal_fs_Hz = 0;
    SKP_int32 targetRate_bps = 25000;
    SKP_int32 smplsSinceLastPacket, packetSize_ms = 20;
    SKP_int32 frameSizeReadFromFile_ms = 20;
    SKP_int32 packetLoss_perc = 0;
#if LOW_COMPLEXITY_ONLY
    SKP_int32 complexity_mode = 0;
#else
    SKP_int32 complexity_mode = 2;
#endif
    SKP_int32 DTX_enabled = 0, INBandFEC_enabled = 0, quiet = 0;
    SKP_SILK_SDK_EncControlStruct encControl; // Struct for input to encoder
    SKP_SILK_SDK_EncControlStruct encStatus;  // Struct for status of encoder

    if( argc < 3 ) {
        print_usage( argv );
        exit( 0 );
    } 
    
    /* get arguments */
    args = 1;
    strcpy( speechInFileName, argv[ args ] );
    args++;
    strcpy( bitOutFileName,   argv[ args ] );
    args++;
    while( args < argc ) {
        if( SKP_STR_CASEINSENSITIVE_COMPARE( argv[ args ], "-Fs_API" ) == 0 ) {
            sscanf( argv[ args + 1 ], "%d", &API_fs_Hz );
            args += 2;
        } else if( SKP_STR_CASEINSENSITIVE_COMPARE( argv[ args ], "-Fs_maxInternal" ) == 0 ) {
            sscanf( argv[ args + 1 ], "%d", &max_internal_fs_Hz );
            args += 2;
        } else if( SKP_STR_CASEINSENSITIVE_COMPARE( argv[ args ], "-packetlength" ) == 0 ) {
            sscanf( argv[ args + 1 ], "%d", &packetSize_ms );
            args += 2;
        } else if( SKP_STR_CASEINSENSITIVE_COMPARE( argv[ args ], "-rate" ) == 0 ) {
            sscanf( argv[ args + 1 ], "%d", &targetRate_bps );
            args += 2;
        } else if( SKP_STR_CASEINSENSITIVE_COMPARE( argv[ args ], "-loss" ) == 0 ) {
            sscanf( argv[ args + 1 ], "%d", &packetLoss_perc );
            args += 2;
        } else if( SKP_STR_CASEINSENSITIVE_COMPARE( argv[ args ], "-complexity" ) == 0 ) {
            sscanf( argv[ args + 1 ], "%d", &complexity_mode );
            args += 2;
        } else if( SKP_STR_CASEINSENSITIVE_COMPARE( argv[ args ], "-inbandFEC" ) == 0 ) {
            sscanf( argv[ args + 1 ], "%d", &INBandFEC_enabled );
            args += 2;
        } else if( SKP_STR_CASEINSENSITIVE_COMPARE( argv[ args ], "-DTX") == 0 ) {
            sscanf( argv[ args + 1 ], "%d", &DTX_enabled );
            args += 2;
        } else if( SKP_STR_CASEINSENSITIVE_COMPARE( argv[ args ], "-quiet" ) == 0 ) {
            quiet = 1;
            args++;
        } else {
            printf( "Error: unrecognized setting: %s\n\n", argv[ args ] );
            print_usage( argv );
            exit( 0 );
        }
    }

    /* If no max internal is specified, set to minimum of API fs and 24 kHz */
    if( max_internal_fs_Hz == 0 ) {
        max_internal_fs_Hz = 24000;
        if( API_fs_Hz < max_internal_fs_Hz ) {
            max_internal_fs_Hz = API_fs_Hz;
        }
    }

    /* Print options */
    if( !quiet ) {
        printf("********** Silk Encoder (Fixed Point) v %s ********************\n", SKP_Silk_SDK_get_version());
        printf("********** Compiled for %d bit cpu ******************************* \n", (int)sizeof(void*) * 8 );
        printf( "Input:                          %s\n",     speechInFileName );
        printf( "Output:                         %s\n",     bitOutFileName );
        printf( "API sampling rate:              %d Hz\n",  API_fs_Hz );
        printf( "Maximum internal sampling rate: %d Hz\n",  max_internal_fs_Hz );
        printf( "Packet interval:                %d ms\n",  packetSize_ms );
        printf( "Inband FEC used:                %d\n",     INBandFEC_enabled );
        printf( "DTX used:                       %d\n",     DTX_enabled );
        printf( "Complexity:                     %d\n",     complexity_mode );
        printf( "Target bitrate:                 %d bps\n", targetRate_bps );
    }

    /* Open files */
    speechInFile = fopen( speechInFileName, "rb" );
    if( speechInFile == NULL ) {
        printf( "Error: could not open input file %s\n", speechInFileName );
        exit( 0 );
    }
    bitOutFile = fopen( bitOutFileName, "wb" );
    if( bitOutFile == NULL ) {
        printf( "Error: could not open output file %s\n", bitOutFileName );
        exit( 0 );
    }

    /* Add Silk header to stream */
    {
        static const char Silk_header[] = "#!SILK_V3";
        fwrite( Silk_header, sizeof( char ), strlen( Silk_header ), bitOutFile );
    }

    /* Create Encoder */
    ret = SKP_Silk_SDK_Get_Encoder_Size( &encSizeBytes );
    if( ret ) {
        printf( "\nError: SKP_Silk_create_encoder returned %d\n", ret );
        exit( 0 );
    }

    psEnc = malloc( encSizeBytes );

    /* Reset Encoder */
    ret = SKP_Silk_SDK_InitEncoder( psEnc, &encStatus );
    if( ret ) {
        printf( "\nError: SKP_Silk_reset_encoder returned %d\n", ret );
        exit( 0 );
    }

    /* Set Encoder parameters */
    encControl.API_sampleRate        = API_fs_Hz;
    encControl.maxInternalSampleRate = max_internal_fs_Hz;
    encControl.packetSize            = ( packetSize_ms * API_fs_Hz ) / 1000;
    encControl.packetLossPercentage  = packetLoss_perc;
    encControl.useInBandFEC          = INBandFEC_enabled;
    encControl.useDTX                = DTX_enabled;
    encControl.complexity            = complexity_mode;
    encControl.bitRate               = ( targetRate_bps > 0 ? targetRate_bps : 0 );

    if( API_fs_Hz > MAX_API_FS_KHZ * 1000 || API_fs_Hz < 0 ) {
        printf( "\nError: API sampling rate = %d out of range, valid range 8000 - 48000 \n \n", API_fs_Hz );
        exit( 0 );
    }

    tottime              = 0;
    totPackets           = 0;
    totActPackets        = 0;
    smplsSinceLastPacket = 0;
    sumBytes             = 0.0;
    sumActBytes          = 0.0;
    smplsSinceLastPacket = 0;
    
    while( 1 ) {
        /* Read input from file */
        counter = fread( in, sizeof( SKP_int16 ), ( frameSizeReadFromFile_ms * API_fs_Hz ) / 1000, speechInFile );
#ifdef _SYSTEM_IS_BIG_ENDIAN
        swap_endian( in, counter );
#endif
        if( ( SKP_int )counter < ( ( frameSizeReadFromFile_ms * API_fs_Hz ) / 1000 ) ) {
            break;
        }

        /* max payload size */
        nBytes = MAX_BYTES_PER_FRAME * MAX_INPUT_FRAMES;

        starttime = GetHighResolutionTime();

        /* Silk Encoder */
        ret = SKP_Silk_SDK_Encode( psEnc, &encControl, in, (SKP_int16)counter, payload, &nBytes );
        if( ret ) {
            printf( "\nSKP_Silk_Encode returned %d", ret );
        }

        tottime += GetHighResolutionTime() - starttime;

        /* Get packet size */
        packetSize_ms = ( SKP_int )( ( 1000 * ( SKP_int32 )encControl.packetSize ) / encControl.API_sampleRate );

        smplsSinceLastPacket += ( SKP_int )counter;
        
        if( ( ( 1000 * smplsSinceLastPacket ) / API_fs_Hz ) == packetSize_ms ) {
            /* Sends a dummy zero size packet in case of DTX period  */
            /* to make it work with the decoder test program.        */
            /* In practice should be handled by RTP sequence numbers */
            totPackets++;
            sumBytes  += nBytes;
            nrg = 0.0;
            for( k = 0; k < ( SKP_int )counter; k++ ) {
                nrg += in[ k ] * (double)in[ k ];
            }
            if( ( nrg / ( SKP_int )counter ) > 1e3 ) {
                sumActBytes += nBytes;
                totActPackets++;
            }

            /* Write payload size */
#ifdef _SYSTEM_IS_BIG_ENDIAN
            nBytes_LE = nBytes;
            swap_endian( &nBytes_LE, 1 );
            fwrite( &nBytes_LE, sizeof( SKP_int16 ), 1, bitOutFile );
#else
            fwrite( &nBytes, sizeof( SKP_int16 ), 1, bitOutFile );
#endif

            /* Write payload */
            fwrite( payload, sizeof( SKP_uint8 ), nBytes, bitOutFile );

            smplsSinceLastPacket = 0;
        
            if( !quiet ) {
                fprintf( stderr, "\rPackets encoded:                %d", totPackets );
            }
        }
    }

    /* Write dummy because it can not end with 0 bytes */
    nBytes = -1;

    /* Write payload size */
    fwrite( &nBytes, sizeof( SKP_int16 ), 1, bitOutFile );

    /* Free Encoder */
    free( psEnc );

    fclose( speechInFile );
    fclose( bitOutFile   );

    filetime  = totPackets * 1e-3 * packetSize_ms;
    avg_rate  = 8.0 / packetSize_ms * sumBytes       / totPackets;
    act_rate  = 8.0 / packetSize_ms * sumActBytes    / totActPackets;
    if( !quiet ) {
        printf( "\nFile length:                    %.3f s", filetime );
        printf( "\nTime for encoding:              %.3f s (%.3f%% of realtime)", 1e-6 * tottime, 1e-4 * tottime / filetime );
        printf( "\nAverage bitrate:                %.3f kbps", avg_rate  );
        printf( "\nActive bitrate:                 %.3f kbps", act_rate  );
        printf( "\n\n" );
    } else {
        /* print time and % of realtime */
        printf("%.3f %.3f %d ", 1e-6 * tottime, 1e-4 * tottime / filetime, totPackets );
        /* print average and active bitrates */
        printf( "%.3f %.3f \n", avg_rate, act_rate );
    }

    return 0;
}
Ejemplo n.º 17
0
static switch_status_t switch_silk_init(switch_codec_t *codec,
                                        switch_codec_flag_t freeswitch_flags,
                                        const switch_codec_settings_t *codec_settings)
{
    struct silk_context *context = NULL;
    SKP_int useinbandfec = 0, usedtx = 0, maxaveragebitrate = 0, plpct =0;
    SKP_int32 encSizeBytes;
    SKP_int32 decSizeBytes;
    int encoding = (freeswitch_flags & SWITCH_CODEC_FLAG_ENCODE);
    int decoding = (freeswitch_flags & SWITCH_CODEC_FLAG_DECODE);

    if (!(encoding || decoding) || (!(context = switch_core_alloc(codec->memory_pool, sizeof(*context))))) {
        return SWITCH_STATUS_FALSE;
    }

    if (codec->fmtp_in) {
        int x, argc;
        char *argv[10];
        argc = switch_separate_string(codec->fmtp_in, ';', argv, (sizeof(argv) / sizeof(argv[0])));
        for (x = 0; x < argc; x++) {
            char *data = argv[x];
            char *arg;
            switch_assert(data);
            while (*data == ' ') {
                data++;
            }
            if ((arg = strchr(data, '='))) {
                *arg++ = '\0';
                if (!strcasecmp(data, "useinbandfec")) {
                    if (switch_true(arg)) {
                        useinbandfec = 1;
                        plpct = 10;// 10% for now
                    }
                }
                if (!strcasecmp(data, "usedtx")) {
                    if (switch_true(arg)) {
                        usedtx = 1;
                    }
                }
                if (!strcasecmp(data, "maxaveragebitrate")) {
                    maxaveragebitrate = atoi(arg);
                    switch(codec->implementation->actual_samples_per_second) {
                    case 8000:
                    {
                        if(maxaveragebitrate < 6000 || maxaveragebitrate > 20000) {
                            maxaveragebitrate = 20000;
                        }
                        break;
                    }
                    case 12000:
                    {
                        if(maxaveragebitrate < 7000 || maxaveragebitrate > 25000) {
                            maxaveragebitrate = 25000;
                        }
                        break;
                    }
                    case 16000:
                    {
                        if(maxaveragebitrate < 8000 || maxaveragebitrate > 30000) {
                            maxaveragebitrate = 30000;
                        }
                        break;
                    }
                    case 24000:
                    {
                        if(maxaveragebitrate < 12000 || maxaveragebitrate > 40000) {
                            maxaveragebitrate = 40000;
                        }
                        break;
                    }

                    default:
                        /* this should never happen but 20000 is common among all rates */
                        maxaveragebitrate = 20000;
                        break;
                    }

                }
            }
        }
    }

    codec->fmtp_out = switch_core_sprintf(codec->memory_pool, "useinbandfec=%s; usedtx=%s; maxaveragebitrate=%d",
                                          useinbandfec ? "true" : "false",
                                          usedtx ? "true" : "false",
                                          maxaveragebitrate ? maxaveragebitrate : codec->implementation->bits_per_second);

    if (encoding) {
        if (SKP_Silk_SDK_Get_Encoder_Size(&encSizeBytes)) {
            return SWITCH_STATUS_FALSE;
        }

        context->enc_state = switch_core_alloc(codec->memory_pool, encSizeBytes);

        if (SKP_Silk_SDK_InitEncoder(context->enc_state, &context->encoder_object)) {
            return SWITCH_STATUS_FALSE;
        }

        context->encoder_object.sampleRate = codec->implementation->actual_samples_per_second;
        context->encoder_object.packetSize = codec->implementation->samples_per_packet;
        context->encoder_object.useInBandFEC = useinbandfec;
        context->encoder_object.complexity = 2;
        context->encoder_object.bitRate = maxaveragebitrate ? maxaveragebitrate : codec->implementation->bits_per_second;
        context->encoder_object.useDTX = usedtx;
        context->encoder_object.packetLossPercentage = plpct;;
    }

    if (decoding) {
        if (SKP_Silk_SDK_Get_Decoder_Size(&decSizeBytes)) {
            return SWITCH_STATUS_FALSE;
        }
        context->dec_state = switch_core_alloc(codec->memory_pool, decSizeBytes);

        if (SKP_Silk_SDK_InitDecoder(context->dec_state)) {
            return SWITCH_STATUS_FALSE;
        }
        context->decoder_object.sampleRate = codec->implementation->actual_samples_per_second;
    }

    codec->private_info = context;

    return SWITCH_STATUS_SUCCESS;
}