Exemplo n.º 1
0
/* wrapper to hide signal interface differrencies */
int joe_set_signal(int signum, sighandler_t handler)
{
	int retval;
#ifdef HAVE_SIGACTION
	struct sigaction sact;

	mset(&sact, 0, sizeof(sact));
	sact.sa_handler = handler;
#ifdef SA_INTERRUPT
	sact.sa_flags = SA_INTERRUPT;
#endif
	retval = sigaction(signum, &sact, NULL);
#elif defined(HAVE_SIGVEC)
	struct sigvec svec;

	mset(&svec, 0, sizeof(svec));
	svec.sv_handler = handler;
#ifdef HAVE_SV_INTERRUPT
	svec.sv_flags = SV_INTERRUPT;
#endif
	retval = sigvec(signum, &svec, NULL);
#else
	retval = (signal(signum, handler) != SIG_ERR) ? 0 : -1;
#ifdef HAVE_SIGINTERRUPT
	siginterrupt(signum, 1);
#endif
#endif
	return(retval);
}
Exemplo n.º 2
0
int DPMHC_K(struct str_DPMHC *ptr_DPMHC_data)
{
    int i_K = ptr_DPMHC_data->i_K;
    gsl_vector *v_u = ptr_DPMHC_data->v_u;
    gsl_vector *v_v = ptr_DPMHC_data->v_v;
    gsl_vector *v_w  = ptr_DPMHC_data->v_w;
    gsl_matrix *m_DPtheta = ptr_DPMHC_data->m_DPtheta;
    double d_DPalpha = ptr_DPMHC_data->d_DPalpha;

    int K_tmp, K_new,j;
    double a,v_j,w_j,csum,min_u;
    //gsl_vector_view theta_j;

  //int k_asset_number = P -> size1; /* number of assets in model */

    K_tmp = i_K;
    min_u = gsl_vector_min ( v_u );
    a = 1.0 - min_u;

    if( a == 1.0 )
        printf("**********min_u = %g *************\n",min_u);

    csum = 0.0;
    j=0;

    while ( csum <= a ){

        /* check if new v_j,w_j and theta_j should be generated */
        if( j >= K_tmp ){

            v_j = gsl_ran_beta ( rng , 1.0, d_DPalpha );
            vset( v_v, j, v_j);

            w_j = v_j * (vget( v_w, j-1 )/vget(v_v,j-1))*(1.0-vget(v_v,j-1));
            vset( v_w, j, w_j);

        /* generate new mu, xi, tau from prior G_0 */
            mset(m_DPtheta, j, 0,
                ptr_DPMHC_data->d_m0 + gsl_ran_gaussian_ziggurat(rng, sqrt(ptr_DPMHC_data->d_s2m)));

            mset(m_DPtheta, j, 1,
                gsl_ran_gaussian_ziggurat(rng, ptr_DPMHC_data->d_A));

            mset(m_DPtheta, j, 2,
                gsl_ran_gamma(rng, 0.5, 0.5) );
        }

        csum += vget(v_w,j);
        K_new = j + 1;
        j++;
    }

    ptr_DPMHC_data->i_K = K_new;

    return 0;
}
Exemplo n.º 3
0
Arquivo: MPolUnit.c Projeto: 8l/csolve
void mpolunit(MPOL *p, MINT *coef, MPOL *q)
{ 
  register i;
  MINT *resco,rem;
  MPOL res;


  if (p->nterms==0) {
	mpolfree(q);
	mset(0,coef);
	return;
  };
  
  MINIT(&rem);
  MFREE(coef);
  MCOPY(&(p->coefs[0]),coef);
  for (i=1;i<p->nterms;i++)
	mgcd(coef,&(p->coefs[i]),coef);

  MPOLINIT(&res);

  res.nterms = p->nterms;
  POL_ALLOC(&res,p->nterms); 
  resco = res.coefs;
  for (i=0;i<p->nterms;i++){
	MINIT(resco);
	mdiv(&(p->coefs[i]),coef,(resco++),&rem);
	expocopy(MEXPO(p,i),MEXPO(&res,i));
  }
  mpolfree(q);
  MPOLMOVEFREE(&res,q);
  MFREE(&rem);
}
void update_phi(int doc_number, int time,
		lda_post* p, lda_seq* var,
		gsl_matrix* g) {
    int i, k, n, K = p->model->ntopics, N = p->doc->nterms;
    double dig[p->model->ntopics];

    for (k = 0; k < K; k++) {
      dig[k] = gsl_sf_psi(vget(p->gamma, k));
    }

    for (n = 0; n < N; n++) {
      // compute log phi up to a constant

      int w = p->doc->word[n];
      for (k = 0; k < K; k++) {
	mset(p->log_phi, n, k,
	     dig[k] + mget(p->model->topics, w, k));
      }

      // normalize in log space

      gsl_vector log_phi_row = gsl_matrix_row(p->log_phi, n).vector;
      gsl_vector phi_row = gsl_matrix_row(p->phi, n).vector;
      log_normalize(&log_phi_row);
      for (i = 0; i < K; i++) {
	vset(&phi_row, i, exp(vget(&log_phi_row, i)));
      }
    }
}
Exemplo n.º 5
0
Arquivo: Mstrtoul.c Projeto: 8l/csolve
mstrtoul(MINT *a, char *s, char **p, short int b)
{
	MINT	y, base;
	int	c, dectop, alphatop;
	short	qy;
	int	i;

	mset(0,a);
	MSET(b,&base);
	y.len	= 1;
	y.val	= &qy;
	dectop = (b <= 10) ? '0' + b - 1 : '9';
	if (b > 10) alphatop = 'a' + b - 10;

	i=0;
	while (isxdigit(c=s[i++])) {
		if (isupper(c)) c = c - 'A' + 'a';
		if (c >= '0' && c <= dectop) {
			qy = c - '0';
			mmult(a,&base,a);
			if (qy != 0) madd(a,&y,a);
			continue;
		} if (b > 10 && (c >= 'a' && c <= alphatop)) {
			qy = c - 'a' + 10;
			mmult(a,&base,a);
			madd(a,&y,a);
			continue;
		}
	};
	if (p!=NULL) (*p)=(char *)s+i-1;
}
Exemplo n.º 6
0
           int main(int argc,char** argv){
		    printf("%s",TITLE);
            get_arguments(argc,argv);
            struct sockaddr_in s;
            use.sizes=sizeof(s);     
            s.sin_family=AF_INET;
            s.sin_addr.s_addr=inet_addr(use.host);
            s.sin_port=htons(use.port);
               printf("[*]connection established\n");
			   printf("[*]Sending packets!\n");
		         for(;;){  
			             use.x++;
                         use.sockets = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
					     if (use.sockets < 0){
					     printf("line 81"); 
                         error_handle();
                        }			           
					    if (strcmp(use.option, "get") == 0){		
						   copy_str(use.sendbytes, GET1, 5);
						   mset(use.sendbytes+5,0x41,999999);
						   copy_str(use.sendbytes+5+999999, GET2, 17);
                        }else{
							  if(strcmp(use.option,"flood")==0){
							    mset(use.sendbytes+5,0x41,999999);
							  }
						}
                       if(connect(use.sockets,(struct sockaddr*)&s,use.sizes)<0){
					     printf("Nr of connections:%d\nline 89:",use.x);
			             error_handle();
					   }else{
							 printf(".");
					    }	 
			          
                       if(send(use.sockets,use.sendbytes,sizeof(use.sendbytes),0)<0){
					     printf("Nr of sends:\nline 96:",use.x);
                         error_handle();
                         shutdown(use.sockets,1);
                       }else{
							 memset(use.recvbytes,0,BUFFSZ);
							 recv(use.sockets,use.recvbytes,BUFFSZ,0);
					    }
                     
			    }
          		 printf("[*]Done!\n");
       return 0;
      }
Exemplo n.º 7
0
void maximization(llna_model* model, llna_ss* ss)
{
    int i, j;
    double sum;

    // mean maximization

    for (i = 0; i < model->k-1; i++)
        vset(model->mu, i, vget(ss->mu_ss, i) / ss->ndata);

    // covariance maximization

    for (i = 0; i < model->k-1; i++)
    {
        for (j = 0; j < model->k-1; j++)
        {
            mset(model->cov, i, j,
                 (1.0 / ss->ndata) *
                 (mget(ss->cov_ss, i, j) +
                  ss->ndata * vget(model->mu, i) * vget(model->mu, j) -
                  vget(ss->mu_ss, i) * vget(model->mu, j) -
                  vget(ss->mu_ss, j) * vget(model->mu, i)));
        }
    }
    if (PARAMS.cov_estimate == SHRINK)
    {
        cov_shrinkage(model->cov, ss->ndata, model->cov);
    }
    matrix_inverse(model->cov, model->inv_cov);
    model->log_det_inv_cov = log_det(model->inv_cov);

    // topic maximization

    for (i = 0; i < model->k; i++)
    {
        sum = 0;
        for (j = 0; j < model->log_beta->size2; j++)
            sum += mget(ss->beta_ss, i, j);

        if (sum == 0) sum = safe_log(sum) * model->log_beta->size2;
        else sum = safe_log(sum);

        for (j = 0; j < model->log_beta->size2; j++)
            mset(model->log_beta, i, j, safe_log(mget(ss->beta_ss, i, j)) - sum);
    }
}
Exemplo n.º 8
0
int DPMHC_mu_smplr(struct str_DPMHC *ptr_DPMHC_data)
{
    int i,j;
    int i_n = ptr_DPMHC_data->v_y->size;
    int i_K = ptr_DPMHC_data->i_K;
    int i_nj;
    double d_muj,d_s2j,d_yhatj;

    double d_xij,d_tauj;

    double d_m0 = ptr_DPMHC_data->d_m0;
    double d_s2m = ptr_DPMHC_data->d_s2m;

   gsl_vector *v_y = ptr_DPMHC_data->v_y;
   gsl_vector_int *vi_S = ptr_DPMHC_data->vi_S;
   gsl_vector_int *vi_n = ptr_DPMHC_data->vi_n;
   gsl_matrix *m_theta = ptr_DPMHC_data->m_DPtheta;


 //  printf("\ni_K = %d\n",i_K);

   for(j=0;j<i_K;j++){

        d_yhatj = 0.;
        i_nj = 0;
        for(i=0;i<i_n;i++){
            if( vget_int(vi_S,i) == j ){
                d_yhatj += vget(v_y,i);
                i_nj++;
            }
        }
        if (vget_int(vi_n,j) != i_nj){
            fprintf(stderr,"Error in  DPMN_theta_polya_smplr(): vi_n[%d] does not equal i_nj\n", j);
            exit(1);
        }
        d_xij = mget(m_theta,j,1);
        d_tauj = mget(m_theta,j,2);
        d_yhatj /= (d_xij * d_xij / d_tauj);

        d_s2j = 1./( 1./d_s2m + i_nj/ (d_xij * d_xij / d_tauj) );
        d_muj = d_s2j * ( d_m0/d_s2m + d_yhatj );


        d_muj = d_muj + gsl_ran_gaussian_ziggurat(rng, sqrt(d_s2j));

        mset(m_theta,j,0, d_muj);


       // printf("%d: eta = %g lambda^2 = %g\n",j, mget(m_theta,j,0), mget(m_theta,j,1) );
     }





    return 0;
}
Exemplo n.º 9
0
bool initNvEnc()
{
    if (pNvEnc != 0)
        return true;

    if (!checkNvEnc())
        return false;

    nvEncLib = LoadLibrary(encodeLibName);

    if(nvEncLib == 0)
    {
        NvLog(TEXT("Failed to load %s"), encodeLibName);
        goto error;
    }

    PNVENCODEAPICREATEINSTANCE nvEncodeAPICreateInstance =
        (PNVENCODEAPICREATEINSTANCE)GetProcAddress(nvEncLib, "NvEncodeAPICreateInstance");

    if(nvEncodeAPICreateInstance == 0)
    {
        NvLog(TEXT("Failed to load nvenc entrypoint"));
        goto error;
    }

    pNvEnc = new NV_ENCODE_API_FUNCTION_LIST;
    assert(pNvEnc);

    mset(pNvEnc, 0, sizeof(NV_ENCODE_API_FUNCTION_LIST));
    pNvEnc->version = NV_ENCODE_API_FUNCTION_LIST_VER;
    NVENCSTATUS status = nvEncodeAPICreateInstance(pNvEnc);

    if (status != NV_ENC_SUCCESS)
    {
        NvLog(TEXT("Failed to get nvenc instance"));
        goto error;
    }

    NvLog(TEXT("NVENC internal init finished successfully"));

    return true;

error:

    iNvencDeviceCount = 0;

    delete pNvEnc;
    pNvEnc = 0;

    FreeLibrary(nvEncLib);
    nvEncLib = 0;

    NvLog(TEXT("NVENC internal init failed"));

    return false;
}
Exemplo n.º 10
0
int main(){
	while(scanf("%s",str) == 1){
		if(str[0] == '0')
		  break;
		len = strlen(str);
		mset(dp, 0);
		printf(FS"\n", solve(0));
	}
	return 0;
}
Exemplo n.º 11
0
int DPMHC_init(struct str_DPMHC *ptr_DPMHC_data, int i_draws){

    int j;
    int i_T = (ptr_DPMHC_data->vi_S)->size;
    if (i_T == 0){
        fprintf(stderr,"Error in DPMHC_init(): DPMHC_alloc() has not been called.\n");
        exit(1);
    }

    int i_K;
    gsl_matrix *m_DPtheta = ptr_DPMHC_data->m_DPtheta;

    ptr_DPMHC_data->m_DPmcmc = gsl_matrix_alloc(i_draws, 2); // for draw of i_K and d_DPalpha

    // initialize slice truction to K = 4 and one alive cluster, i_m = 1
    i_K = ptr_DPMHC_data->i_K = 4;
    ptr_DPMHC_data->i_m = 1;
    gsl_vector_int_set_all(ptr_DPMHC_data->vi_S,0);
    vset_int(ptr_DPMHC_data->vi_n,0,i_T);

    // draw DP precision parameter d_DPalpha ~ Gamma(a,b)
    double d_DPalpha;
    d_DPalpha = ran_gamma(rng, ptr_DPMHC_data->d_a, ptr_DPMHC_data->d_b);
    ptr_DPMHC_data->d_DPalpha = d_DPalpha;

    // Draw initial mixture locations for K clusters
    for(j = 0; j < i_K; j++){

        mset(m_DPtheta, j, 0,
                ptr_DPMHC_data->d_m0 + gsl_ran_gaussian_ziggurat(rng, sqrt(ptr_DPMHC_data->d_s2m)));

        mset(m_DPtheta, j, 1,
                gsl_ran_gaussian_ziggurat(rng, ptr_DPMHC_data->d_A));

        mset(m_DPtheta, j, 2,
                gsl_ran_gamma(rng, 0.5, 0.5) );

    }

    return 0;
}
Exemplo n.º 12
0
int DPMHC_tau_smplr(struct str_DPMHC *ptr_DPMHC_data)
{
    int i,j;
    int i_n = ptr_DPMHC_data->v_y->size;
    int i_K = ptr_DPMHC_data->i_K;
    int i_nj;
    double d_muj,d_yi;
    double d_yhat;

    double d_xij,d_tauj;



    gsl_vector *v_y = ptr_DPMHC_data->v_y;
    gsl_vector_int *vi_S = ptr_DPMHC_data->vi_S;
    gsl_vector_int *vi_n = ptr_DPMHC_data->vi_n;
    gsl_matrix *m_theta = ptr_DPMHC_data->m_DPtheta;


 //  printf("\ni_K = %d\n",i_K);
    for(j=0;j<i_K;j++){

        d_muj = mget(m_theta,j, 0);
        d_xij = mget(m_theta,j, 1);

        d_yhat = 0.;
        i_nj = 0;
        for(i=0;i<i_n;i++){
            if( vget_int(vi_S,i) == j ){
                d_yi = vget(v_y,i);
                d_yhat += (d_yi/fabs(d_xij) - d_muj/fabs(d_xij)) * (d_yi/fabs(d_xij) - d_muj/fabs(d_xij));
                i_nj++;
            }
        }
        if (vget_int(vi_n,j) != i_nj){
            fprintf(stderr,"Error in  DPMN_tau_smplr(): vi_n[%d] does not equal i_nj\n", j);
            exit(1);
        }

        d_tauj = gsl_ran_gamma(rng, 0.5 + (double)i_nj/2.0, 0.5 + d_yhat/2.0);

        mset(m_theta,j, 2, d_tauj);


       // printf("%d: eta = %g lambda^2 = %g\n",j, mget(m_theta,j,0), mget(m_theta,j,1) );
     }





    return 0;
}
Exemplo n.º 13
0
void init_lda_post(lda_post* p) {
    int k, n, K = p->model->ntopics, N = p->doc->nterms;

    for (k = 0; k < K; k++)
    {
        vset(p->gamma, k,
             vget(p->model->alpha,k) + ((double) p->doc->total)/K);
        for (n = 0; n < N; n++)
            mset(p->phi, n, k, 1.0/K);
    }
    p->doc_weight = NULL;
}
Exemplo n.º 14
0
Arquivo: Msqrt.c Projeto: 8l/csolve
msqrt(MINT *a, MINT *b, MINT *r)
{	MINT x,y,z;
	register alen,j;

	MINIT(&x); MINIT(&y); MINIT(&z);
	alen = a->len;

	if (alen<0) mpfatal("msqrt: neg arg");
	if (alen==0) {
		mset(0,b);
		mset(0,r);
		return(0);
	}

	if(alen & 01) x.len = (1+alen)/2;
	else x.len = 1 + alen/2;
	valloc(x.val,x.len);
	for (j=x.len; (--j)>=0;) x.val[j]=0;
	if (alen & 01) x.val[x.len-1]=0400;
	else x.val[x.len-1]=1;

	for (;;) {
		mdiv(a,&x,&y,&z);
		madd(&x,&y,&y);
		mshiftr(&y,1);
		if (mcmp(&x,&y) <= 0) break;
		mmove(&y,&x);
	}
	mcopy(&x,&y);
	mmult(&x,&x,&x);
	msub(a,&x,r);
	MFREE(&x);
	MMOVEFREE(&y,b);
	MFREE(&z);
	return(r->len);
}
Exemplo n.º 15
0
int main(int argc, char * argv[])
{
    int i,j;
    // Allocate memory
    char *m=(char *)malloc(SIZE);
    if (m==NULL) {	// Check for errors
        perror("malloc");
        return errno;
    }
    // Set memory
    mset(m,0,SIZE);
    // Free
    free(m);

    return 0;
}
Exemplo n.º 16
0
Arquivo: Mmult.c Projeto: 8l/csolve
void mmult(MINT *a, MINT *b, MINT *c)
{
    register  carry,i,j,x;
    register short *aval, *bval;
    short *cval;
    int alen, blen, clen, sign;
#ifdef DEBUG
    if (1) {printf("\n"); mout(a); printf(" * ");mout(b);printf(" = ");}
#endif

    alen = a->len;
    blen = b->len;
    if (alen == 0 || blen == 0) {
	mset(0,c);
	return;
    }

    sign = 1;
    if (alen < 0) { alen = -alen; sign = -1; }
    if (blen < 0) { blen = -blen; sign = -sign; }

    if (alen < blen) {
	i = alen;  alen = blen;  blen = i;
	bval = a->val; aval = b->val;
    }
    else { aval = a->val; bval = b->val; }

    clen = alen+blen;
    valloc(cval, clen);

    if (blen == 1) {
	/*  We eliminate a lot of loop overhead on this common case. */
	x = 0;
	j = bval[0];
	bval = cval;
	for (i=0; i<alen; i++) {
	    x += j * aval[i];
	    bval[i] = x & 077777;
	    x >>= 15;
#if (! INTR)
	    (*PollPtr)();
#endif
	}
	bval[i] = x;
	if (x == 0) clen = i;    /* clen = alen+blen-1 == alen */
    }
Exemplo n.º 17
0
void c_ctr::init_model(int ctr_run) {

  m_U = gsl_matrix_calloc(m_num_users, m_num_factors);
  m_V = gsl_matrix_calloc(m_num_items, m_num_factors);

  if (ctr_run) {
    gsl_matrix_memcpy(m_V, m_theta);
  }
  else {
    // this is for convenience, so that updates are similar.
    m_theta = gsl_matrix_calloc(m_num_items, m_num_factors);

    for (size_t i = 0; i < m_V->size1; i ++) 
      for (size_t j = 0; j < m_V->size2; j ++) 
        mset(m_V, i, j, runiform());
  }
}
Exemplo n.º 18
0
double c_ctr::doc_inference(const c_document* doc, const gsl_vector* theta_v, 
                            const gsl_matrix* log_beta, gsl_matrix* phi,
                            gsl_vector* gamma, gsl_matrix* word_ss, 
                            bool update_word_ss) {

  double pseudo_count = 1.0;
  double likelihood = 0;
  gsl_vector* log_theta_v = gsl_vector_alloc(theta_v->size);
  gsl_vector_memcpy(log_theta_v, theta_v);
  vct_log(log_theta_v);

  int n, k, w;
  double x;
  for (n = 0; n < doc->m_length; n ++) {
    w = doc->m_words[n]; 
    for (k = 0; k < m_num_factors; k ++)
      mset(phi, n, k, vget(theta_v, k) * mget(m_beta, k, w));

    gsl_vector_view row =  gsl_matrix_row(phi, n);
    vnormalize(&row.vector);

    for (k = 0; k < m_num_factors; k ++) {
      x = mget(phi, n, k);
      if (x > 0) 
        likelihood += x*(vget(log_theta_v, k) + mget(log_beta, k, w) - log(x));
    }
  }

  if (pseudo_count > 0) {
    likelihood += pseudo_count * vsum(log_theta_v);
  }

  gsl_vector_set_all(gamma, pseudo_count); // smoothing with small pseudo counts
  for (n = 0; n < doc->m_length; n ++) {
    for (k = 0; k < m_num_factors; k ++) {
      x = doc->m_counts[n] * mget(phi, n, k);
      vinc(gamma, k, x);      
      if (update_word_ss) minc(word_ss, k, doc->m_words[n], x);
    }
  }

  gsl_vector_free(log_theta_v);
  return likelihood;
}
Exemplo n.º 19
0
////////////////////////////////////////////////////////////////////////////////
// Main
////////////////////////////////////////////////////////////////////////////////
int main(int argc, char* argv[])
{
	uint64_t start = getSystemTime();
	if(start == -1)
		return errno;

	char *m = (char *)malloc(SIZE);
	if (m==NULL) {
		perror("malloc");
		return errno; 
	}
	
	mset(m, 0x8, SIZE);
	//check(m, 0x8, SIZE); //uncomment this to check the output. (adds time)

	free(m);
	uint64_t fini = getSystemTime();
	if(fini == -1)
		return errno;
	printf("Time: %lld\n",(fini-start));
	return 0;
}
Exemplo n.º 20
0
//短信唤醒并发送注册命令
void SmsWakeup(void)
{
    static BYTE i,loc;

    i = 0;
    while(i<SmsLength)
    {
        if (SmsContent[i] == ',')
        {
            break;
        }
        i++;
    }
    if (i>=SmsLength)
    {
        goto Fail;
    }

    mset(IpAddrStr,0,16);
    mset(PortStr,0,6);
    
    mcpy(IpAddrStr,&SmsContent[3],i-3);             // Server Ip Address
    if (!CheckValidIpAddr())
    {
        goto Fail;
    }

    if (!StrToIpAdd((BYTE*)&SysParam[SP_SERVERIP]))
    {
        goto Fail;
    }

    loc = i;

    mcpy(PortStr,&SmsContent[loc+1],SmsLength-loc-1);  // Server Port
    if (!CheckValidPort())
    {
        goto Fail;
    }

    if (!StrToPort((BYTE*)&SysParam[SP_SERVERPORT]))
    {
        goto Fail;
    }
    
    SaveSysParam();
            
    
    NeedConnSrv = 1;
    return;
    

Fail:
    NeedConnSrv = 0;
    mcpy(&SmsContent[SmsLength],"(Fail)\r\n",8);
    SmsLength += 8;
    if (SysParam[SP_MODTYPE] == GSM_MG323)
    {
        Send_Pdu_SMS();
    }
    else if (SysParam[SP_MODTYPE] == CDMA_MC323)
    {
        Send_Txt_SMS(SmsNumber, SmsContent);
    }
}
Exemplo n.º 21
0
void NVENCEncoder::init()
{
    NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS stEncodeSessionParams = { 0 };
    NV_ENC_PRESET_CONFIG presetConfig = { 0 };
    GUID clientKey = NV_CLIENT_KEY;
    CUcontext cuContextCurr;
    NVENCSTATUS nvStatus = NV_ENC_SUCCESS;
    int surfaceCount = 0;

    GUID encoderPreset = NV_ENC_PRESET_HQ_GUID;

    int useCustomPreset = AppConfig->GetInt(TEXT("Video Encoding"), TEXT("UseCustomSettings"));
    if (useCustomPreset)
    {
        String presetString = AppConfig->GetString(TEXT("Video Encoding"), TEXT("CustomSettings"), TEXT("default")).MakeLower();

        if (presetString == TEXT("hp"))
            encoderPreset = NV_ENC_PRESET_HP_GUID;
        else if (presetString == TEXT("hq"))
            encoderPreset = NV_ENC_PRESET_HQ_GUID;
        else if (presetString == TEXT("bd"))
            encoderPreset = NV_ENC_PRESET_BD_GUID;
        else if (presetString == TEXT("ll"))
            encoderPreset = NV_ENC_PRESET_LOW_LATENCY_DEFAULT_GUID;
        else if (presetString == TEXT("llhp"))
            encoderPreset = NV_ENC_PRESET_LOW_LATENCY_HP_GUID;
        else if (presetString == TEXT("llhq"))
            encoderPreset = NV_ENC_PRESET_LOW_LATENCY_HQ_GUID;
        else
            encoderPreset = NV_ENC_PRESET_DEFAULT_GUID;
    }

    TCHAR envClientKey[128] = { 0 };
    DWORD envRes = GetEnvironmentVariable(TEXT("NVENC_KEY"), envClientKey, 128);
    if (envRes > 0 && envRes <= 128)
    {
        if (CLSIDFromString(envClientKey, &clientKey) == NOERROR)
            NvLog(TEXT("Got NVENC key from environment"));
        else
            NvLog(TEXT("NVENC_KEY environment variable has invalid format"));
    }

    mset(&initEncodeParams, 0, sizeof(NV_ENC_INITIALIZE_PARAMS));
    mset(&encodeConfig, 0, sizeof(NV_ENC_CONFIG));

    encodeConfig.version = NV_ENC_CONFIG_VER;
    presetConfig.version = NV_ENC_PRESET_CONFIG_VER;
    initEncodeParams.version = NV_ENC_INITIALIZE_PARAMS_VER;

    stEncodeSessionParams.version = NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS_VER;
    stEncodeSessionParams.apiVersion = NVENCAPI_VERSION;
    stEncodeSessionParams.clientKeyPtr = &clientKey;

    cuContext = 0;
    checkCudaErrors(cuCtxCreate(&cuContext, 0, pNvencDevices[iNvencUseDeviceID]));
    checkCudaErrors(cuCtxPopCurrent(&cuContextCurr));

    stEncodeSessionParams.device = (void*)cuContext;
    stEncodeSessionParams.deviceType = NV_ENC_DEVICE_TYPE_CUDA;

    nvStatus = pNvEnc->nvEncOpenEncodeSessionEx(&stEncodeSessionParams, &encoder);
    if (nvStatus != NV_ENC_SUCCESS)
    {
        encoder = 0;
        NvLog(TEXT("nvEncOpenEncodeSessionEx failed - invalid license key?"));
        goto error;
    }

    if (!populateEncodePresetGUIDs())
        goto error;

    if (!checkPresetSupport(encoderPreset))
    {
        NvLog(TEXT("Preset is not supported!"));
        goto error;
    }

    nvStatus = pNvEnc->nvEncGetEncodePresetConfig(encoder, NV_ENC_CODEC_H264_GUID, encoderPreset, &presetConfig);
    if (nvStatus != NV_ENC_SUCCESS)
    {
        NvLog(TEXT("nvEncGetEncodePresetConfig failed"));
        goto error;
    }

    initEncodeParams.encodeGUID = NV_ENC_CODEC_H264_GUID;
    initEncodeParams.encodeHeight = height;
    initEncodeParams.encodeWidth = width;
    initEncodeParams.darHeight = height;
    initEncodeParams.darWidth = width;
    initEncodeParams.frameRateNum = fps;
    initEncodeParams.frameRateDen = 1;

    initEncodeParams.enableEncodeAsync = 0;
    initEncodeParams.enablePTD = 1;

    initEncodeParams.presetGUID = encoderPreset;
    initEncodeParams.encodeConfig = &encodeConfig;
    memcpy(&encodeConfig, &presetConfig.presetCfg, sizeof(NV_ENC_CONFIG));

    if (keyint != 0)
        encodeConfig.gopLength = keyint * fps;

    if (maxBitRate != -1)
    {
        encodeConfig.rcParams.averageBitRate = maxBitRate * 1000;
        encodeConfig.rcParams.maxBitRate = maxBitRate * 1000;
    }

    if (bufferSize != -1)
        encodeConfig.rcParams.vbvBufferSize = bufferSize * 1000;

    if (bUseCBR)
        encodeConfig.rcParams.rateControlMode = NV_ENC_PARAMS_RC_CBR;

    encodeConfig.encodeCodecConfig.h264Config.enableVFR = bUseCFR ? 0 : 1;

    encodeConfig.frameFieldMode = NV_ENC_PARAMS_FRAME_FIELD_MODE_FRAME;

    encodeConfig.encodeCodecConfig.h264Config.bdirectMode = encodeConfig.frameIntervalP > 1 ? NV_ENC_H264_BDIRECT_MODE_TEMPORAL : NV_ENC_H264_BDIRECT_MODE_DISABLE;

    encodeConfig.encodeCodecConfig.h264Config.idrPeriod = encodeConfig.gopLength;
    encodeConfig.encodeCodecConfig.h264Config.h264VUIParameters.colourMatrix = colorDesc.matrix;
    encodeConfig.encodeCodecConfig.h264Config.h264VUIParameters.videoFullRangeFlag = colorDesc.fullRange;
    encodeConfig.encodeCodecConfig.h264Config.h264VUIParameters.colourPrimaries = colorDesc.primaries;
    encodeConfig.encodeCodecConfig.h264Config.h264VUIParameters.transferCharacteristics = colorDesc.transfer;

    nvStatus = pNvEnc->nvEncInitializeEncoder(encoder, &initEncodeParams);

    if (nvStatus != NV_ENC_SUCCESS)
    {
        NvLog(TEXT("nvEncInitializeEncoder failed"));
        goto error;
    }

    for (surfaceCount = 0; surfaceCount < maxSurfaceCount; ++surfaceCount)
    {
        NV_ENC_CREATE_INPUT_BUFFER allocSurf = { 0 };
        allocSurf.version = NV_ENC_CREATE_INPUT_BUFFER_VER;

        allocSurf.width = (width + 31) & ~31;
        allocSurf.height = (height + 31) & ~31;

        allocSurf.memoryHeap = NV_ENC_MEMORY_HEAP_SYSMEM_CACHED;
        allocSurf.bufferFmt = NV_ENC_BUFFER_FORMAT_NV12_PL;

        nvStatus = pNvEnc->nvEncCreateInputBuffer(encoder, &allocSurf);

        if (nvStatus != NV_ENC_SUCCESS)
        {
            NvLog(TEXT("nvEncCreateInputBuffer #%d failed"), surfaceCount);
            goto error;
        }

        inputSurfaces[surfaceCount].width = allocSurf.width;
        inputSurfaces[surfaceCount].height = allocSurf.height;
        inputSurfaces[surfaceCount].locked = false;
        inputSurfaces[surfaceCount].useCount = 0;
        inputSurfaces[surfaceCount].inputSurface = allocSurf.inputBuffer;


        NV_ENC_CREATE_BITSTREAM_BUFFER allocOut = { 0 };
        allocOut.version = NV_ENC_CREATE_BITSTREAM_BUFFER_VER;
        allocOut.size = 1024 * 1024;
        allocOut.memoryHeap = NV_ENC_MEMORY_HEAP_SYSMEM_CACHED;

        nvStatus = pNvEnc->nvEncCreateBitstreamBuffer(encoder, &allocOut);

        if (nvStatus != NV_ENC_SUCCESS)
        {
            NvLog(TEXT("Failed allocating bitstream #%d buffer"), surfaceCount);

            outputSurfaces[surfaceCount].outputSurface = 0;
            surfaceCount += 1;

            goto error;
        }

        outputSurfaces[surfaceCount].outputSurface = allocOut.bitstreamBuffer;
        outputSurfaces[surfaceCount].size = allocOut.size;
        outputSurfaces[surfaceCount].busy = false;
    }

    NvLog(TEXT("------------------------------------------"));
    NvLog(TEXT("%s"), GetInfoString().Array());
    NvLog(TEXT("------------------------------------------"));

    alive = true;

    return;

error:
    alive = false;

    for (int i = 0; i < surfaceCount; ++i)
    {
        pNvEnc->nvEncDestroyInputBuffer(encoder, inputSurfaces[i].inputSurface);
        if (outputSurfaces[i].outputSurface != 0)
            pNvEnc->nvEncDestroyBitstreamBuffer(encoder, outputSurfaces[i].outputSurface);
    }
    surfaceCount = 0;

    if (encoder)
        pNvEnc->nvEncDestroyEncoder(encoder);
    encoder = 0;

    if (cuContext)
        cuCtxDestroy(cuContext);
}
Exemplo n.º 22
0
void update_phi_fixed(int doc_number, int time,
		      lda_post* p, lda_seq* var,
		      gsl_matrix* g3_matrix,
		      gsl_matrix* g4_matrix,
		      gsl_matrix* g5_matrix) {
    // Hate to do this, but I had problems allocating this data
    // structure.
    if (scaled_influence == NULL) {
      scaled_influence = NewScaledInfluence(FLAGS_max_number_time_points);
    }

    int i, k, n, K = p->model->ntopics, N = p->doc->nterms;
    double dig[p->model->ntopics];

    double k_sum = 0.0;
    for (k = 0; k < K; k++) {
        double gamma_k = vget(p->gamma, k);
        dig[k] = gsl_sf_psi(gamma_k);
	k_sum += gamma_k;
    }
    double dig_sum = gsl_sf_psi(k_sum);

    gsl_vector_view document_weights;
    if (var && var->influence) {
      document_weights = gsl_matrix_row(
      var->influence->doc_weights[time], doc_number);
    }

    for (n=0; n < N; ++n) {
      int w = p->doc->word[n];
      // We have info. about the topics. Use them!
      // Try two alternate approaches.  We compare results of the new
      // algorithm with the old to make sure we're not doing anything
      // silly.

      for (k = 0; k < K; ++k) {
	// Find an estimate for log_phi_nk.
	double doc_weight = 0.0;
	sslm_var* topic = var->topic[k];
	const double chain_variance = topic->chain_variance;

	// These matrices are already set up for the correct time.
	double g3 = mget(g3_matrix, w, k);
	double g4 = mget(g4_matrix, w, k);
	double g5 = mget(g5_matrix, w, k);
	double w_phi_sum = gsl_matrix_get(
	    var->topic[k]->w_phi_sum, w, time);

	// Only set these variables if we are within the correct
	// time window.
	if (time < var->nseq) {
	  doc_weight = gsl_vector_get(&document_weights.vector, k);
	}
	
	double term_weight;
	if (FLAGS_normalize_docs == "normalize") {
	  term_weight = ((double) p->doc->count[n]
			 / (double) p->doc->total);
	} else if (FLAGS_normalize_docs == "log") {
	  term_weight = log(p->doc->count[n] + 1.0);
	} else if (FLAGS_normalize_docs == "log_norm") {
	  term_weight = log(p->doc->count[n] / p->doc->total);
	} else if (FLAGS_normalize_docs == "identity") {
	  term_weight = p->doc->count[n];
	} else if (FLAGS_normalize_docs == "occurrence") {
	  term_weight = ((double) p->doc->count[n]
			 / (double) p->doc->total);
	} else {
	  assert(0);
	}

	assert(var != NULL);
	
	double total, term1, term2, term3, term4;
	double phi_last = 0.0;

	// It's unnecessary to always multiply by 1/chain_variance
	// this deep in a loop, but it's likely not a major
	// bottleneck.
	term1 = dig[k] + mget(p->model->topics, w, k);
	term2 = (g3
		 * term_weight
		 * doc_weight
		 / chain_variance);
	term3 = (term_weight
		 * doc_weight
		 * g4
		 / chain_variance);
	term4 = (term_weight * term_weight
		 * (phi_last * (doc_weight * doc_weight)
		    - (doc_weight * doc_weight
		       + FLAGS_sigma_l * FLAGS_sigma_l))
		 * g5
		 / chain_variance);

	// Note: we're ignoring term3.  sgerrish: 18 July 2010:
	// Changing term2 to have a positive coefficient (instead of
	// negative) to be consistent with parallel version.
	// sgerrish: 23 July 2010: changing term2 back to negative,
	// to try to reproduce earlier results.
	total = term1 - term2 - term3 + term4;
	mset(p->log_phi, n, k, total);
      }
      
      // Normalize in log space.
      gsl_vector log_phi_row = gsl_matrix_row(p->log_phi, n).vector;
      gsl_vector phi_row = gsl_matrix_row(p->phi, n).vector;
      log_normalize(&log_phi_row);
      
      for (i = 0; i < K; i++) {
	vset(&phi_row, i, exp(vget(&log_phi_row, i)));
      }
    }
}
Exemplo n.º 23
0
void minc(gsl_matrix* m, int i, int j, double x)
{
    mset(m, i, j, mget(m, i, j) + x);
}
Exemplo n.º 24
0
void NVENCEncoder::init()
{
    NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS stEncodeSessionParams = {0};
    NV_ENC_PRESET_CONFIG presetConfig = {0};
    GUID clientKey = NV_CLIENT_KEY;
    CUcontext cuContextCurr;
    NVENCSTATUS nvStatus = NV_ENC_SUCCESS;
    int surfaceCount = 0;

    GUID encoderPreset = NV_ENC_PRESET_HQ_GUID;
    dontTouchConfig = false;
    bool is2PassRC = false;

    String profileString = AppConfig->GetString(TEXT("Video Encoding"), TEXT("X264Profile"), TEXT("high"));

    String presetString = AppConfig->GetString(TEXT("Video Encoding"), TEXT("NVENCPreset"), TEXT("High Quality"));

    if (presetString == TEXT("High Performance"))
    {
        encoderPreset = NV_ENC_PRESET_HP_GUID;
    }
    else if (presetString == TEXT("High Quality"))
    {
        encoderPreset = NV_ENC_PRESET_HQ_GUID;
    }
    else if (presetString == TEXT("Bluray Disk"))
    {
        encoderPreset = NV_ENC_PRESET_BD_GUID;
    }
    else if (presetString == TEXT("Low Latency (2pass)"))
    {
        encoderPreset = NV_ENC_PRESET_LOW_LATENCY_DEFAULT_GUID;
        is2PassRC = true;
    }
    else if (presetString == TEXT("High Performance Low Latency (2pass)"))
    {
        encoderPreset = NV_ENC_PRESET_LOW_LATENCY_HP_GUID;
        is2PassRC = true;
    }
    else if (presetString == TEXT("High Quality Low Latency (2pass)"))
    {
        encoderPreset = NV_ENC_PRESET_LOW_LATENCY_HQ_GUID;
        is2PassRC = true;
    }
    else if (presetString == TEXT("Low Latency"))
    {
        encoderPreset = NV_ENC_PRESET_LOW_LATENCY_DEFAULT_GUID;
    }
    else if (presetString == TEXT("High Performance Low Latency"))
    {
        encoderPreset = NV_ENC_PRESET_LOW_LATENCY_HP_GUID;
    }
    else if (presetString == TEXT("High Quality Low Latency"))
    {
        encoderPreset = NV_ENC_PRESET_LOW_LATENCY_HQ_GUID;
    }
    else if (presetString == TEXT("Lossless"))
    {
        encoderPreset = NV_ENC_PRESET_LOSSLESS_DEFAULT_GUID;
        dontTouchConfig = true;
    }
    else if (presetString == TEXT("High Performance Lossless"))
    {
        encoderPreset = NV_ENC_PRESET_LOSSLESS_HP_GUID;
        dontTouchConfig = true;
    }
    else if (presetString == TEXT("NVDefault"))
    {
        encoderPreset = NV_ENC_PRESET_DEFAULT_GUID;
    }
    else if (presetString == TEXT("Streaming"))
    {
        encoderPreset = NV_ENC_PRESET_STREAMING;
        clientKey = NV_ENC_KEY_STREAMING;
    }
    else if (presetString == TEXT("Streaming (2pass)"))
    {
        encoderPreset = NV_ENC_PRESET_STREAMING;
        is2PassRC = true;
        clientKey = NV_ENC_KEY_STREAMING;
    }
    else
    {
        if (height > 1080 || (height == 1080 && fps > 30))
        {
            encoderPreset = NV_ENC_PRESET_HQ_GUID;
        }
        if (height > 720 || (height == 720 && fps > 30))
        {
            encoderPreset = NV_ENC_PRESET_LOW_LATENCY_HQ_GUID;
        }
        else
        {
            encoderPreset = NV_ENC_PRESET_LOW_LATENCY_HQ_GUID;
            is2PassRC = true;
        }
    }

    TCHAR envClientKey[128] = {0};
    DWORD envRes = GetEnvironmentVariable(TEXT("NVENC_KEY"), envClientKey, 128);
    if (envRes > 0 && envRes <= 128)
    {
        if (stringToGuid(envClientKey, &clientKey))
        {
            NvLog(TEXT("Got NVENC key from environment"));
        }
        else
        {
            NvLog(TEXT("NVENC_KEY environment variable has invalid format"));
        }
    }

    mset(&initEncodeParams, 0, sizeof(NV_ENC_INITIALIZE_PARAMS));
    mset(&encodeConfig, 0, sizeof(NV_ENC_CONFIG));

    encodeConfig.version = NV_ENC_CONFIG_VER;
    presetConfig.version = NV_ENC_PRESET_CONFIG_VER;
    presetConfig.presetCfg.version = NV_ENC_CONFIG_VER;
    initEncodeParams.version = NV_ENC_INITIALIZE_PARAMS_VER;

    stEncodeSessionParams.version = NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS_VER;
    stEncodeSessionParams.apiVersion = NVENCAPI_VERSION;
    stEncodeSessionParams.clientKeyPtr = &clientKey;

    cuContext = 0;
    checkCudaErrors(cuCtxCreate(&cuContext, 0, pNvencDevices[iNvencUseDeviceID]));
    checkCudaErrors(cuCtxPopCurrent(&cuContextCurr));

    stEncodeSessionParams.device = (void*)cuContext;
    stEncodeSessionParams.deviceType = NV_ENC_DEVICE_TYPE_CUDA;

    nvStatus = pNvEnc->nvEncOpenEncodeSessionEx(&stEncodeSessionParams, &encoder);
    if (nvStatus != NV_ENC_SUCCESS)
    {
        encoder = 0;

        OBSMessageBox(NULL,
                      Str("Encoder.NVENC.OldDriver"),
                      NULL,
                      MB_OK | MB_ICONERROR);

        NvLog(TEXT("nvEncOpenEncodeSessionEx failed with 0x%x - outdated driver?"), nvStatus);
        goto error;
    }

    if (!populateEncodePresetGUIDs())
        goto error;

    if (!checkPresetSupport(encoderPreset))
    {
        NvLog(TEXT("Preset is not supported!"));
        goto error;
    }

    nvStatus = pNvEnc->nvEncGetEncodePresetConfig(encoder, NV_ENC_CODEC_H264_GUID, encoderPreset, &presetConfig);
    if (nvStatus != NV_ENC_SUCCESS)
    {
        NvLog(TEXT("nvEncGetEncodePresetConfig failed with 0x%x"), nvStatus);
        goto error;
    }

    initEncodeParams.encodeGUID = NV_ENC_CODEC_H264_GUID;
    initEncodeParams.encodeHeight = height;
    initEncodeParams.encodeWidth = width;
    initEncodeParams.darHeight = height;
    initEncodeParams.darWidth = width;
    initEncodeParams.frameRateNum = fps;
    initEncodeParams.frameRateDen = 1;

    initEncodeParams.enableEncodeAsync = 0;
    initEncodeParams.enablePTD = 1;

    initEncodeParams.presetGUID = encoderPreset;

    initEncodeParams.encodeConfig = &encodeConfig;
    memcpy(&encodeConfig, &presetConfig.presetCfg, sizeof(NV_ENC_CONFIG));

    encodeConfig.version = NV_ENC_CONFIG_VER;

    if (!dontTouchConfig)
    {
        if (keyint != 0)
            encodeConfig.gopLength = keyint * fps;

        if (maxBitRate != -1)
        {
            encodeConfig.rcParams.averageBitRate = maxBitRate * 1000;
            encodeConfig.rcParams.maxBitRate = maxBitRate * 1000;
        }

        if (bufferSize != -1)
        {
            encodeConfig.rcParams.vbvBufferSize = bufferSize * 1000;
            encodeConfig.rcParams.vbvInitialDelay = bufferSize * 1000;
        }

        if (bUseCBR)
        {
            auto filler = AppConfig->GetInt(TEXT("Video Encoding"), TEXT("PadCBR"), 1) != 0;
            if (is2PassRC)
            {
                encodeConfig.rcParams.rateControlMode = filler ? NV_ENC_PARAMS_RC_2_PASS_FRAMESIZE_CAP : NV_ENC_PARAMS_RC_2_PASS_VBR;
            }
            else
            {
                encodeConfig.rcParams.rateControlMode = filler ? NV_ENC_PARAMS_RC_CBR : NV_ENC_PARAMS_RC_VBR;
            }

            encodeConfig.frameIntervalP = 1;

            encodeConfig.encodeCodecConfig.h264Config.adaptiveTransformMode = NV_ENC_H264_ADAPTIVE_TRANSFORM_ENABLE;
            encodeConfig.encodeCodecConfig.h264Config.fmoMode = NV_ENC_H264_FMO_DISABLE;
        }
        else
        {
            encodeConfig.rcParams.rateControlMode = NV_ENC_PARAMS_RC_VBR_MINQP;
            encodeConfig.rcParams.enableMinQP = 1;
            encodeConfig.rcParams.minQP.qpInterB = 32 - quality;
            encodeConfig.rcParams.minQP.qpInterP = 32 - quality;
            encodeConfig.rcParams.minQP.qpIntra = 32 - quality;

            encodeConfig.frameIntervalP = 3;
        }

        encodeConfig.encodeCodecConfig.h264Config.outputBufferingPeriodSEI = 1;
        encodeConfig.encodeCodecConfig.h264Config.outputPictureTimingSEI = 1;
        encodeConfig.encodeCodecConfig.h264Config.disableSPSPPS = 1;

        encodeConfig.encodeCodecConfig.h264Config.enableVFR = bUseCFR ? 0 : 1;

        encodeConfig.frameFieldMode = NV_ENC_PARAMS_FRAME_FIELD_MODE_FRAME;

        if(profileString.CompareI(TEXT("main")))
            encodeConfig.profileGUID = NV_ENC_H264_PROFILE_MAIN_GUID;
        else if(profileString.CompareI(TEXT("high")))
            encodeConfig.profileGUID = NV_ENC_H264_PROFILE_HIGH_GUID;

        encodeConfig.encodeCodecConfig.h264Config.disableSPSPPS = 1;
        encodeConfig.encodeCodecConfig.h264Config.bdirectMode = encodeConfig.frameIntervalP > 1 ? NV_ENC_H264_BDIRECT_MODE_TEMPORAL : NV_ENC_H264_BDIRECT_MODE_DISABLE;
        encodeConfig.encodeCodecConfig.h264Config.idrPeriod = encodeConfig.gopLength;

        encodeConfig.encodeCodecConfig.h264Config.h264VUIParameters.videoSignalTypePresentFlag = 1;
        encodeConfig.encodeCodecConfig.h264Config.h264VUIParameters.colourDescriptionPresentFlag = 1;
        encodeConfig.encodeCodecConfig.h264Config.h264VUIParameters.colourMatrix = colorDesc.matrix;
        encodeConfig.encodeCodecConfig.h264Config.h264VUIParameters.videoFullRangeFlag = colorDesc.fullRange;
        encodeConfig.encodeCodecConfig.h264Config.h264VUIParameters.videoFormat = 5;
        encodeConfig.encodeCodecConfig.h264Config.h264VUIParameters.colourPrimaries = colorDesc.primaries;
        encodeConfig.encodeCodecConfig.h264Config.h264VUIParameters.transferCharacteristics = colorDesc.transfer;
    }

    nvStatus = pNvEnc->nvEncInitializeEncoder(encoder, &initEncodeParams);

    if (nvStatus != NV_ENC_SUCCESS)
    {
        NvLog(TEXT("nvEncInitializeEncoder failed with 0x%x"), nvStatus);
        goto error;
    }

    for (surfaceCount = 0; surfaceCount < maxSurfaceCount; ++surfaceCount)
    {
        NV_ENC_CREATE_INPUT_BUFFER allocSurf = { 0 };
        allocSurf.version = NV_ENC_CREATE_INPUT_BUFFER_VER;

        allocSurf.width = (width + 31) & ~31;
        allocSurf.height = (height + 31) & ~31;

        allocSurf.memoryHeap = NV_ENC_MEMORY_HEAP_SYSMEM_CACHED;
        allocSurf.bufferFmt = NV_ENC_BUFFER_FORMAT_NV12_PL;

        nvStatus = pNvEnc->nvEncCreateInputBuffer(encoder, &allocSurf);

        if (nvStatus != NV_ENC_SUCCESS)
        {
            NvLog(TEXT("nvEncCreateInputBuffer #%d failed with 0x%x"), surfaceCount, nvStatus);
            goto error;
        }

        inputSurfaces[surfaceCount].width = allocSurf.width;
        inputSurfaces[surfaceCount].height = allocSurf.height;
        inputSurfaces[surfaceCount].locked = false;
        inputSurfaces[surfaceCount].useCount = 0;
        inputSurfaces[surfaceCount].inputSurface = allocSurf.inputBuffer;


        NV_ENC_CREATE_BITSTREAM_BUFFER allocOut = { 0 };
        allocOut.version = NV_ENC_CREATE_BITSTREAM_BUFFER_VER;
        allocOut.size = outBufferSize;
        allocOut.memoryHeap = NV_ENC_MEMORY_HEAP_SYSMEM_CACHED;

        nvStatus = pNvEnc->nvEncCreateBitstreamBuffer(encoder, &allocOut);

        if (nvStatus != NV_ENC_SUCCESS)
        {
            NvLog(TEXT("Failed allocating bitstream #%d buffer with 0x%x"), surfaceCount, nvStatus);

            outputSurfaces[surfaceCount].outputSurface = 0;
            surfaceCount += 1;

            goto error;
        }

        outputSurfaces[surfaceCount].outputSurface = allocOut.bitstreamBuffer;
        outputSurfaces[surfaceCount].size = allocOut.size;
        outputSurfaces[surfaceCount].busy = false;
    }

    NvLog(TEXT("------------------------------------------"));
    NvLog(TEXT("%s"), GetInfoString().Array());
    NvLog(TEXT("------------------------------------------"));

    alive = true;

    return;

error:
    alive = false;

    for (int i = 0; i < surfaceCount; ++i)
    {
        pNvEnc->nvEncDestroyInputBuffer(encoder, inputSurfaces[i].inputSurface);
        if (outputSurfaces[i].outputSurface != 0)
            pNvEnc->nvEncDestroyBitstreamBuffer(encoder, outputSurfaces[i].outputSurface);
    }
    surfaceCount = 0;

    if (encoder)
        pNvEnc->nvEncDestroyEncoder(encoder);
    encoder = 0;

    if (cuContext)
        cuCtxDestroy(cuContext);
}
void init (int startx, int starty) {
    mset (visit, false);
    cost [startx][starty] = 0;
    visit [startx][starty] = true;
    q.push (make_pair (startx, starty));
}
Exemplo n.º 26
0
//--------------------------------------------------------------------------------------------------*/
// 创建文件系统
void fs_make(void)
{
	// 超级块
	Super_Block	sb;
	
	sb.magic			= MAGIC;			// 魔数
	sb.imap_1st_sects		= IMAP_1ST_SECTS;		// imap第一个扇区号
	sb.nr_inodes		= NR_INODES;		// inodes总数
	sb.nr_imap_sects		= NR_IMAP_SECTS;		// inode-map 占用扇区数
	sb.smap_1st_sects		= SMAP_1ST_SECTS;		// smap第一个扇区号
	sb.nr_sects		= NR_SECTS;		// 扇区总数
	sb.nr_smap_sects		= NR_SMAP_SECTS;		// sector-map占用扇区数
	sb.inode_1st_sects		= INODE_1ST_SECTS;		// inode_array第一个扇区号
	sb.inode_size		= INODE_SIZE;		// inode 大小
	sb.inode_per_sect		= INODE_PER_SECT;		// 每扇区能容纳的inode数
	sb.nr_inode_sects		= NR_INODE_SECTS;		// inode占用扇区数
	sb.dat_1st_sect		= DAT_1ST_SECT;		// 第一个数据扇区号
	sb.dir_ent_size		= DIR_ENT_SIZE;		// dir_entry的大小
	sb.dir_ent_inode_off	= DIR_ENT_INODE_OFF;	// dir_entry结构中inode_nr的偏移
	sb.dir_ent_fname_off	= DIR_ENT_FNAME_OFF;	// dir_entry结构中name的偏移
	sb.dir_ent_per_sect		= DIR_ENT_PER_SECT;		// 每个root扇区能容纳的dir_entry数
	sb.root_sects		= ROOT_SECTS;		// root占用扇区数
	sb.root_inode		= ROOT_INODE;		// root directory 的inode号
	sb.inode_isize_off		= INODE_ISEZE_OFF;		// inode结构中i_size的偏移
	sb.inode_start_off		= INODE_START_OFF;		// inode结构中i_start_sect的偏移
	
	printk("super block  lba: %x,sects: %x\n",1,1);
	printk("i_node map   lba: %x,sects: %x\n",IMAP_1ST_SECTS	,NR_IMAP_SECTS);
	printk("sector map   lba: %x,sects: %x\n",SMAP_1ST_SECTS	,NR_SMAP_SECTS);
	printk("inode_array  lba: %x,sects: %x\n",INODE_1ST_SECTS	,NR_INODE_SECTS);
	printk("data_root    lba: %x,sects: %x\n",DAT_1ST_SECT	,NR_SECTS);
	mset(fsbuf,0x11,SECTOR_SIZE * 1);
	memcopy(fsbuf,(char*)&sb,SUPER_BLOCK_SIZE);
	hd_write(ROOT_DEV,fsbuf,SECTOR_SIZE * 1,1);		// 超级块放在第 1 个扇区(从0开始数)
	//----------------------------------------------------------
	// imap
	int	i;
	for(i = 0;i < NR_IMAP_SECTS;i++)
	{
		mset(fsbuf,0,SECTOR_SIZE);
		if(i == 0)
			*fsbuf = 0x1f;			// 0:保留,1:root,2-4:tty0-tty2。总共5位	
		hd_write(ROOT_DEV,fsbuf,SECTOR_SIZE * ( IMAP_1ST_SECTS + i),1);
	}
	//----------------------------------------------------------
	// smap
	mset(fsbuf,0,SECTOR_SIZE * NR_SMAP_SECTS);
	int	j;
	for(i = 0 ;i < (ROOT_SECTS + 1) / 8;i++)		// 0:保留,此时只有root占用了硬盘扇区	// +1 是因为根目录区从第1扇区开始(从0开始数)
		fsbuf[i] = 0xff;
	for(j = 0 ;j < (ROOT_SECTS + 1) % 8;j++)
		fsbuf[i] |= 1 << j;
	hd_write(ROOT_DEV,fsbuf,SECTOR_SIZE * SMAP_1ST_SECTS,NR_SMAP_SECTS);
	
	int	ints	= (ROOT_SECTS + 1) / 32;		// 以4字节为最小单位操作
	int	bits	= (ROOT_SECTS + 1) % 32;
	for(i = 0;i < NR_SMAP_SECTS;i++)
	{
		mset(fsbuf,0,SECTOR_SIZE);
		int*	p_int = (int*)fsbuf;
		for(j = 0;j < SECTOR_SIZE / 4;j++,p_int++)	// 以4字节为最小单位操作
		{
			if(ints > 0)
			{
				*p_int	= 0xffffffff;
				ints--;
				continue;
			}
			// ints为0时,程序才能运行到这里
			*p_int	= 0x00000000;
			if(bits > 0)
			{
				while(bits > 0)
				{
					bits--;
					*p_int	|= 1 << bits;
				}
			}
		}
		hd_write(ROOT_DEV,fsbuf,SECTOR_SIZE * (SMAP_1ST_SECTS + i),1);
	}
	//----------------------------------------------------------
	// inode_array
	DEV_Inode* p_inode = (DEV_Inode*)fsbuf;		// 0:保留,1:root,2-4:tty0-tty2。总共5个
	mset(fsbuf,0,SECTOR_SIZE);
	p_inode++;				// 0:保留
	p_inode->i_mode		= I_MODE_ROOT;	// 1:root
	p_inode->i_size		= SECTOR_SIZE * ROOT_SECTS;
	p_inode->i_start_sect	= 1;
	p_inode->i_nr_sects		= ROOT_SECTS;
	p_inode++;
	for(i = 0 ;i < NR_TTY ;i++,p_inode++)		// 2-4:tty
	{
		p_inode->i_mode		= I_MODE_CHAR;
		p_inode->i_size		= 0;
		p_inode->i_start_sect	= DEVICE(MAJAR_TTY,i);	// 设为tty的设备号
		p_inode->i_nr_sects		= 0;
	}
	hd_write(ROOT_DEV,fsbuf,SECTOR_SIZE * INODE_1ST_SECTS,1);
	//----------------------------------------------------------
	// root(dir_entry)				0:保留,".",tty0-tty2。总共5个
	Dir_Entry* p_dir;
	for(i = 0;i < ROOT_SECTS;i++)			// 其余的清零
	{
		p_dir = (Dir_Entry*)fsbuf;
		for(j = 0;j < DIR_ENT_PER_SECT;j++,p_dir++)
			p_dir->inode_nr = 0;
		hd_write(ROOT_DEV,fsbuf,SECTOR_SIZE * (DAT_1ST_SECT + 1 + i),1);	// +1 是因为根目录区从第1扇区开始(从0开始数)
	}
	p_dir = (Dir_Entry*)fsbuf;
	p_dir++;					// 0:保留
	p_dir->inode_nr	= 1;			// 1:"."	root
	memcopy(p_dir->name,".",2);
	p_dir++;
	for(i = 0;i < NR_TTY;i++,p_dir++)		// tty
	{
		p_dir->inode_nr	= 2 + i;
		memcopy(p_dir->name,"tty0",5);
		p_dir->name[3] = '0' + i;
	}
	hd_write(ROOT_DEV,fsbuf,SECTOR_SIZE * (DAT_1ST_SECT + 1),1);		// +1 是因为根目录区从第1扇区开始(从0开始数)
}
Exemplo n.º 27
0
int DPMHC_xi_smplr(struct str_DPMHC *ptr_DPMHC_data, int i_J, struct str_firm_data *a_firm_data)
{
    int j,i;
    int i_K = ptr_DPMHC_data->i_K;
    int i_n = ptr_DPMHC_data->v_y->size; // is this the same as i_J???
    if (i_n != i_J){
        fprintf(stderr,"Error in  DPMN_xi_smplr(): DPMHC.v_y length does not equal i_J\n");
        exit(1);
    }
    double d_sumT_si;

    gsl_vector_int *vi_S = ptr_DPMHC_data->vi_S;
    gsl_matrix *m_theta = ptr_DPMHC_data->m_DPtheta;
    double d_A = ptr_DPMHC_data->d_A;
    double d_mu_si, d_tau_si, d_ei;
    double d_mean_j, d_var_j;
    double d_xi_j;

    int i_Ti;
    int i_factors = (a_firm_data[0].v_beta)->size;
    gsl_vector *v_ret;
    gsl_matrix *m_factors;
    gsl_vector *v_betai;
    gsl_vector *v_rstar_i;
    gsl_matrix *m_Xi;
    gsl_matrix_view mv_Xi;
    double d_rstar_j;
    double d_s2i;


    for(j=0;j<i_K;j++){

        d_mu_si = mget(m_theta,j,0);
        d_tau_si = mget(m_theta,j,2);


        d_rstar_j = 0.;
        d_sumT_si = 0;
        for(i=0;i<i_J;i++){
            if( vget_int(vi_S,i) == j ){

                d_ei = vget(ptr_DPMHC_data->v_e,i);

                m_factors = a_firm_data[i].m_factors;
                i_Ti = a_firm_data[i].i_ni;
                d_s2i = a_firm_data[i].d_s2;
                m_Xi = gsl_matrix_alloc(i_Ti,i_factors);
                mv_Xi = gsl_matrix_submatrix(m_factors,0,0,i_Ti,i_factors);
                gsl_matrix_memcpy(m_Xi,&mv_Xi.matrix);

                v_betai = a_firm_data[i].v_beta;
                v_ret = a_firm_data[i].v_ret;
                v_rstar_i = gsl_vector_alloc(i_Ti);
                gsl_vector_memcpy(v_rstar_i,v_ret);
                gsl_blas_dgemv(CblasNoTrans, -1.0, m_Xi, v_betai, 1.0, v_rstar_i);

                gsl_vector_add_constant(v_rstar_i, -d_mu_si);
                gsl_vector_scale(v_rstar_i, 1./(sqrt(d_tau_si) * d_ei) );

                d_rstar_j += sum(v_rstar_i);

                d_sumT_si += i_Ti/(d_s2i/(d_tau_si * d_ei * d_ei) );

                gsl_matrix_free(m_Xi);
                gsl_vector_free(v_rstar_i);
            }
        }

        d_var_j = 1./( 1./(d_A * d_A) + d_sumT_si);
        d_mean_j = d_rstar_j * d_var_j;

        d_xi_j = d_mean_j + gsl_ran_gaussian_ziggurat(rng, sqrt(d_var_j) );

        mset(m_theta, j, 1, d_xi_j);

       // printf("%d: eta = %g lambda^2 = %g\n",j, mget(m_theta,j,0), mget(m_theta,j,1) );
     }


    return 0;
}