Esempio n. 1
0
/*
Open a Zip file. path contain the full pathname (by example,
on a Windows NT computer "c:\\test\\zlib114.zip" or on an Unix computer
"zlib/zlib114.zip".
If the zipfile cannot be opened (file doesn't exist or in not valid), the
return value is NULL.
Else, the return value is a unzFile Handle, usable with other function
of this unzip package.
 */
extern unzFile ZEXPORT unzOpen2(const char *path, zlib_filefunc_def *pzlib_filefunc_def)
{
  unz_s us;
  unz_s *s;
  DWORD central_pos, uL;

  DWORD number_disk; /* number of the current dist, used for
  spaning ZIP, unsupported, always 0*/
  DWORD number_disk_with_CD; /* number the the disk with central dir, used
  for spaning ZIP, unsupported, always 0*/
  DWORD number_entry_CD; /* total number of entries in
  the central dir
  (same than number_entry on nospan) */

  int err = UNZ_OK;

  if (pzlib_filefunc_def == NULL)
  {
    fill_fopen_filefunc(&us.z_filefunc);
  }
  else
  {
    us.z_filefunc =  *pzlib_filefunc_def;
  }

  us.filestream = (*(us.z_filefunc.zopen_file))(us.z_filefunc.opaque, path, ZLIB_FILEFUNC_MODE_READ | ZLIB_FILEFUNC_MODE_EXISTING);
  if (us.filestream == NULL)
  {
    return NULL;
  }

  central_pos = unzlocal_SearchCentralDir(&us.z_filefunc, us.filestream);
  if (central_pos == 0)
  {
    err = UNZ_ERRNO;
  }

  if (ZSEEK(us.z_filefunc, us.filestream, central_pos, SEEK_SET) != 0)
  {
    err = UNZ_ERRNO;
  }

  /* the signature, already checked */
  if (unzlocal_getLong(&us.z_filefunc, us.filestream, &uL) != UNZ_OK)
  {
    err = UNZ_ERRNO;
  }

  /* number of this disk */
  if (unzlocal_getShort(&us.z_filefunc, us.filestream, &number_disk) != UNZ_OK)
  {
    err = UNZ_ERRNO;
  }

  /* number of the disk with the start of the central directory */
  if (unzlocal_getShort(&us.z_filefunc, us.filestream, &number_disk_with_CD) != UNZ_OK)
  {
    err = UNZ_ERRNO;
  }

  /* total number of entries in the central dir on this disk */
  if (unzlocal_getShort(&us.z_filefunc, us.filestream, &us.gi.number_entry) != UNZ_OK)
  {
    err = UNZ_ERRNO;
  }

  /* total number of entries in the central dir */
  if (unzlocal_getShort(&us.z_filefunc, us.filestream, &number_entry_CD) != UNZ_OK)
  {
    err = UNZ_ERRNO;
  }

  if ((number_entry_CD != us.gi.number_entry) || (number_disk_with_CD != 0) || (number_disk != 0))
  {
    err = UNZ_BADZIPFILE;
  }

  /* size of the central directory */
  if (unzlocal_getLong(&us.z_filefunc, us.filestream, &us.size_central_dir) != UNZ_OK)
  {
    err = UNZ_ERRNO;
  }

  /* offset of start of central directory with respect to the
  starting disk number */
  if (unzlocal_getLong(&us.z_filefunc, us.filestream, &us.offset_central_dir) != UNZ_OK)
  {
    err = UNZ_ERRNO;
  }

  /* zipfile comment length */
  if (unzlocal_getShort(&us.z_filefunc, us.filestream, &us.gi.size_comment) != UNZ_OK)
  {
    err = UNZ_ERRNO;
  }

  if ((central_pos < us.offset_central_dir + us.size_central_dir) && (err == UNZ_OK))
  {
    err = UNZ_BADZIPFILE;
  }

  if (err != UNZ_OK)
  {
    ZCLOSE(us.z_filefunc, us.filestream);
    return NULL;
  }

  us.byte_before_the_zipfile = central_pos - (us.offset_central_dir + us.size_central_dir);
  us.central_pos = central_pos;
  us.pfile_in_zip_read = NULL;
  us.encrypted = 0;


  s = (unz_s*)ALLOC(sizeof(unz_s));
  *s = us;
  unzGoToFirstFile((unzFile)s);
  return (unzFile)s;
}
static int opus_decode_frame(OpusDecoder *st, const unsigned char *data,
      int len, opus_val16 *pcm, int frame_size, int decode_fec)
{
   void *silk_dec;
   CELTDecoder *celt_dec;
   int i, silk_ret=0, celt_ret=0;
   ec_dec dec;
   opus_int32 silk_frame_size;
   VARDECL(opus_int16, pcm_silk);
   VARDECL(opus_val16, pcm_transition);
   VARDECL(opus_val16, redundant_audio);

   int audiosize;
   int mode;
   int transition=0;
   int start_band;
   int redundancy=0;
   int redundancy_bytes = 0;
   int celt_to_silk=0;
   int c;
   int F2_5, F5, F10, F20;
   const opus_val16 *window;
   opus_uint32 redundant_rng = 0;
   ALLOC_STACK;

   silk_dec = (char*)st+st->silk_dec_offset;
   celt_dec = (CELTDecoder*)((char*)st+st->celt_dec_offset);
   F20 = st->Fs/50;
   F10 = F20>>1;
   F5 = F10>>1;
   F2_5 = F5>>1;
   if (frame_size < F2_5)
      return OPUS_BUFFER_TOO_SMALL;
   /* Payloads of 1 (2 including ToC) or 0 trigger the PLC/DTX */
   if (len<=1)
   {
      data = NULL;
      /* In that case, don't conceal more than what the ToC says */
      frame_size = IMIN(frame_size, st->frame_size);
   }
   if (data != NULL)
   {
      audiosize = st->frame_size;
      mode = st->mode;
      ec_dec_init(&dec,(unsigned char*)data,len);
   } else {
      audiosize = frame_size;

      if (st->prev_mode == 0)
      {
         /* If we haven't got any packet yet, all we can do is return zeros */
         for (i=0;i<audiosize*st->channels;i++)
            pcm[i] = 0;
         RESTORE_STACK;
         return audiosize;
      } else {
         mode = st->prev_mode;
      }
   }

   /* For CELT/hybrid PLC of more than 20 ms, do multiple calls */
   if (data==NULL && frame_size > F20 && mode != MODE_SILK_ONLY)
   {
      int nb_samples = 0;
      do {
         int ret = opus_decode_frame(st, NULL, 0, pcm, F20, 0);
         if (ret != F20)
            return OPUS_INTERNAL_ERROR;
         pcm += F20*st->channels;
         nb_samples += F20;
      } while (nb_samples < frame_size);
      RESTORE_STACK;
      return frame_size;
   }
   ALLOC(pcm_transition, F5*st->channels, opus_val16);

   if (data!=NULL && st->prev_mode > 0 && (
       (mode == MODE_CELT_ONLY && st->prev_mode != MODE_CELT_ONLY && !st->prev_redundancy)
    || (mode != MODE_CELT_ONLY && st->prev_mode == MODE_CELT_ONLY) )
      )
   {
      transition = 1;
      if (mode == MODE_CELT_ONLY)
         opus_decode_frame(st, NULL, 0, pcm_transition, IMIN(F5, audiosize), 0);
   }
   if (audiosize > frame_size)
   {
      /*fprintf(stderr, "PCM buffer too small: %d vs %d (mode = %d)\n", audiosize, frame_size, mode);*/
      RESTORE_STACK;
      return OPUS_BAD_ARG;
   } else {
      frame_size = audiosize;
   }

   ALLOC(pcm_silk, IMAX(F10, frame_size)*st->channels, opus_int16);
   ALLOC(redundant_audio, F5*st->channels, opus_val16);

   /* SILK processing */
   if (mode != MODE_CELT_ONLY)
   {
      int lost_flag, decoded_samples;
      opus_int16 *pcm_ptr = pcm_silk;

      if (st->prev_mode==MODE_CELT_ONLY)
         silk_InitDecoder( silk_dec );

      /* The SILK PLC cannot produce frames of less than 10 ms */
      st->DecControl.payloadSize_ms = IMAX(10, 1000 * audiosize / st->Fs);

      if (data != NULL)
      {
        st->DecControl.nChannelsInternal = st->stream_channels;
        if( mode == MODE_SILK_ONLY ) {
           if( st->bandwidth == OPUS_BANDWIDTH_NARROWBAND ) {
              st->DecControl.internalSampleRate = 8000;
           } else if( st->bandwidth == OPUS_BANDWIDTH_MEDIUMBAND ) {
              st->DecControl.internalSampleRate = 12000;
           } else if( st->bandwidth == OPUS_BANDWIDTH_WIDEBAND ) {
              st->DecControl.internalSampleRate = 16000;
           } else {
              st->DecControl.internalSampleRate = 16000;
              silk_assert( 0 );
           }
        } else {
           /* Hybrid mode */
           st->DecControl.internalSampleRate = 16000;
        }
     }

     lost_flag = data == NULL ? 1 : 2 * decode_fec;
     decoded_samples = 0;
     do {
        /* Call SILK decoder */
        int first_frame = decoded_samples == 0;
        silk_ret = silk_Decode( silk_dec, &st->DecControl,
                                lost_flag, first_frame, &dec, pcm_ptr, &silk_frame_size );
        if( silk_ret ) {
           if (lost_flag) {
              /* PLC failure should not be fatal */
              silk_frame_size = frame_size;
              for (i=0;i<frame_size*st->channels;i++)
                 pcm_ptr[i] = 0;
           } else {
             RESTORE_STACK;
             return OPUS_INVALID_PACKET;
           }
        }
        pcm_ptr += silk_frame_size * st->channels;
        decoded_samples += silk_frame_size;
      } while( decoded_samples < frame_size );
   }

   start_band = 0;
   if (!decode_fec && mode != MODE_CELT_ONLY && data != NULL
    && ec_tell(&dec)+17+20*(st->mode == MODE_HYBRID) <= 8*len)
   {
      /* Check if we have a redundant 0-8 kHz band */
      if (mode == MODE_HYBRID)
         redundancy = ec_dec_bit_logp(&dec, 12);
      else
         redundancy = 1;
      if (redundancy)
      {
         celt_to_silk = ec_dec_bit_logp(&dec, 1);
         /* redundancy_bytes will be at least two, in the non-hybrid
            case due to the ec_tell() check above */
         redundancy_bytes = mode==MODE_HYBRID ?
               (opus_int32)ec_dec_uint(&dec, 256)+2 :
               len-((ec_tell(&dec)+7)>>3);
         len -= redundancy_bytes;
         /* This is a sanity check. It should never happen for a valid
            packet, so the exact behaviour is not normative. */
         if (len*8 < ec_tell(&dec))
         {
            len = 0;
            redundancy_bytes = 0;
            redundancy = 0;
         }
         /* Shrink decoder because of raw bits */
         dec.storage -= redundancy_bytes;
      }
   }
   if (mode != MODE_CELT_ONLY)
      start_band = 17;

   {
      int endband=21;

      switch(st->bandwidth)
      {
      case OPUS_BANDWIDTH_NARROWBAND:
         endband = 13;
         break;
      case OPUS_BANDWIDTH_MEDIUMBAND:
      case OPUS_BANDWIDTH_WIDEBAND:
         endband = 17;
         break;
      case OPUS_BANDWIDTH_SUPERWIDEBAND:
         endband = 19;
         break;
      case OPUS_BANDWIDTH_FULLBAND:
         endband = 21;
         break;
      }
      celt_decoder_ctl(celt_dec, CELT_SET_END_BAND(endband));
      celt_decoder_ctl(celt_dec, CELT_SET_CHANNELS(st->stream_channels));
   }

   if (redundancy)
      transition = 0;

   if (transition && mode != MODE_CELT_ONLY)
      opus_decode_frame(st, NULL, 0, pcm_transition, IMIN(F5, audiosize), 0);

   /* 5 ms redundant frame for CELT->SILK*/
   if (redundancy && celt_to_silk)
   {
      celt_decoder_ctl(celt_dec, CELT_SET_START_BAND(0));
      celt_decode_with_ec(celt_dec, data+len, redundancy_bytes,
                          redundant_audio, F5, NULL);
      celt_decoder_ctl(celt_dec, OPUS_GET_FINAL_RANGE(&redundant_rng));
   }

   /* MUST be after PLC */
   celt_decoder_ctl(celt_dec, CELT_SET_START_BAND(start_band));

   if (mode != MODE_SILK_ONLY)
   {
      int celt_frame_size = IMIN(F20, frame_size);
      /* Make sure to discard any previous CELT state */
      if (mode != st->prev_mode && st->prev_mode > 0 && !st->prev_redundancy)
         celt_decoder_ctl(celt_dec, OPUS_RESET_STATE);
      /* Decode CELT */
      celt_ret = celt_decode_with_ec(celt_dec, decode_fec ? NULL : data,
                                     len, pcm, celt_frame_size, &dec);
   } else {
      unsigned char silence[2] = {0xFF, 0xFF};
      for (i=0;i<frame_size*st->channels;i++)
         pcm[i] = 0;
      /* For hybrid -> SILK transitions, we let the CELT MDCT
         do a fade-out by decoding a silence frame */
      if (st->prev_mode == MODE_HYBRID && !(redundancy && celt_to_silk && st->prev_redundancy) )
      {
         celt_decoder_ctl(celt_dec, CELT_SET_START_BAND(0));
         celt_decode_with_ec(celt_dec, silence, 2, pcm, F2_5, NULL);
      }
   }

   if (mode != MODE_CELT_ONLY)
   {
#ifdef FIXED_POINT
      for (i=0;i<frame_size*st->channels;i++)
         pcm[i] = SAT16(pcm[i] + pcm_silk[i]);
#else
      for (i=0;i<frame_size*st->channels;i++)
         pcm[i] = pcm[i] + (opus_val16)((1./32768.)*pcm_silk[i]);
#endif
   }

   {
      const CELTMode *celt_mode;
      celt_decoder_ctl(celt_dec, CELT_GET_MODE(&celt_mode));
      window = celt_mode->window;
   }

   /* 5 ms redundant frame for SILK->CELT */
   if (redundancy && !celt_to_silk)
   {
      celt_decoder_ctl(celt_dec, OPUS_RESET_STATE);
      celt_decoder_ctl(celt_dec, CELT_SET_START_BAND(0));

      celt_decode_with_ec(celt_dec, data+len, redundancy_bytes, redundant_audio, F5, NULL);
      celt_decoder_ctl(celt_dec, OPUS_GET_FINAL_RANGE(&redundant_rng));
      smooth_fade(pcm+st->channels*(frame_size-F2_5), redundant_audio+st->channels*F2_5,
                  pcm+st->channels*(frame_size-F2_5), F2_5, st->channels, window, st->Fs);
   }
   if (redundancy && celt_to_silk)
   {
      for (c=0;c<st->channels;c++)
      {
         for (i=0;i<F2_5;i++)
            pcm[st->channels*i+c] = redundant_audio[st->channels*i+c];
      }
      smooth_fade(redundant_audio+st->channels*F2_5, pcm+st->channels*F2_5,
                  pcm+st->channels*F2_5, F2_5, st->channels, window, st->Fs);
   }
   if (transition)
   {
      if (audiosize >= F5)
      {
         for (i=0;i<st->channels*F2_5;i++)
            pcm[i] = pcm_transition[i];
         smooth_fade(pcm_transition+st->channels*F2_5, pcm+st->channels*F2_5,
                     pcm+st->channels*F2_5, F2_5,
                     st->channels, window, st->Fs);
      } else {
         /* Not enough time to do a clean transition, but we do it anyway
            This will not preserve amplitude perfectly and may introduce
            a bit of temporal aliasing, but it shouldn't be too bad and
            that's pretty much the best we can do. In any case, generating this
            transition it pretty silly in the first place */
         smooth_fade(pcm_transition, pcm,
                     pcm, F2_5,
                     st->channels, window, st->Fs);
      }
   }

   if (len <= 1)
      st->rangeFinal = 0;
   else
      st->rangeFinal = dec.rng ^ redundant_rng;

   st->prev_mode = mode;
   st->prev_redundancy = redundancy && !celt_to_silk;
   RESTORE_STACK;
   return celt_ret < 0 ? celt_ret : audiosize;

}
Esempio n. 3
0
static VALUE ra_sound_allocate(VALUE klass) {
    RA_SOUND *snd = ALLOC(RA_SOUND);
    memset(snd, 0, sizeof(RA_SOUND));
    VALUE self = Data_Wrap_Struct(klass, ra_sound_mark, ra_sound_free, snd);
    return self;
}
Esempio n. 4
0
/**
  @brief Symmetric sifting algorithm.

  @details Assumes that no dead nodes are present.
    <ol>
    <li> Order all the variables according to the number of entries in
    each unique subtable.
    <li> Sift the variable up and down, remembering each time the total
    size of the DD heap and grouping variables that are symmetric.
    <li> Select the best permutation.
    <li> Repeat 3 and 4 for all variables.
    </ol>

  @return 1 plus the number of symmetric variables if successful; 0
  otherwise.

  @sideeffect None

  @see cuddSymmSiftingConv

*/
int
cuddSymmSifting(
  DdManager * table,
  int  lower,
  int  upper)
{
    int		i;
    IndexKey	*var;
    int		size;
    int		x;
    int		result;
    int		symvars;
    int		symgroups;
#ifdef DD_STATS
    int		previousSize;
#endif

    size = table->size;

    /* Find order in which to sift variables. */
    var = ALLOC(IndexKey,size);
    if (var == NULL) {
	table->errorCode = CUDD_MEMORY_OUT;
	goto ddSymmSiftingOutOfMem;
    }

    for (i = 0; i < size; i++) {
	x = table->perm[i];
	var[i].index = i;
	var[i].keys = table->subtables[x].keys;
    }

    util_qsort(var,size,sizeof(IndexKey),ddSymmUniqueCompare);

    /* Initialize the symmetry of each subtable to itself. */
    for (i = lower; i <= upper; i++) {
	table->subtables[i].next = i;
    }

    for (i = 0; i < ddMin(table->siftMaxVar,size); i++) {
	if (table->ddTotalNumberSwapping >= table->siftMaxSwap)
	    break;
        if (util_cpu_time() - table->startTime > table->timeLimit) {
            table->autoDyn = 0; /* prevent further reordering */
            break;
        }
        if (table->terminationCallback != NULL &&
            table->terminationCallback(table->tcbArg)) {
            table->autoDyn = 0; /* prevent further reordering */
            break;
        }
	x = table->perm[var[i].index];
#ifdef DD_STATS
	previousSize = (int) (table->keys - table->isolated);
#endif
	if (x < lower || x > upper) continue;
	if (table->subtables[x].next == (unsigned) x) {
	    result = ddSymmSiftingAux(table,x,lower,upper);
	    if (!result) goto ddSymmSiftingOutOfMem;
#ifdef DD_STATS
	    if (table->keys < (unsigned) previousSize + table->isolated) {
		(void) fprintf(table->out,"-");
	    } else if (table->keys > (unsigned) previousSize +
		       table->isolated) {
		(void) fprintf(table->out,"+"); /* should never happen */
	    } else {
		(void) fprintf(table->out,"=");
	    }
	    fflush(table->out);
#endif
	}
    }

    FREE(var);

    ddSymmSummary(table, lower, upper, &symvars, &symgroups);

#ifdef DD_STATS
    (void) fprintf(table->out, "\n#:S_SIFTING %8d: symmetric variables\n",
		   symvars);
    (void) fprintf(table->out, "#:G_SIFTING %8d: symmetric groups",
		   symgroups);
#endif

    return(1+symvars);

ddSymmSiftingOutOfMem:

    if (var != NULL) FREE(var);

    return(0);

} /* end of cuddSymmSifting */
Esempio n. 5
0
/*
 * Merge a set of per-file branches into a global branch
 */
static void
rev_branch_merge (rev_ref **branches, int nbranch,
		  rev_ref *branch, rev_list *rl)
{
	int nlive;
	int n;
	rev_commit *prev = NULL;
	rev_commit *head = NULL, **tail = &head;
	rev_commit **commits;
	rev_commit *commit;
	rev_commit *latest;
	rev_commit **p;
	int lazy = 0;
	time_t start = 0;

	ALLOC((commits = calloc (nbranch, sizeof (rev_commit *))), "rev_branch_merge");
	nlive = 0;

//	printf("rev_branch_merge: nbranch=%d\n", nbranch);
	
	for (n = 0; n < nbranch; n++) {
		rev_commit *c;
		/*
		 * Initialize commits to head of each branch
		 */
		c = commits[n] = branches[n]->commit;
		/*
		* Compute number of branches with remaining entries
		*/
		if (!c)
			continue;
		if (branches[n]->tail) {
			c->tailed = 1;
			continue;
		}
		nlive++;
		while (c && !c->tail) {
			if (!start || time_compare(c->date, start) < 0)
			    {
//				printf("  1:setting start=%ld:%s (from %s)\n", start, ctime_nonl(&start), c->file->name);
				start = c->date;
			    }
			c = c->parent;
		}
		if (c && (c->file || c->date != c->parent->date)) {
			if (!start || time_compare(c->date, start) < 0) {
//				printf("  2:setting start=%ld:%s (from %s)\n", start, ctime_nonl(&start), c->file->name);
				start = c->date;
			}
		}
	}

	for (n = 0; n < nbranch; n++) {
		rev_commit *c = commits[n];

#if 0
		printf("Doing commit %p: @ %ld\n", c, c->date);
		if (c->file) printf("  %s\n", c->file->name);
#endif
		
		if (!c->tailed)
			continue;
		if (!start || time_compare(start, c->date) >= 0)
			continue;
		if (c->file) {
		    /*
		      This case can occur if files have been added to
		      a branch since it's creation.
		    */
			printf(	"Warning: %s too late date %s through branch %s (%ld:%ld=%ld)\n",
				c->file->name, ctime_nonl(&c->date), branch->name, start, c->date, start-c->date);
			continue;
		}
		commits[n] = NULL;
	}
	/*
	 * Walk down branches until each one has merged with the
	 * parent branch
	 */
	while (nlive > 0 && nbranch > 0) {
		for (n = 0, p = commits, latest = NULL; n < nbranch; n++) {
			rev_commit *c = commits[n];
			if (!c)
				continue;
			*p++ = c;
			if (c->tailed)
				continue;
			if (!latest || time_compare(latest->date, c->date) < 0)
				latest = c;
		}
		nbranch = p - commits;

		/*
		 * Construct current commit
		 */
		if (!lazy) {
			commit = rev_commit_build (commits, latest, nbranch);
			if (rev_mode == ExecuteGit)
				lazy = 1;
		} else {
			commit = create_tree(latest);
		}

		/*
		 * Step each branch
		 */
		nlive = 0;
		for (n = 0; n < nbranch; n++) {
			rev_commit *c = commits[n];
			rev_commit *to;
			/* already got to parent branch? */
			if (c->tailed)
				continue;
			/* not affected? */
			if (c != latest && !rev_commit_match(c, latest)) {
				if (c->parent || c->file)
					nlive++;
				continue;
			}
			to = c->parent;
			/* starts here? */
			if (!to)
				goto Kill;

			if (c->tail) {
				/*
				 * Adding file independently added on another
				 * non-trunk branch.
				 */
				if (!to->parent && !to->file)
					goto Kill;
				/*
				 * If the parent is at the beginning of trunk
				 * and it is younger than some events on our
				 * branch, we have old CVS adding file
				 * independently
				 * added on another branch.
				 */
				if (start && time_compare(start, to->date) < 0)
					goto Kill;
				/*
				 * XXX: we still can't be sure that it's
				 * not a file added on trunk after parent
				 * branch had forked off it but before
				 * our branch's creation.
				 */
				to->tailed = 1;
			} else if (to->file) {
				nlive++;
			} else {
				/*
				 * See if it's recent CVS adding a file
				 * independently added on another branch.
				 */
				if (!to->parent)
					goto Kill;
				if (to->tail && to->date == to->parent->date)
					goto Kill;
				nlive++;
			}
			if (to->file)
				set_commit(to);
			else
				delete_commit(c);
			commits[n] = to;
			continue;
Kill:
			delete_commit(c);
			commits[n] = NULL;
		}

		*tail = commit;
		tail = &commit->parent;
		prev = commit;
	}
    /*
     * Connect to parent branch
     */
    nbranch = rev_commit_date_sort (commits, nbranch);
    if (nbranch && branch->parent )
    {
	rev_ref	*lost;
	int	present;

//	present = 0;
	for (present = 0; present < nbranch; present++)
	    if (commits[present]->file) {
		/*
		 * Skip files which appear in the repository after
		 * the first commit along the branch
		 */
		if (prev && commits[present]->date > prev->date &&
		    commits[present]->date == rev_commit_first_date (commits[present]))
		{
		    fprintf (stderr, "Warning: file %s appears after branch %s date\n",
			     commits[present]->file->name, branch->name);
		    continue;
		}
		break;
	    }
	if (present == nbranch)
	    *tail = NULL;
	else if ((*tail = rev_commit_locate_one (branch->parent,
						 commits[present])))
	{
	    if (prev && time_compare ((*tail)->date, prev->date) > 0) {
		fprintf (stderr, "Warning: branch point %s -> %s later than branch\n",
			 branch->name, branch->parent->name);
		fprintf (stderr, "\ttrunk(%3d):  %s %s", n,
			 ctime_nonl (&commits[present]->date),
			 commits[present]->file ? " " : "D" );
		if (commits[present]->file)
		    dump_number_file (stderr,
				      commits[present]->file->name,
				      &commits[present]->file->number);
		fprintf (stderr, "\n");
		fprintf (stderr, "\tbranch(%3d): %s  ", n,
			 prev->file?ctime_nonl (&prev->file->date):"no file");
		if (prev->file) {
		    dump_number_file (stderr,
				  prev->file->name,
				  &prev->file->number);
		}
		fprintf (stderr, "\n");
	    }
	} else if ((*tail = rev_commit_locate_date (branch->parent,
						  commits[present]->date)))
	    fprintf (stderr, "Warning: branch point %s -> %s matched by date\n",
		     branch->name, branch->parent->name);
	else {
	    fprintf (stderr, "Error: branch point %s -> %s not found.",
		     branch->name, branch->parent->name);

	    if ((lost = rev_branch_of_commit (rl, commits[present])))
		fprintf (stderr, " Possible match on %s.", lost->name);
	    fprintf (stderr, "\n");
	}
	if (*tail) {
	    if (prev)
		prev->tail = 1;
	} else 
	    *tail = rev_commit_build (commits, commits[0], nbranch);
    }
    for (n = 0; n < nbranch; n++)
	if (commits[n])
	    commits[n]->tailed = 0;
    free (commits);
    branch->commit = head;
}
Esempio n. 6
0
/*
** The routine above returns the sizes of the objects, and saves the lists
**   (the list heads are static).  S then calls again with appropriately
**   sized arrays to this routine. This stuffs the arrays and frees the memory
*/
void s_to_rp2(Sint *n,         Sint *nsplit,    Sint *nnode,     Sint *ncat, 
          Sint *numcat,    Sint *maxcat,    Sint *xvals,     Sint *which, 
          double *cptable, double *dsplit,  Sint *isplit,    Sint *csplit,
          double *dnode,   Sint *inode)
    {
    int i;
    int  nodenum, j;
    struct cptable *cp, *cp2;
    double **ddnode  , *ddsplit[3];
    Sint   *iinode[6], *iisplit[3];
    Sint   **ccsplit;
    double scale;
 
    /*
    ** create the "ragged array" pointers to the matrices
    */

    ddnode = (double **) ALLOC(3+rp.num_resp, sizeof(double *));
    for (i=0; i<(3+rp.num_resp); i++) {
    ddnode[i] = dnode;  dnode  += *nnode;
    }
    for (i=0; i<3; i++) {
    ddsplit[i]= dsplit; dsplit += *nsplit;
    }
    for (i=0; i<6; i++) {
    iinode[i] = inode;  inode  += *nnode;
    }
    for (i=0; i<3; i++) {
    iisplit[i]= isplit; isplit += *nsplit;
    }

    /* I don't understand this next line.  Even if I don't need ccsplit
    ** (maxcat=0), not allocating it makes S memory fault.  Not that
    **  4 extra bytes is any big deal....
    */
    if (*maxcat==0) i=1; else i = *maxcat;
    ccsplit = (Sint **)CALLOC(i, sizeof(Sint *));
    for (i=0; i<*maxcat; i++) {
    ccsplit[i] = csplit;   csplit += *ncat;
    }

    /* retrieve the complexity table */
    scale = 1/tree->risk;
    i=0;
    for (cp = &cptab; cp !=0; cp= cp->forward) {
    cptable[i++] = cp->cp * scale;
    cptable[i++] = cp->nsplit;
    cptable[i++] = cp->risk * scale;
    if (*xvals >1) {
        cptable[i++] = cp->xrisk*scale;
        cptable[i++] = cp->xstd *scale;
        }
    }

    /* Now get the tree */
    *nnode=0; *nsplit=0; *ncat=0;   /*array starting points */
    rpmatrix(tree, nnode, nsplit, ncat, numcat,
            ddsplit, iisplit, ccsplit, ddnode, iinode, 1);

    /*
    ** Now fix up the 'which' array
    **   It would be a simple S match(), except that nodes sometimes get cut
    */
    for (i=0; i<*n; i++) {
    nodenum = savewhich[i];
    do {
        for (j=0; j< *nnode; j++)
        if (iinode[0][j] == nodenum) {
            which[i] = j+1;
            break;
            }
        nodenum /=2;
        }  while (j >= *nnode);
    }

    /*
    ** restore the memory
    **  since the root was not calloced, I have to not free it (second arg
    **  of free_tree).
    */
    free_tree(tree, 0);
    for (cp=cptab.forward; cp!=0; ) {
    cp2 = cp->forward;
    Free(cp);
    cp = cp2;
    }
    Free(ccsplit);
    Free(savewhich);
    }
Esempio n. 7
0
IZ_BOOL DxtEncoder::init(
    izanagi::IMemoryAllocator* allocator,
    izanagi::graph::CGraphicsDevice* device,
    IZ_UINT width, IZ_UINT height,
    const char* vtxShader,
    const char* dxtShader,
    const char* pixelShader)
{
    m_width = width;
    m_height = height;

    char* buf = nullptr;
    IZ_UINT allocatedSize = 0;

    {
        izanagi::CFileInputStream in;
        VRETURN(in.Open(dxtShader));

        allocatedSize = in.GetSize();
        buf = (char*)ALLOC(allocator, allocatedSize);

        in.Read(buf, 0, allocatedSize);
        buf[allocatedSize] = 0;

        m_dxt = device->CreatePixelShader(buf);
        VRETURN(m_dxt);
    }

    {
        izanagi::CFileInputStream in;
        VRETURN(in.Open(vtxShader));

        auto size = in.GetSize();
        IZ_ASSERT(allocatedSize >= size);

        in.Read(buf, 0, size);
        buf[size] = 0;

        m_vs = device->CreateVertexShader(buf);
        VRETURN(m_vs);
    }

    {
        izanagi::CFileInputStream in;
        VRETURN(in.Open(pixelShader));

        auto size = in.GetSize();
        IZ_ASSERT(allocatedSize >= size);

        in.Read(buf, 0, size);
        buf[size] = 0;

        m_ps = device->CreatePixelShader(buf);
        VRETURN(m_ps);
    }

    FREE(allocator, buf);
    {
        m_shd = device->CreateShaderProgram();
        VRETURN(m_shd);

        VRETURN(m_shd->AttachVertexShader(m_vs));
        VRETURN(m_shd->AttachPixelShader(m_dxt));
    }

    {
        m_shdDraw = device->CreateShaderProgram();
        VRETURN(m_shdDraw);

        VRETURN(m_shdDraw->AttachVertexShader(m_vs));
        VRETURN(m_shdDraw->AttachPixelShader(m_ps));
    }

    {
        // NOTE
        // DXTは 4x4 ブロックで、128bit/block.
        // GL_RGBA32UI は 128bit/texel.
        // すると、1texel が DXTのブロックのサイズと同じになるので、fragment shaderの1pixel出力がそのままDXTの1ブロックになる.
        m_tex = device->CreateTexture(
            width / 4, height / 4,
            1,
            izanagi::graph::E_GRAPH_PIXEL_FMT_RGBA32UI,
            izanagi::graph::E_GRAPH_RSC_USAGE_STATIC);
        VRETURN(m_tex);

        CALL_GL_API(glGenFramebuffers(1, &m_fbo));

        glGenBuffers(1, &m_pbo);
        glBindBuffer(GL_PIXEL_PACK_BUFFER, m_pbo);
        glBufferData(GL_PIXEL_PACK_BUFFER, width * height, 0, GL_STREAM_COPY);
        glBindBuffer(GL_PIXEL_PACK_BUFFER, 0);

        m_texDxt = device->CreateTexture(
            width, height,
            1,
            izanagi::graph::E_GRAPH_PIXEL_FMT_DXT5,
            izanagi::graph::E_GRAPH_RSC_USAGE_STATIC);
        VRETURN(m_tex);
    }

    {
        m_allocator = allocator;

        // NOTE
        // RGBA : w * h * 4;
        // DXT5 : RGBA / 4 = (w * h * 4) / 4 = w * h
        auto size = width * height;
        m_pixels = ALLOC_ZERO(m_allocator, size);
    }

    return IZ_TRUE;
}
Esempio n. 8
0
File: PLC.c Progetto: sherief/opus
static inline void silk_PLC_conceal(
    silk_decoder_state                  *psDec,             /* I/O Decoder state        */
    silk_decoder_control                *psDecCtrl,         /* I/O Decoder control      */
    opus_int16                          frame[]             /* O LPC residual signal    */
)
{
    opus_int   i, j, k;
    opus_int   lag, idx, sLTP_buf_idx, shift1, shift2;
    opus_int32 rand_seed, harm_Gain_Q15, rand_Gain_Q15, inv_gain_Q30;
    opus_int32 energy1, energy2, *rand_ptr, *pred_lag_ptr;
    opus_int32 LPC_pred_Q10, LTP_pred_Q12;
    opus_int16 rand_scale_Q14;
    opus_int16 *B_Q14, *exc_buf_ptr;
    opus_int32 *sLPC_Q14_ptr;
    VARDECL( opus_int16, exc_buf );
    opus_int16 A_Q12[ MAX_LPC_ORDER ];
    VARDECL( opus_int16, sLTP );
    VARDECL( opus_int32, sLTP_Q14 );
    silk_PLC_struct *psPLC = &psDec->sPLC;
    opus_int32 prevGain_Q10[2];
    SAVE_STACK;

    ALLOC( exc_buf, 2*psPLC->subfr_length, opus_int16 );
    ALLOC( sLTP, psDec->ltp_mem_length, opus_int16 );
    ALLOC( sLTP_Q14, psDec->ltp_mem_length + psDec->frame_length, opus_int32 );

    prevGain_Q10[0] = silk_RSHIFT( psPLC->prevGain_Q16[ 0 ], 6);
    prevGain_Q10[1] = silk_RSHIFT( psPLC->prevGain_Q16[ 1 ], 6);

    if( psDec->first_frame_after_reset ) {
       silk_memset( psPLC->prevLPC_Q12, 0, sizeof( psPLC->prevLPC_Q12 ) );
    }

    /* Find random noise component */
    /* Scale previous excitation signal */
    exc_buf_ptr = exc_buf;
    for( k = 0; k < 2; k++ ) {
        for( i = 0; i < psPLC->subfr_length; i++ ) {
            exc_buf_ptr[ i ] = (opus_int16)silk_SAT16( silk_RSHIFT(
                silk_SMULWW( psDec->exc_Q14[ i + ( k + psPLC->nb_subfr - 2 ) * psPLC->subfr_length ], prevGain_Q10[ k ] ), 8 ) );
        }
        exc_buf_ptr += psPLC->subfr_length;
    }
    /* Find the subframe with lowest energy of the last two and use that as random noise generator */
    silk_sum_sqr_shift( &energy1, &shift1, exc_buf,                         psPLC->subfr_length );
    silk_sum_sqr_shift( &energy2, &shift2, &exc_buf[ psPLC->subfr_length ], psPLC->subfr_length );

    if( silk_RSHIFT( energy1, shift2 ) < silk_RSHIFT( energy2, shift1 ) ) {
        /* First sub-frame has lowest energy */
        rand_ptr = &psDec->exc_Q14[ silk_max_int( 0, ( psPLC->nb_subfr - 1 ) * psPLC->subfr_length - RAND_BUF_SIZE ) ];
    } else {
        /* Second sub-frame has lowest energy */
        rand_ptr = &psDec->exc_Q14[ silk_max_int( 0, psPLC->nb_subfr * psPLC->subfr_length - RAND_BUF_SIZE ) ];
    }

    /* Set up Gain to random noise component */
    B_Q14          = psPLC->LTPCoef_Q14;
    rand_scale_Q14 = psPLC->randScale_Q14;

    /* Set up attenuation gains */
    harm_Gain_Q15 = HARM_ATT_Q15[ silk_min_int( NB_ATT - 1, psDec->lossCnt ) ];
    if( psDec->prevSignalType == TYPE_VOICED ) {
        rand_Gain_Q15 = PLC_RAND_ATTENUATE_V_Q15[  silk_min_int( NB_ATT - 1, psDec->lossCnt ) ];
    } else {
        rand_Gain_Q15 = PLC_RAND_ATTENUATE_UV_Q15[ silk_min_int( NB_ATT - 1, psDec->lossCnt ) ];
    }

    /* LPC concealment. Apply BWE to previous LPC */
    silk_bwexpander( psPLC->prevLPC_Q12, psDec->LPC_order, SILK_FIX_CONST( BWE_COEF, 16 ) );

    /* Preload LPC coeficients to array on stack. Gives small performance gain */
    silk_memcpy( A_Q12, psPLC->prevLPC_Q12, psDec->LPC_order * sizeof( opus_int16 ) );

    /* First Lost frame */
    if( psDec->lossCnt == 0 ) {
        rand_scale_Q14 = 1 << 14;

        /* Reduce random noise Gain for voiced frames */
        if( psDec->prevSignalType == TYPE_VOICED ) {
            for( i = 0; i < LTP_ORDER; i++ ) {
                rand_scale_Q14 -= B_Q14[ i ];
            }
            rand_scale_Q14 = silk_max_16( 3277, rand_scale_Q14 ); /* 0.2 */
            rand_scale_Q14 = (opus_int16)silk_RSHIFT( silk_SMULBB( rand_scale_Q14, psPLC->prevLTP_scale_Q14 ), 14 );
        } else {
            /* Reduce random noise for unvoiced frames with high LPC gain */
            opus_int32 invGain_Q30, down_scale_Q30;

            invGain_Q30 = silk_LPC_inverse_pred_gain( psPLC->prevLPC_Q12, psDec->LPC_order );

            down_scale_Q30 = silk_min_32( silk_RSHIFT( (opus_int32)1 << 30, LOG2_INV_LPC_GAIN_HIGH_THRES ), invGain_Q30 );
            down_scale_Q30 = silk_max_32( silk_RSHIFT( (opus_int32)1 << 30, LOG2_INV_LPC_GAIN_LOW_THRES ), down_scale_Q30 );
            down_scale_Q30 = silk_LSHIFT( down_scale_Q30, LOG2_INV_LPC_GAIN_HIGH_THRES );

            rand_Gain_Q15 = silk_RSHIFT( silk_SMULWB( down_scale_Q30, rand_Gain_Q15 ), 14 );
        }
    }

    rand_seed    = psPLC->rand_seed;
    lag          = silk_RSHIFT_ROUND( psPLC->pitchL_Q8, 8 );
    sLTP_buf_idx = psDec->ltp_mem_length;

    /* Rewhiten LTP state */
    idx = psDec->ltp_mem_length - lag - psDec->LPC_order - LTP_ORDER / 2;
    silk_assert( idx > 0 );
    silk_LPC_analysis_filter( &sLTP[ idx ], &psDec->outBuf[ idx ], A_Q12, psDec->ltp_mem_length - idx, psDec->LPC_order );
    /* Scale LTP state */
    inv_gain_Q30 = silk_INVERSE32_varQ( psPLC->prevGain_Q16[ 1 ], 46 );
    inv_gain_Q30 = silk_min( inv_gain_Q30, silk_int32_MAX >> 1 );
    for( i = idx + psDec->LPC_order; i < psDec->ltp_mem_length; i++ ) {
        sLTP_Q14[ i ] = silk_SMULWB( inv_gain_Q30, sLTP[ i ] );
    }

    /***************************/
    /* LTP synthesis filtering */
    /***************************/
    for( k = 0; k < psDec->nb_subfr; k++ ) {
        /* Set up pointer */
        pred_lag_ptr = &sLTP_Q14[ sLTP_buf_idx - lag + LTP_ORDER / 2 ];
        for( i = 0; i < psDec->subfr_length; i++ ) {
            /* Unrolled loop */
            /* Avoids introducing a bias because silk_SMLAWB() always rounds to -inf */
            LTP_pred_Q12 = 2;
            LTP_pred_Q12 = silk_SMLAWB( LTP_pred_Q12, pred_lag_ptr[  0 ], B_Q14[ 0 ] );
            LTP_pred_Q12 = silk_SMLAWB( LTP_pred_Q12, pred_lag_ptr[ -1 ], B_Q14[ 1 ] );
            LTP_pred_Q12 = silk_SMLAWB( LTP_pred_Q12, pred_lag_ptr[ -2 ], B_Q14[ 2 ] );
            LTP_pred_Q12 = silk_SMLAWB( LTP_pred_Q12, pred_lag_ptr[ -3 ], B_Q14[ 3 ] );
            LTP_pred_Q12 = silk_SMLAWB( LTP_pred_Q12, pred_lag_ptr[ -4 ], B_Q14[ 4 ] );
            pred_lag_ptr++;

            /* Generate LPC excitation */
            rand_seed = silk_RAND( rand_seed );
            idx = silk_RSHIFT( rand_seed, 25 ) & RAND_BUF_MASK;
            sLTP_Q14[ sLTP_buf_idx ] = silk_LSHIFT32( silk_SMLAWB( LTP_pred_Q12, rand_ptr[ idx ], rand_scale_Q14 ), 2 );
            sLTP_buf_idx++;
        }

        /* Gradually reduce LTP gain */
        for( j = 0; j < LTP_ORDER; j++ ) {
            B_Q14[ j ] = silk_RSHIFT( silk_SMULBB( harm_Gain_Q15, B_Q14[ j ] ), 15 );
        }
        /* Gradually reduce excitation gain */
        rand_scale_Q14 = silk_RSHIFT( silk_SMULBB( rand_scale_Q14, rand_Gain_Q15 ), 15 );

        /* Slowly increase pitch lag */
        psPLC->pitchL_Q8 = silk_SMLAWB( psPLC->pitchL_Q8, psPLC->pitchL_Q8, PITCH_DRIFT_FAC_Q16 );
        psPLC->pitchL_Q8 = silk_min_32( psPLC->pitchL_Q8, silk_LSHIFT( silk_SMULBB( MAX_PITCH_LAG_MS, psDec->fs_kHz ), 8 ) );
        lag = silk_RSHIFT_ROUND( psPLC->pitchL_Q8, 8 );
    }

    /***************************/
    /* LPC synthesis filtering */
    /***************************/
    sLPC_Q14_ptr = &sLTP_Q14[ psDec->ltp_mem_length - MAX_LPC_ORDER ];

    /* Copy LPC state */
    silk_memcpy( sLPC_Q14_ptr, psDec->sLPC_Q14_buf, MAX_LPC_ORDER * sizeof( opus_int32 ) );

    silk_assert( psDec->LPC_order >= 10 ); /* check that unrolling works */
    for( i = 0; i < psDec->frame_length; i++ ) {
        /* partly unrolled */
        /* Avoids introducing a bias because silk_SMLAWB() always rounds to -inf */
        LPC_pred_Q10 = silk_RSHIFT( psDec->LPC_order, 1 );
        LPC_pred_Q10 = silk_SMLAWB( LPC_pred_Q10, sLPC_Q14_ptr[ MAX_LPC_ORDER + i -  1 ], A_Q12[ 0 ] );
        LPC_pred_Q10 = silk_SMLAWB( LPC_pred_Q10, sLPC_Q14_ptr[ MAX_LPC_ORDER + i -  2 ], A_Q12[ 1 ] );
        LPC_pred_Q10 = silk_SMLAWB( LPC_pred_Q10, sLPC_Q14_ptr[ MAX_LPC_ORDER + i -  3 ], A_Q12[ 2 ] );
        LPC_pred_Q10 = silk_SMLAWB( LPC_pred_Q10, sLPC_Q14_ptr[ MAX_LPC_ORDER + i -  4 ], A_Q12[ 3 ] );
        LPC_pred_Q10 = silk_SMLAWB( LPC_pred_Q10, sLPC_Q14_ptr[ MAX_LPC_ORDER + i -  5 ], A_Q12[ 4 ] );
        LPC_pred_Q10 = silk_SMLAWB( LPC_pred_Q10, sLPC_Q14_ptr[ MAX_LPC_ORDER + i -  6 ], A_Q12[ 5 ] );
        LPC_pred_Q10 = silk_SMLAWB( LPC_pred_Q10, sLPC_Q14_ptr[ MAX_LPC_ORDER + i -  7 ], A_Q12[ 6 ] );
        LPC_pred_Q10 = silk_SMLAWB( LPC_pred_Q10, sLPC_Q14_ptr[ MAX_LPC_ORDER + i -  8 ], A_Q12[ 7 ] );
        LPC_pred_Q10 = silk_SMLAWB( LPC_pred_Q10, sLPC_Q14_ptr[ MAX_LPC_ORDER + i -  9 ], A_Q12[ 8 ] );
        LPC_pred_Q10 = silk_SMLAWB( LPC_pred_Q10, sLPC_Q14_ptr[ MAX_LPC_ORDER + i - 10 ], A_Q12[ 9 ] );
        for( j = 10; j < psDec->LPC_order; j++ ) {
            LPC_pred_Q10 = silk_SMLAWB( LPC_pred_Q10, sLPC_Q14_ptr[ MAX_LPC_ORDER + i - j - 1 ], A_Q12[ j ] );
        }

        /* Add prediction to LPC excitation */
        sLPC_Q14_ptr[ MAX_LPC_ORDER + i ] = silk_ADD_LSHIFT32( sLPC_Q14_ptr[ MAX_LPC_ORDER + i ], LPC_pred_Q10, 4 );

        /* Scale with Gain */
        frame[ i ] = (opus_int16)silk_SAT16( silk_SAT16( silk_RSHIFT_ROUND( silk_SMULWW( sLPC_Q14_ptr[ MAX_LPC_ORDER + i ], prevGain_Q10[ 1 ] ), 8 ) ) );
    }

    /* Save LPC state */
    silk_memcpy( psDec->sLPC_Q14_buf, &sLPC_Q14_ptr[ psDec->frame_length ], MAX_LPC_ORDER * sizeof( opus_int32 ) );

    /**************************************/
    /* Update states                      */
    /**************************************/
    psPLC->rand_seed     = rand_seed;
    psPLC->randScale_Q14 = rand_scale_Q14;
    for( i = 0; i < MAX_NB_SUBFR; i++ ) {
        psDecCtrl->pitchL[ i ] = lag;
    }
    RESTORE_STACK;
}
Esempio n. 9
0
/*
 * Slightly modified version of authdessec_create which takes the public key
 * of the server principal as an argument. This spares us a call to
 * getpublickey() which in the nameserver context can cause a deadlock.
 */
AUTH *
authdes_pk_seccreate(const char *servername, netobj *pkey, u_int window,
	const char *timehost, const des_block *ckey, nis_server *srvr)
{
	AUTH *auth;
	struct ad_private *ad;
	char namebuf[MAXNETNAMELEN+1];

	/*
	 * Allocate everything now
	 */
	auth = ALLOC(AUTH);
	if (auth == NULL) {
		syslog(LOG_ERR, "authdes_pk_seccreate: out of memory");
		return (NULL);
	}
	ad = ALLOC(struct ad_private);
	if (ad == NULL) {
		syslog(LOG_ERR, "authdes_pk_seccreate: out of memory");
		goto failed;
	}
	ad->ad_fullname = ad->ad_servername = NULL; /* Sanity reasons */
	ad->ad_timehost = NULL;
	ad->ad_netid = NULL;
	ad->ad_uaddr = NULL;
	ad->ad_nis_srvr = NULL;
	ad->ad_timediff.tv_sec = 0;
	ad->ad_timediff.tv_usec = 0;
	memcpy(ad->ad_pkey, pkey->n_bytes, pkey->n_len);
	if (!getnetname(namebuf))
		goto failed;
	ad->ad_fullnamelen = RNDUP((u_int) strlen(namebuf));
	ad->ad_fullname = (char *)mem_alloc(ad->ad_fullnamelen + 1);
	ad->ad_servernamelen = strlen(servername);
	ad->ad_servername = (char *)mem_alloc(ad->ad_servernamelen + 1);

	if (ad->ad_fullname == NULL || ad->ad_servername == NULL) {
		syslog(LOG_ERR, "authdes_seccreate: out of memory");
		goto failed;
	}
	if (timehost != NULL) {
		ad->ad_timehost = (char *)mem_alloc(strlen(timehost) + 1);
		if (ad->ad_timehost == NULL) {
			syslog(LOG_ERR, "authdes_seccreate: out of memory");
			goto failed;
		}
		memcpy(ad->ad_timehost, timehost, strlen(timehost) + 1);
		ad->ad_dosync = TRUE;
	} else if (srvr != NULL) {
		ad->ad_nis_srvr = srvr;	/* transient */
		ad->ad_dosync = TRUE;
	} else {
		ad->ad_dosync = FALSE;
	}
	memcpy(ad->ad_fullname, namebuf, ad->ad_fullnamelen + 1);
	memcpy(ad->ad_servername, servername, ad->ad_servernamelen + 1);
	ad->ad_window = window;
	if (ckey == NULL) {
		if (key_gendes(&auth->ah_key) < 0) {
			syslog(LOG_ERR,
	    "authdes_seccreate: keyserv(1m) is unable to generate session key");
			goto failed;
		}
	} else {
		auth->ah_key = *ckey;
	}

	/*
	 * Set up auth handle
	 */
	auth->ah_cred.oa_flavor = AUTH_DES;
	auth->ah_verf.oa_flavor = AUTH_DES;
	auth->ah_ops = authdes_ops();
	auth->ah_private = (caddr_t)ad;

	if (!authdes_refresh(auth, NULL)) {
		goto failed;
	}
	ad->ad_nis_srvr = NULL; /* not needed any longer */
	return (auth);

failed:
	if (auth)
		FREE(auth, sizeof (AUTH));
	if (ad) {
		if (ad->ad_fullname)
			FREE(ad->ad_fullname, ad->ad_fullnamelen + 1);
		if (ad->ad_servername)
			FREE(ad->ad_servername, ad->ad_servernamelen + 1);
		if (ad->ad_timehost)
			FREE(ad->ad_timehost, strlen(ad->ad_timehost) + 1);
		if (ad->ad_netid)
			FREE(ad->ad_netid, strlen(ad->ad_netid) + 1);
		if (ad->ad_uaddr)
			FREE(ad->ad_uaddr, strlen(ad->ad_uaddr) + 1);
		FREE(ad, sizeof (struct ad_private));
	}
	return (NULL);
}
Esempio n. 10
0
static int
nfsx_init(mntfs *mf)
{
	/*
	 * mf_info has the form:
	 *   host:/prefix/path,sub,sub,sub
	 */
	int i;
	int glob_error;
	struct nfsx *nx;
	int asked_for_wakeup = 0;

	nx = (struct nfsx *) mf->mf_private;

	if (nx == 0) {
		char **ivec;
		char *info = 0;
		char *host;
		char *pref;
		int error = 0;

		info = strdup(mf->mf_info);
		host = strchr(info, ':');
		if (!host) {
			error = EINVAL;
			goto errexit;
		}

		pref = host+1;
		host = info;

		/*
		 * Split the prefix off from the suffices
		 */
		ivec = strsplit(pref, ',', '\'');

		/*
		 * Count array size
		 */
		for (i = 0; ivec[i]; i++)
			;

		nx = ALLOC(nfsx);
		mf->mf_private = nx;
		mf->mf_prfree = nfsx_prfree;

		nx->nx_c = i - 1;	/* i-1 because we don't want the prefix */
		nx->nx_v = xreallocarray(NULL, nx->nx_c, sizeof *nx->nx_v);
		{ char *mp = 0;
		  char *xinfo = 0;
		  char *fs = mf->mf_fo->opt_fs;
		  char *rfs = 0;
		  for (i = 0; i < nx->nx_c; i++) {
			char *path = ivec[i+1];
			rfs = str3cat(rfs, pref, "/", path);
			/*
			 * Determine the mount point.
			 * If this is the root, then don't remove
			 * the trailing slash to avoid mntfs name clashes.
			 */
			mp = str3cat(mp, fs, "/", rfs);
			normalize_slash(mp);
			deslashify(mp);
			/*
			 * Determine the mount info
			 */
			xinfo = str3cat(xinfo, host, *path == '/' ? "" : "/", path);
			normalize_slash(xinfo);
			if (pref[1] != '\0')
				deslashify(xinfo);
#ifdef DEBUG
			dlog("nfsx: init mount for %s on %s", xinfo, mp);
#endif
			nx->nx_v[i].n_error = -1;
			nx->nx_v[i].n_mnt = find_mntfs(&nfs_ops, mf->mf_fo, mp, xinfo, "", mf->mf_mopts, mf->mf_remopts);
		  }
		  free(rfs);
		  free(mp);
		  free(xinfo);
		}

		free(ivec);
errexit:
		free(info);
		if (error)
			return error;
	}

	/*
	 * Iterate through the mntfs's and call
	 * the underlying init routine on each
	 */
	glob_error = 0;
	for (i = 0; i < nx->nx_c; i++) {
		nfsx_mnt *n = &nx->nx_v[i];
		mntfs *m = n->n_mnt;
		int error = (*m->mf_ops->fs_init)(m);
		/*
		 * If HARD_NFSX_ERRORS is defined, make any
		 * initialisation failure a hard error and
		 * fail the entire group.  Otherwise only fail
		 * if none of the group is mountable (see nfsx_fmount).
		 */
#ifdef HARD_NFSX_ERRORS
		if (error > 0)
			return error;
#else
		if (error > 0)
			n->n_error = error;
#endif
		else if (error < 0) {
			glob_error = -1;
			if (!asked_for_wakeup) {
				asked_for_wakeup = 1;
				sched_task(wakeup_task, mf, m);
			}
		}
	}

	return glob_error;
}
Esempio n. 11
0
BICAPI  BOOLEAN  singular_value_decomposition(
    int    m,
    int    n,
    Real   **a,
    Real   w[],
    Real   **v )
{
  
  int i,j;
  BOOLEAN val;
  char jobu = 'O';
  char jobvt = 'A';
  long int _m = (long int) m;
  long int _n = (long int) n;

  long int lda = _m;  
  long int ldu = _m;
  long int ldvt = _n;
  long int lwork = MAX(3*MIN(_m,_n)+MAX(_m,_n),5*MIN(_m,_n));
  Real** _a;
  Real* work;
  Real** _u;
  Real** _v;
  long int info;
  Real temp;

  ALLOC(work,(int) lwork);
  ALLOC2D(_a,n,m);
  ALLOC2D(_u,n,m);
  ALLOC2D(_v,n,n);

  for (j = 0; j < n; j++) {    
    for (i = 0; i < m; i++) {
      _a[j][i] = a[i][j];
    }
  }
  

  val = bicpl_dgesvd_(&jobu, &jobvt, &_m, &_n, (Real*) *_a, &lda, (Real*) w, 
		(Real*) *_u, &ldu, (Real*) *_v, &ldvt, 
		(Real*) work, &lwork, &info);
      
  for (j = 0; j < n; j++) {    
    for (i = 0; i < m; i++) {
      a[i][j] = _a[j][i];
    }
  }

  for (j = 0; j < n; j++) {    
    for (i = 0; i < n; i++) {
      v[i][j] = _v[i][j];
    }
  }

  FREE(work);
  FREE2D(_u);
  FREE2D(_v);
  FREE2D(_a);
  
  return val;  
}
Esempio n. 12
0
/*
 * call-seq:
 *     DescriptorPool.new => pool
 *
 * Creates a new, empty, descriptor pool.
 */
VALUE DescriptorPool_alloc(VALUE klass) {
  DescriptorPool* self = ALLOC(DescriptorPool);
  self->symtab = upb_symtab_new(&self->symtab);
  return TypedData_Wrap_Struct(klass, &_DescriptorPool_type, self);
}
Esempio n. 13
0
extern int ZEXPORT zipOpenNewFileInZip (zipFile file, const char* filename, const zip_fileinfo* zipfi, 
                                        const void* extrafield_local, uInt size_extrafield_local,
                                        const void* extrafield_global, uInt size_extrafield_global,
                                        const char* comment, int method, int level)
{
    zip_internal* zi;
    uInt size_filename;
    uInt size_comment;
    uInt i;
    int err = ZIP_OK;

    if (file == NULL)
        return ZIP_PARAMERROR;
    if ((method!=0) && (method!=Z_DEFLATED))
        return ZIP_PARAMERROR;

    zi = (zip_internal*)file;

    if (zi->in_opened_file_inzip == 1)
    {
        err = zipCloseFileInZip (file);
        if (err != ZIP_OK)
            return err;
    }


    if (filename==NULL)
        filename="-";

    if (comment==NULL)
        size_comment = 0;
    else
        size_comment = strlen(comment);

    size_filename = strlen(filename);

    if (zipfi == NULL)
        zi->ci.dosDate = 0;
    else
    {
        if (zipfi->dosDate != 0)
            zi->ci.dosDate = zipfi->dosDate;
        else zi->ci.dosDate = ziplocal_TmzDateToDosDate(&zipfi->tmz_date,zipfi->dosDate);
    }

    zi->ci.flag = 0;
    if ((level==8) || (level==9))
      zi->ci.flag |= 2;
    if ((level==2))
      zi->ci.flag |= 4;
    if ((level==1))
      zi->ci.flag |= 6;

    zi->ci.crc32 = 0;
    zi->ci.method = method;
    zi->ci.stream_initialised = 0;
    zi->ci.pos_in_buffered_data = 0;
    zi->ci.pos_local_header = ftell(zi->filezip);
    zi->ci.size_centralheader = SIZECENTRALHEADER + size_filename + 
                                      size_extrafield_global + size_comment;
    zi->ci.central_header = (char*)ALLOC((uInt)zi->ci.size_centralheader);

    ziplocal_putValue_inmemory(zi->ci.central_header,(uLong)CENTRALHEADERMAGIC,4);
    /* version info */
    ziplocal_putValue_inmemory(zi->ci.central_header+4,(uLong)VERSIONMADEBY,2);
    ziplocal_putValue_inmemory(zi->ci.central_header+6,(uLong)20,2);
    ziplocal_putValue_inmemory(zi->ci.central_header+8,(uLong)zi->ci.flag,2);
    ziplocal_putValue_inmemory(zi->ci.central_header+10,(uLong)zi->ci.method,2);
    ziplocal_putValue_inmemory(zi->ci.central_header+12,(uLong)zi->ci.dosDate,4);
    ziplocal_putValue_inmemory(zi->ci.central_header+16,(uLong)0,4); /*crc*/
    ziplocal_putValue_inmemory(zi->ci.central_header+20,(uLong)0,4); /*compr size*/
    ziplocal_putValue_inmemory(zi->ci.central_header+24,(uLong)0,4); /*uncompr size*/
    ziplocal_putValue_inmemory(zi->ci.central_header+28,(uLong)size_filename,2);
    ziplocal_putValue_inmemory(zi->ci.central_header+30,(uLong)size_extrafield_global,2);
    ziplocal_putValue_inmemory(zi->ci.central_header+32,(uLong)size_comment,2);
    ziplocal_putValue_inmemory(zi->ci.central_header+34,(uLong)0,2); /*disk nm start*/

    if (zipfi==NULL)
        ziplocal_putValue_inmemory(zi->ci.central_header+36,(uLong)0,2); 
    else
        ziplocal_putValue_inmemory(zi->ci.central_header+36,(uLong)zipfi->internal_fa,2); 

    if (zipfi==NULL)
        ziplocal_putValue_inmemory(zi->ci.central_header+38,(uLong)0,4); 
    else
        ziplocal_putValue_inmemory(zi->ci.central_header+38,(uLong)zipfi->external_fa,4);

    ziplocal_putValue_inmemory(zi->ci.central_header+42,(uLong)zi->ci.pos_local_header,4);

    for (i=0;i<size_filename;i++)
        *(zi->ci.central_header+SIZECENTRALHEADER+i) = *(filename+i);

    for (i=0;i<size_extrafield_global;i++)
        *(zi->ci.central_header+SIZECENTRALHEADER+size_filename+i) =
              *(((const char*)extrafield_global)+i);

    for (i=0;i<size_comment;i++)
        *(zi->ci.central_header+SIZECENTRALHEADER+size_filename+
              size_extrafield_global+i) = *(comment+i);
    if (zi->ci.central_header == NULL)
        return ZIP_INTERNALERROR;

    /* write the local header */
    err = ziplocal_putValue(zi->filezip,(uLong)LOCALHEADERMAGIC,4);

    if (err==ZIP_OK)
        err = ziplocal_putValue(zi->filezip,(uLong)20,2);/* version needed to extract */
    if (err==ZIP_OK)
        err = ziplocal_putValue(zi->filezip,(uLong)zi->ci.flag,2);

    if (err==ZIP_OK)
        err = ziplocal_putValue(zi->filezip,(uLong)zi->ci.method,2);

    if (err==ZIP_OK)
        err = ziplocal_putValue(zi->filezip,(uLong)zi->ci.dosDate,4);

    if (err==ZIP_OK)
        err = ziplocal_putValue(zi->filezip,(uLong)0,4); /* crc 32, unknown */
    if (err==ZIP_OK)
        err = ziplocal_putValue(zi->filezip,(uLong)0,4); /* compressed size, unknown */
    if (err==ZIP_OK)
        err = ziplocal_putValue(zi->filezip,(uLong)0,4); /* uncompressed size, unknown */

    if (err==ZIP_OK)
        err = ziplocal_putValue(zi->filezip,(uLong)size_filename,2);

    if (err==ZIP_OK)
        err = ziplocal_putValue(zi->filezip,(uLong)size_extrafield_local,2);

    if ((err==ZIP_OK) && (size_filename>0))
        if (fwrite(filename,(uInt)size_filename,1,zi->filezip)!=1)
                err = ZIP_ERRNO;

    if ((err==ZIP_OK) && (size_extrafield_local>0))
        if (fwrite(extrafield_local,(uInt)size_extrafield_local,1,zi->filezip)
                                                                           !=1)
                err = ZIP_ERRNO;

    zi->ci.stream.avail_in = (uInt)0;
    zi->ci.stream.avail_out = (uInt)Z_BUFSIZE;
    zi->ci.stream.next_out = zi->ci.buffered_data;
    zi->ci.stream.total_in = 0;
    zi->ci.stream.total_out = 0;

    if ((err==ZIP_OK) && (zi->ci.method == Z_DEFLATED))
    {
        zi->ci.stream.zalloc = (alloc_func)0;
        zi->ci.stream.zfree = (free_func)0;
        zi->ci.stream.opaque = (voidpf)0;

        err = deflateInit2(&zi->ci.stream, level,
               Z_DEFLATED, -MAX_WBITS, DEF_MEM_LEVEL, 0);

        if (err==Z_OK)
            zi->ci.stream_initialised = 1;
    }


    if (err==Z_OK)
        zi->in_opened_file_inzip = 1;
    return err;
}
Esempio n. 14
0
static inline
unsigned char *advance(unsigned char *pc)
{
  if (SEND(pc)) {
    int count = 3;
		
    if (VAL_IS_FLOAT(SEND_ARG1(pc)))
      count += sizeof(meld_float);
    else if (VAL_IS_INT(SEND_ARG1(pc)))
      count += sizeof(meld_int);
    else if (VAL_IS_FIELD(SEND_ARG1(pc)))
      count += 2;
    else if (VAL_IS_REVERSE(SEND_ARG1(pc)))
      count += 2;
    else {
      assert(0);
      exit(1);
    }

    return pc+count;
  }
  else if(OP(pc)) {
    int count = 3;

    /* check v1 */
    if (VAL_IS_FLOAT(OP_ARG1(pc)))
      count += sizeof(meld_float);
    else if (VAL_IS_INT(OP_ARG1(pc)))
      count += sizeof(meld_int);
    else if (VAL_IS_FIELD(OP_ARG1(pc)))
      count += 2;
    else if (VAL_IS_REVERSE(OP_ARG1(pc)))
      count += 2;
    else if (VAL_IS_REG(OP_ARG1(pc)))
      {} /* do nothing */
    else {
      assert(0);
      exit(1);
    }
			
    /* check v2 */
    if (VAL_IS_FLOAT(OP_ARG2(pc)))
      count += sizeof(meld_float);
    else if (VAL_IS_INT(OP_ARG2(pc)))
      count += sizeof(meld_int);
    else if (VAL_IS_FIELD(OP_ARG2(pc)))
      count += 2;
    else if (VAL_IS_REVERSE(OP_ARG2(pc)))
      count += 2;
    else if (VAL_IS_REG(OP_ARG2(pc)))
      {} /* do nothing */
    else {
      printf("got value %c\n", OP_ARG2(pc));
      assert(0);
      exit(1);
    }

    return pc+count;
  }
  else if(MOVE(pc)) {
    int count = 2;
		
    /* move src */
    if (VAL_IS_FLOAT(MOVE_SRC(pc)))
      count += sizeof(meld_float);
    else if (VAL_IS_INT(MOVE_SRC(pc)))
      count += sizeof(meld_int);
    else if (VAL_IS_FIELD(MOVE_SRC(pc)))
      count += 2;
    else if (VAL_IS_REVERSE(MOVE_SRC(pc)))
      count += 2;
    else if (VAL_IS_TUPLE(MOVE_SRC(pc)))
      {} /* nothing */
    else if(VAL_IS_REG(MOVE_SRC(pc)))
      {} /* nothing */
    else if(VAL_IS_HOST(MOVE_SRC(pc)))
      {} /* nothing */
    else {
      assert(0);
      exit(1);
    }
  		
    /* move dst */
    if (VAL_IS_FLOAT(MOVE_DST(pc)))
      count += sizeof(meld_float);
    else if (VAL_IS_INT(MOVE_DST(pc)))
      count += sizeof(meld_int);
    else if (VAL_IS_FIELD(MOVE_DST(pc)))
      count += 2;
    else if (VAL_IS_REVERSE(MOVE_DST(pc)))
      count += 2;
    else if (VAL_IS_REG(MOVE_DST(pc)))
      {} /* nothing */
    else {
      assert(0);
      exit(1);
    }

    return pc+count;
  }
  else if(ITER(pc)) {
    
    pc += ITER_BASE;
    
    if(ITER_MATCH_NONE(pc))
      pc += 2;
    else {
      unsigned char *old;
      while(1) {
        old = pc;

	if (VAL_IS_FLOAT(ITER_MATCH_VAL(pc)))
	  pc += sizeof(meld_float);
	else if (VAL_IS_INT(ITER_MATCH_VAL(pc)))
	  pc += sizeof(meld_int);
	else if (VAL_IS_FIELD(ITER_MATCH_VAL(pc)))
	  pc += 2;
	else if (VAL_IS_REVERSE(ITER_MATCH_VAL(pc)))
	  pc += 2;
	else {
	  assert(0);
	  exit(1);
	}

        pc += 2;

        if(ITER_MATCH_END(old))
          break;
      }
    }

    return pc;
  } else if (ALLOC(pc)) {
    int count = 2;

    if (VAL_IS_INT(ALLOC_DST(pc)))
      count += sizeof(meld_int);
    else if	(VAL_IS_FLOAT(ALLOC_DST(pc)))
      count += sizeof(meld_float);
    else if (VAL_IS_FIELD(ALLOC_DST(pc)))
      count += 2;
    else if (VAL_IS_REG(ALLOC_DST(pc)))
      {} /* nothing */
    else if (VAL_IS_REVERSE(ALLOC_DST(pc))) {
      count += 2;
      assert(0);
      exit(1);
    } else {
      assert(0);
      exit(1);
    }

    return pc+count;
  }
  else if (CALL(pc)) {
    int numArgs = CALL_ARGS(pc);
    int i;
		
    for (i = 0, pc+=2; i < numArgs; i++, pc++) {
      if (VAL_IS_FLOAT(CALL_VAL(pc)))
        pc += sizeof(meld_float);
      else if (VAL_IS_INT(CALL_VAL(pc)))
	pc += sizeof(meld_int);
      else if (VAL_IS_FIELD(CALL_VAL(pc)))
	pc += 2;
      else if (VAL_IS_REVERSE(CALL_VAL(pc))) {
	pc += 2;
	assert(0);
	exit(1);
      }
    }
    return pc;
  }
  else if (IF(pc)) {
    return pc+IF_BASE;
  }
  else {
    return pc+1;
  }
}
Esempio n. 15
0
/* Encode quantization indices of excitation */
void silk_encode_pulses(
    ec_enc                      *psRangeEnc,                    /* I/O  compressor data structure                   */
    const opus_int              signalType,                     /* I    Signal type                                 */
    const opus_int              quantOffsetType,                /* I    quantOffsetType                             */
    opus_int8                   pulses[],                       /* I    quantization indices                        */
    const opus_int              frame_length                    /* I    Frame length                                */
)
{
    opus_int   i, k, j, iter, bit, nLS, scale_down, RateLevelIndex = 0;
    opus_int32 abs_q, minSumBits_Q5, sumBits_Q5;
    VARDECL( opus_int, abs_pulses );
    VARDECL( opus_int, sum_pulses );
    VARDECL( opus_int, nRshifts );
    opus_int   pulses_comb[ 8 ];
    opus_int   *abs_pulses_ptr;
    const opus_int8 *pulses_ptr;
    const opus_uint8 *cdf_ptr;
    const opus_uint8 *nBits_ptr;
    SAVE_STACK;

    silk_memset( pulses_comb, 0, 8 * sizeof( opus_int ) ); /* Fixing Valgrind reported problem*/

    /****************************/
    /* Prepare for shell coding */
    /****************************/
    /* Calculate number of shell blocks */
    silk_assert( 1 << LOG2_SHELL_CODEC_FRAME_LENGTH == SHELL_CODEC_FRAME_LENGTH );
    iter = silk_RSHIFT( frame_length, LOG2_SHELL_CODEC_FRAME_LENGTH );
    if( iter * SHELL_CODEC_FRAME_LENGTH < frame_length ) {
        silk_assert( frame_length == 12 * 10 ); /* Make sure only happens for 10 ms @ 12 kHz */
        iter++;
        silk_memset( &pulses[ frame_length ], 0, SHELL_CODEC_FRAME_LENGTH * sizeof(opus_int8));
    }

    /* Take the absolute value of the pulses */
    ALLOC( abs_pulses, iter * SHELL_CODEC_FRAME_LENGTH, opus_int );
    silk_assert( !( SHELL_CODEC_FRAME_LENGTH & 3 ) );
    for( i = 0; i < iter * SHELL_CODEC_FRAME_LENGTH; i+=4 ) {
        abs_pulses[i+0] = ( opus_int )silk_abs( pulses[ i + 0 ] );
        abs_pulses[i+1] = ( opus_int )silk_abs( pulses[ i + 1 ] );
        abs_pulses[i+2] = ( opus_int )silk_abs( pulses[ i + 2 ] );
        abs_pulses[i+3] = ( opus_int )silk_abs( pulses[ i + 3 ] );
    }

    /* Calc sum pulses per shell code frame */
    ALLOC( sum_pulses, iter, opus_int );
    ALLOC( nRshifts, iter, opus_int );
    abs_pulses_ptr = abs_pulses;
    for( i = 0; i < iter; i++ ) {
        nRshifts[ i ] = 0;

        while( 1 ) {
            /* 1+1 -> 2 */
            scale_down = combine_and_check( pulses_comb, abs_pulses_ptr, silk_max_pulses_table[ 0 ], 8 );
            /* 2+2 -> 4 */
            scale_down += combine_and_check( pulses_comb, pulses_comb, silk_max_pulses_table[ 1 ], 4 );
            /* 4+4 -> 8 */
            scale_down += combine_and_check( pulses_comb, pulses_comb, silk_max_pulses_table[ 2 ], 2 );
            /* 8+8 -> 16 */
            scale_down += combine_and_check( &sum_pulses[ i ], pulses_comb, silk_max_pulses_table[ 3 ], 1 );

            if( scale_down ) {
                /* We need to downscale the quantization signal */
                nRshifts[ i ]++;
                for( k = 0; k < SHELL_CODEC_FRAME_LENGTH; k++ ) {
                    abs_pulses_ptr[ k ] = silk_RSHIFT( abs_pulses_ptr[ k ], 1 );
                }
            } else {
                /* Jump out of while(1) loop and go to next shell coding frame */
                break;
            }
        }
        abs_pulses_ptr += SHELL_CODEC_FRAME_LENGTH;
    }

    /**************/
    /* Rate level */
    /**************/
    /* find rate level that leads to fewest bits for coding of pulses per block info */
    minSumBits_Q5 = silk_int32_MAX;
    for( k = 0; k < N_RATE_LEVELS - 1; k++ ) {
        nBits_ptr  = silk_pulses_per_block_BITS_Q5[ k ];
        sumBits_Q5 = silk_rate_levels_BITS_Q5[ signalType >> 1 ][ k ];
        for( i = 0; i < iter; i++ ) {
            if( nRshifts[ i ] > 0 ) {
                sumBits_Q5 += nBits_ptr[ MAX_PULSES + 1 ];
            } else {
                sumBits_Q5 += nBits_ptr[ sum_pulses[ i ] ];
            }
        }
        if( sumBits_Q5 < minSumBits_Q5 ) {
            minSumBits_Q5 = sumBits_Q5;
            RateLevelIndex = k;
        }
    }
    ec_enc_icdf( psRangeEnc, RateLevelIndex, silk_rate_levels_iCDF[ signalType >> 1 ], 8 );

    /***************************************************/
    /* Sum-Weighted-Pulses Encoding                    */
    /***************************************************/
    cdf_ptr = silk_pulses_per_block_iCDF[ RateLevelIndex ];
    for( i = 0; i < iter; i++ ) {
        if( nRshifts[ i ] == 0 ) {
            ec_enc_icdf( psRangeEnc, sum_pulses[ i ], cdf_ptr, 8 );
        } else {
            ec_enc_icdf( psRangeEnc, MAX_PULSES + 1, cdf_ptr, 8 );
            for( k = 0; k < nRshifts[ i ] - 1; k++ ) {
                ec_enc_icdf( psRangeEnc, MAX_PULSES + 1, silk_pulses_per_block_iCDF[ N_RATE_LEVELS - 1 ], 8 );
            }
            ec_enc_icdf( psRangeEnc, sum_pulses[ i ], silk_pulses_per_block_iCDF[ N_RATE_LEVELS - 1 ], 8 );
        }
    }

    /******************/
    /* Shell Encoding */
    /******************/
    for( i = 0; i < iter; i++ ) {
        if( sum_pulses[ i ] > 0 ) {
            silk_shell_encoder( psRangeEnc, &abs_pulses[ i * SHELL_CODEC_FRAME_LENGTH ] );
        }
    }

    /****************/
    /* LSB Encoding */
    /****************/
    for( i = 0; i < iter; i++ ) {
        if( nRshifts[ i ] > 0 ) {
            pulses_ptr = &pulses[ i * SHELL_CODEC_FRAME_LENGTH ];
            nLS = nRshifts[ i ] - 1;
            for( k = 0; k < SHELL_CODEC_FRAME_LENGTH; k++ ) {
                abs_q = (opus_int8)silk_abs( pulses_ptr[ k ] );
                for( j = nLS; j > 0; j-- ) {
                    bit = silk_RSHIFT( abs_q, j ) & 1;
                    ec_enc_icdf( psRangeEnc, bit, silk_lsb_iCDF, 8 );
                }
                bit = abs_q & 1;
                ec_enc_icdf( psRangeEnc, bit, silk_lsb_iCDF, 8 );
            }
        }
    }

    /****************/
    /* Encode signs */
    /****************/
    silk_encode_signs( psRangeEnc, pulses, frame_length, signalType, quantOffsetType, sum_pulses );
    RESTORE_STACK;
}
Esempio n. 16
0
value_t AllocReversedList( zone_t zone, value_t listObj )
{
	struct closure *out = ALLOC( List_reverse_func, LIST_REVERSE_SLOT_COUNT );
	out->slots[LIST_REVERSE_LIST_SLOT] = listObj;
	return out;
}
Esempio n. 17
0
AUTH *
authdes_pk_create (const char *servername, netobj *pkey, u_int window,
		   struct sockaddr *syncaddr, des_block *ckey)
{
  AUTH *auth;
  struct ad_private *ad;
  char namebuf[MAXNETNAMELEN + 1];

  /*
   * Allocate everything now
   */
  auth = ALLOC (AUTH);
  ad = ALLOC (struct ad_private);

  if (auth == NULL || ad == NULL)
    {
      debug ("authdes_create: out of memory");
      goto failed;
    }

  memset (ad, 0, sizeof (struct ad_private));
  memcpy (ad->ad_pkey, pkey->n_bytes, pkey->n_len);
  if (!getnetname (namebuf))
    goto failed;
  ad->ad_fullnamelen = RNDUP (strlen (namebuf));
  ad->ad_fullname = mem_alloc (ad->ad_fullnamelen + 1);

  ad->ad_servernamelen = strlen (servername);
  ad->ad_servername = mem_alloc (ad->ad_servernamelen + 1);

  if (ad->ad_fullname == NULL || ad->ad_servername == NULL)
    {
      debug ("authdes_create: out of memory");
      goto failed;
    }

  /*
   * Set up private data
   */
  memcpy (ad->ad_fullname, namebuf, ad->ad_fullnamelen + 1);
  memcpy (ad->ad_servername, servername, ad->ad_servernamelen + 1);
  ad->ad_timediff.tv_sec = ad->ad_timediff.tv_usec = 0;
  if (syncaddr != NULL)
    {
      ad->ad_syncaddr = *syncaddr;
      ad->ad_dosync = TRUE;
    }
  else
    ad->ad_dosync = FALSE;

  ad->ad_window = window;
  if (ckey == NULL)
    {
      if (key_gendes (&auth->ah_key) < 0)
	{
	  debug ("authdes_create: unable to gen conversation key");
	  goto failed;
	}
    }
  else
    auth->ah_key = *ckey;

  /*
   * Set up auth handle
   */
  auth->ah_cred.oa_flavor = AUTH_DES;
  auth->ah_verf.oa_flavor = AUTH_DES;
  auth->ah_ops = (struct auth_ops *) &authdes_ops;
  auth->ah_private = (caddr_t) ad;

  if (!authdes_refresh (auth))
    goto failed;

  return auth;

failed:
  if (auth != NULL)
    FREE (auth, sizeof (AUTH));
  if (ad != NULL)
    {
      if (ad->ad_fullname != NULL)
	FREE (ad->ad_fullname, ad->ad_fullnamelen + 1);
      if (ad->ad_servername != NULL)
	FREE (ad->ad_servername, ad->ad_servernamelen + 1);
      FREE (ad, sizeof (struct ad_private));
    }
  return NULL;
}
Esempio n. 18
0
extern zipFile ZEXPORT zipOpen2 (
    const char *pathname,
    int append,
    zipcharpc* globalcomment,
    zlib_filefunc_def* pzlib_filefunc_def)
{
    zip_internal ziinit;
    zip_internal* zi;
    int err=ZIP_OK;


    if (pzlib_filefunc_def==NULL)
        fill_fopen_filefunc(&ziinit.z_filefunc);
    else
        ziinit.z_filefunc = *pzlib_filefunc_def;

    ziinit.filestream = (*(ziinit.z_filefunc.zopen_file))
                 (ziinit.z_filefunc.opaque,
                  pathname,
                  (append == APPEND_STATUS_CREATE) ?
                  (ZLIB_FILEFUNC_MODE_READ | ZLIB_FILEFUNC_MODE_WRITE | ZLIB_FILEFUNC_MODE_CREATE) :
                    (ZLIB_FILEFUNC_MODE_READ | ZLIB_FILEFUNC_MODE_WRITE | ZLIB_FILEFUNC_MODE_EXISTING));

    if (ziinit.filestream == NULL)
        return NULL;
    ziinit.begin_pos = ZTELL(ziinit.z_filefunc,ziinit.filestream);
    ziinit.in_opened_file_inzip = 0;
    ziinit.ci.stream_initialised = 0;
    ziinit.number_entry = 0;
    ziinit.add_position_when_writting_offset = 0;
    init_linkedlist(&(ziinit.central_dir));


    zi = (zip_internal*)ALLOC(sizeof(zip_internal));
    if (zi==NULL)
    {
        ZCLOSE(ziinit.z_filefunc,ziinit.filestream);
        return NULL;
    }

    /* now we add file in a zipfile */
#    ifndef NO_ADDFILEINEXISTINGZIP
    if (append == APPEND_STATUS_ADDINZIP)
    {
        uLong byte_before_the_zipfile;/* byte before the zipfile, (>0 for sfx)*/

        uLong size_central_dir;     /* size of the central directory  */
        uLong offset_central_dir;   /* offset of start of central directory */
        uLong central_pos,uL;

        uLong number_disk;          /* number of the current dist, used for
                                    spaning ZIP, unsupported, always 0*/
        uLong number_disk_with_CD;  /* number the the disk with central dir, used
                                    for spaning ZIP, unsupported, always 0*/
        uLong number_entry;
        uLong number_entry_CD;      /* total number of entries in
                                    the central dir
                                    (same than number_entry on nospan) */
        uLong size_comment;

        central_pos = ziplocal_SearchCentralDir(&ziinit.z_filefunc,ziinit.filestream);
        if (central_pos==0)
            err=ZIP_ERRNO;

        if (ZSEEK(ziinit.z_filefunc, ziinit.filestream,
                                        central_pos,ZLIB_FILEFUNC_SEEK_SET)!=0)
            err=ZIP_ERRNO;

        /* the signature, already checked */
        if (ziplocal_getLong(&ziinit.z_filefunc, ziinit.filestream,&uL)!=ZIP_OK)
            err=ZIP_ERRNO;

        /* number of this disk */
        if (ziplocal_getShort(&ziinit.z_filefunc, ziinit.filestream,&number_disk)!=ZIP_OK)
            err=ZIP_ERRNO;

        /* number of the disk with the start of the central directory */
        if (ziplocal_getShort(&ziinit.z_filefunc, ziinit.filestream,&number_disk_with_CD)!=ZIP_OK)
            err=ZIP_ERRNO;

        /* total number of entries in the central dir on this disk */
        if (ziplocal_getShort(&ziinit.z_filefunc, ziinit.filestream,&number_entry)!=ZIP_OK)
            err=ZIP_ERRNO;

        /* total number of entries in the central dir */
        if (ziplocal_getShort(&ziinit.z_filefunc, ziinit.filestream,&number_entry_CD)!=ZIP_OK)
            err=ZIP_ERRNO;

        if ((number_entry_CD!=number_entry) ||
            (number_disk_with_CD!=0) ||
            (number_disk!=0))
            err=ZIP_BADZIPFILE;

        /* size of the central directory */
        if (ziplocal_getLong(&ziinit.z_filefunc, ziinit.filestream,&size_central_dir)!=ZIP_OK)
            err=ZIP_ERRNO;

        /* offset of start of central directory with respect to the
            starting disk number */
        if (ziplocal_getLong(&ziinit.z_filefunc, ziinit.filestream,&offset_central_dir)!=ZIP_OK)
            err=ZIP_ERRNO;

        /* zipfile comment length */
        if (ziplocal_getShort(&ziinit.z_filefunc, ziinit.filestream,&size_comment)!=ZIP_OK)
            err=ZIP_ERRNO;

        if ((central_pos<offset_central_dir+size_central_dir) &&
            (err==ZIP_OK))
            err=ZIP_BADZIPFILE;

        if (err!=ZIP_OK)
        {
            ZCLOSE(ziinit.z_filefunc, ziinit.filestream);
            return NULL;
        }

        byte_before_the_zipfile = central_pos -
                                (offset_central_dir+size_central_dir);
        ziinit.add_position_when_writting_offset = byte_before_the_zipfile ;

        {
            uLong size_central_dir_to_read = size_central_dir;
            size_t buf_size = SIZEDATA_INDATABLOCK;
            void* buf_read = (void*)ALLOC(buf_size);
            if (ZSEEK(ziinit.z_filefunc, ziinit.filestream,
                  offset_central_dir + byte_before_the_zipfile,
                  ZLIB_FILEFUNC_SEEK_SET) != 0)
                  err=ZIP_ERRNO;

            while ((size_central_dir_to_read>0) && (err==ZIP_OK))
            {
                uLong read_this = SIZEDATA_INDATABLOCK;
                if (read_this > size_central_dir_to_read)
                    read_this = size_central_dir_to_read;
                if (ZREAD(ziinit.z_filefunc, ziinit.filestream,buf_read,read_this) != read_this)
                    err=ZIP_ERRNO;

                if (err==ZIP_OK)
                    err = add_data_in_datablock(&ziinit.central_dir,buf_read,
                                                (uLong)read_this);
                size_central_dir_to_read-=read_this;
            }
            TRYFREE(buf_read);
        }
        ziinit.begin_pos = byte_before_the_zipfile;
        ziinit.number_entry = number_entry_CD;

        if (ZSEEK(ziinit.z_filefunc, ziinit.filestream,
                  offset_central_dir+byte_before_the_zipfile,ZLIB_FILEFUNC_SEEK_SET)!=0)
            err=ZIP_ERRNO;
    }
#    endif /* !NO_ADDFILEINEXISTINGZIP*/

    if (err != ZIP_OK)
    {
        TRYFREE(zi);
        return NULL;
    }
    else
    {
        *zi = ziinit;
        return (zipFile)zi;
    }
}
Esempio n. 19
0
static krb5_error_code
init_tgs_req (krb5_context context,
	      krb5_ccache ccache,
	      krb5_addresses *addresses,
	      krb5_kdc_flags flags,
	      Ticket *second_ticket,
	      krb5_creds *in_creds,
	      krb5_creds *krbtgt,
	      unsigned nonce,
	      const METHOD_DATA *padata,
	      krb5_keyblock **subkey,
	      TGS_REQ *t,
	      krb5_key_usage usage)
{
    krb5_error_code ret = 0;

    memset(t, 0, sizeof(*t));
    t->pvno = 5;
    t->msg_type = krb_tgs_req;
    if (in_creds->session.keytype) {
	ALLOC_SEQ(&t->req_body.etype, 1);
	if(t->req_body.etype.val == NULL) {
	    ret = ENOMEM;
	    krb5_set_error_string(context, "malloc: out of memory");
	    goto fail;
	}
	t->req_body.etype.val[0] = in_creds->session.keytype;
    } else {
	ret = krb5_init_etype(context, 
			      &t->req_body.etype.len, 
			      &t->req_body.etype.val, 
			      NULL);
    }
    if (ret)
	goto fail;
    t->req_body.addresses = addresses;
    t->req_body.kdc_options = flags.b;
    ret = copy_Realm(&in_creds->server->realm, &t->req_body.realm);
    if (ret)
	goto fail;
    ALLOC(t->req_body.sname, 1);
    if (t->req_body.sname == NULL) {
	ret = ENOMEM;
	krb5_set_error_string(context, "malloc: out of memory");
	goto fail;
    }

    /* some versions of some code might require that the client be
       present in TGS-REQs, but this is clearly against the spec */

    ret = copy_PrincipalName(&in_creds->server->name, t->req_body.sname);
    if (ret)
	goto fail;

    /* req_body.till should be NULL if there is no endtime specified,
       but old MIT code (like DCE secd) doesn't like that */
    ALLOC(t->req_body.till, 1);
    if(t->req_body.till == NULL){
	ret = ENOMEM;
	krb5_set_error_string(context, "malloc: out of memory");
	goto fail;
    }
    *t->req_body.till = in_creds->times.endtime;
    
    t->req_body.nonce = nonce;
    if(second_ticket){
	ALLOC(t->req_body.additional_tickets, 1);
	if (t->req_body.additional_tickets == NULL) {
	    ret = ENOMEM;
	    krb5_set_error_string(context, "malloc: out of memory");
	    goto fail;
	}
	ALLOC_SEQ(t->req_body.additional_tickets, 1);
	if (t->req_body.additional_tickets->val == NULL) {
	    ret = ENOMEM;
	    krb5_set_error_string(context, "malloc: out of memory");
	    goto fail;
	}
	ret = copy_Ticket(second_ticket, t->req_body.additional_tickets->val); 
	if (ret)
	    goto fail;
    }
    ALLOC(t->padata, 1);
    if (t->padata == NULL) {
	ret = ENOMEM;
	krb5_set_error_string(context, "malloc: out of memory");
	goto fail;
    }
    ALLOC_SEQ(t->padata, 1 + padata->len);
    if (t->padata->val == NULL) {
	ret = ENOMEM;
	krb5_set_error_string(context, "malloc: out of memory");
	goto fail;
    }
    {
	int i;
	for (i = 0; i < padata->len; i++) {
	    ret = copy_PA_DATA(&padata->val[i], &t->padata->val[i + 1]);
	    if (ret) {
		krb5_set_error_string(context, "malloc: out of memory");
		goto fail;
	    }
	}
    }

    {
	krb5_auth_context ac;
	krb5_keyblock *key = NULL;

	ret = krb5_auth_con_init(context, &ac);
	if(ret)
	    goto fail;

	if (krb5_config_get_bool_default(context, NULL, FALSE,
					 "realms",
					 krbtgt->server->realm,
					 "tgs_require_subkey",
					 NULL))
	{
	    ret = krb5_generate_subkey (context, &krbtgt->session, &key);
	    if (ret) {
		krb5_auth_con_free (context, ac);
		goto fail;
	    }

	    ret = krb5_auth_con_setlocalsubkey(context, ac, key);
	    if (ret) {
		if (key)
		    krb5_free_keyblock (context, key);
		krb5_auth_con_free (context, ac);
		goto fail;
	    }
	}

	ret = set_auth_data (context, &t->req_body, &in_creds->authdata,
			     key ? key : &krbtgt->session);
	if (ret) {
	    if (key)
		krb5_free_keyblock (context, key);
	    krb5_auth_con_free (context, ac);
	    goto fail;
	}

	ret = make_pa_tgs_req(context,
			      ac,
			      &t->req_body, 
			      &t->padata->val[0],
			      krbtgt,
			      usage);
	if(ret) {
	    if (key)
		krb5_free_keyblock (context, key);
	    krb5_auth_con_free(context, ac);
	    goto fail;
	}
	*subkey = key;
	
	krb5_auth_con_free(context, ac);
    }
fail:
    if (ret) {
	t->req_body.addresses = NULL;
	free_TGS_REQ (t);
    }
    return ret;
}
Esempio n. 20
0
extern int ZEXPORT zipOpenNewFileInZip3 (
    zipFile file,
    const char* filename,
    const zip_fileinfo* zipfi,
    const void* extrafield_local,
    uInt size_extrafield_local,
    const void* extrafield_global,
    uInt size_extrafield_global,
    const char* comment,
    int method,
    int level,
    int raw,
    int windowBits,
    int memLevel,
    int strategy,
    const char* password,
    uLong crcForCrypting)
{
    zip_internal* zi;
    uInt size_filename;
    uInt size_comment;
    uInt i;
    int err = ZIP_OK;

#    ifdef NOCRYPT
    if (password != NULL)
        return ZIP_PARAMERROR;
#    endif

    if (file == NULL)
        return ZIP_PARAMERROR;
    if ((method!=0) && (method!=Z_DEFLATED))
        return ZIP_PARAMERROR;

    zi = (zip_internal*)file;

    if (zi->in_opened_file_inzip == 1)
    {
        err = zipCloseFileInZip (file);
        if (err != ZIP_OK)
            return err;
    }


    if (filename==NULL)
        filename="-";

    if (comment==NULL)
        size_comment = 0;
    else
        size_comment = strlen(comment);

    size_filename = strlen(filename);

    if (zipfi == NULL)
        zi->ci.dosDate = 0;
    else
    {
        if (zipfi->dosDate != 0)
            zi->ci.dosDate = zipfi->dosDate;
        else zi->ci.dosDate = ziplocal_TmzDateToDosDate(&zipfi->tmz_date,zipfi->dosDate);
    }

    zi->ci.flag = 0;
    if ((level==8) || (level==9))
      zi->ci.flag |= 2;
    if ((level==2))
      zi->ci.flag |= 4;
    if ((level==1))
      zi->ci.flag |= 6;
    if (password != NULL)
      zi->ci.flag |= 1;

    zi->ci.crc32 = 0;
    zi->ci.method = method;
    zi->ci.encrypt = 0;
    zi->ci.stream_initialised = 0;
    zi->ci.pos_in_buffered_data = 0;
    zi->ci.raw = raw;
    zi->ci.pos_local_header = ZTELL(zi->z_filefunc,zi->filestream) ;
    zi->ci.size_centralheader = SIZECENTRALHEADER + size_filename +
                                      size_extrafield_global + size_comment;
    zi->ci.central_header = (char*)ALLOC((uInt)zi->ci.size_centralheader);

    ziplocal_putValue_inmemory(zi->ci.central_header,(uLong)CENTRALHEADERMAGIC,4);
    /* version info */
    ziplocal_putValue_inmemory(zi->ci.central_header+4,(uLong)VERSIONMADEBY,2);
    ziplocal_putValue_inmemory(zi->ci.central_header+6,(uLong)20,2);
    ziplocal_putValue_inmemory(zi->ci.central_header+8,(uLong)zi->ci.flag,2);
    ziplocal_putValue_inmemory(zi->ci.central_header+10,(uLong)zi->ci.method,2);
    ziplocal_putValue_inmemory(zi->ci.central_header+12,(uLong)zi->ci.dosDate,4);
    ziplocal_putValue_inmemory(zi->ci.central_header+16,(uLong)0,4); /*crc*/
    ziplocal_putValue_inmemory(zi->ci.central_header+20,(uLong)0,4); /*compr size*/
    ziplocal_putValue_inmemory(zi->ci.central_header+24,(uLong)0,4); /*uncompr size*/
    ziplocal_putValue_inmemory(zi->ci.central_header+28,(uLong)size_filename,2);
    ziplocal_putValue_inmemory(zi->ci.central_header+30,(uLong)size_extrafield_global,2);
    ziplocal_putValue_inmemory(zi->ci.central_header+32,(uLong)size_comment,2);
    ziplocal_putValue_inmemory(zi->ci.central_header+34,(uLong)0,2); /*disk nm start*/

    if (zipfi==NULL)
        ziplocal_putValue_inmemory(zi->ci.central_header+36,(uLong)0,2);
    else
        ziplocal_putValue_inmemory(zi->ci.central_header+36,(uLong)zipfi->internal_fa,2);

    if (zipfi==NULL)
        ziplocal_putValue_inmemory(zi->ci.central_header+38,(uLong)0,4);
    else
        ziplocal_putValue_inmemory(zi->ci.central_header+38,(uLong)zipfi->external_fa,4);

    ziplocal_putValue_inmemory(zi->ci.central_header+42,(uLong)zi->ci.pos_local_header- zi->add_position_when_writting_offset,4);

    for (i=0;i<size_filename;i++)
        *(zi->ci.central_header+SIZECENTRALHEADER+i) = *(filename+i);

    for (i=0;i<size_extrafield_global;i++)
        *(zi->ci.central_header+SIZECENTRALHEADER+size_filename+i) =
              *(((const char*)extrafield_global)+i);

    for (i=0;i<size_comment;i++)
        *(zi->ci.central_header+SIZECENTRALHEADER+size_filename+
              size_extrafield_global+i) = *(comment+i);
    if (zi->ci.central_header == NULL)
        return ZIP_INTERNALERROR;

    /* write the local header */
    err = ziplocal_putValue(&zi->z_filefunc,zi->filestream,(uLong)LOCALHEADERMAGIC,4);

    if (err==ZIP_OK)
        err = ziplocal_putValue(&zi->z_filefunc,zi->filestream,(uLong)20,2);/* version needed to extract */
    if (err==ZIP_OK)
        err = ziplocal_putValue(&zi->z_filefunc,zi->filestream,(uLong)zi->ci.flag,2);

    if (err==ZIP_OK)
        err = ziplocal_putValue(&zi->z_filefunc,zi->filestream,(uLong)zi->ci.method,2);

    if (err==ZIP_OK)
        err = ziplocal_putValue(&zi->z_filefunc,zi->filestream,(uLong)zi->ci.dosDate,4);

    if (err==ZIP_OK)
        err = ziplocal_putValue(&zi->z_filefunc,zi->filestream,(uLong)0,4); /* crc 32, unknown */
    if (err==ZIP_OK)
        err = ziplocal_putValue(&zi->z_filefunc,zi->filestream,(uLong)0,4); /* compressed size, unknown */
    if (err==ZIP_OK)
        err = ziplocal_putValue(&zi->z_filefunc,zi->filestream,(uLong)0,4); /* uncompressed size, unknown */

    if (err==ZIP_OK)
        err = ziplocal_putValue(&zi->z_filefunc,zi->filestream,(uLong)size_filename,2);

    if (err==ZIP_OK)
        err = ziplocal_putValue(&zi->z_filefunc,zi->filestream,(uLong)size_extrafield_local,2);

    if ((err==ZIP_OK) && (size_filename>0))
        if (ZWRITE(zi->z_filefunc,zi->filestream,filename,size_filename)!=size_filename)
                err = ZIP_ERRNO;

    if ((err==ZIP_OK) && (size_extrafield_local>0))
        if (ZWRITE(zi->z_filefunc,zi->filestream,extrafield_local,size_extrafield_local)
                                                                           !=size_extrafield_local)
                err = ZIP_ERRNO;

    zi->ci.stream.avail_in = (uInt)0;
    zi->ci.stream.avail_out = (uInt)Z_BUFSIZE;
    zi->ci.stream.next_out = zi->ci.buffered_data;
    zi->ci.stream.total_in = 0;
    zi->ci.stream.total_out = 0;

    if ((err==ZIP_OK) && (zi->ci.method == Z_DEFLATED) && (!zi->ci.raw))
    {
        zi->ci.stream.zalloc = (alloc_func)0;
        zi->ci.stream.zfree = (free_func)0;
        zi->ci.stream.opaque = (voidpf)0;

        if (windowBits>0)
            windowBits = -windowBits;

        err = deflateInit2(&zi->ci.stream, level,
               Z_DEFLATED, windowBits, memLevel, strategy);

        if (err==Z_OK)
            zi->ci.stream_initialised = 1;
    }
#    ifndef NOCRYPT
    zi->ci.crypt_header_size = 0;
    if ((err==Z_OK) && (password != NULL))
    {
        unsigned char bufHead[RAND_HEAD_LEN];
        unsigned int sizeHead;
        zi->ci.encrypt = 1;
        zi->ci.pcrc_32_tab = (const unsigned long*)get_crc_table();
        /*init_keys(password,zi->ci.keys,zi->ci.pcrc_32_tab);*/

        sizeHead=crypthead(password,bufHead,RAND_HEAD_LEN,zi->ci.keys,zi->ci.pcrc_32_tab,crcForCrypting);
        zi->ci.crypt_header_size = sizeHead;

        if (ZWRITE(zi->z_filefunc,zi->filestream,bufHead,sizeHead) != sizeHead)
                err = ZIP_ERRNO;
    }
#    endif

    if (err==Z_OK)
        zi->in_opened_file_inzip = 1;
    return err;
}
Esempio n. 21
0
static opus_int silk_setup_resamplers(
    silk_encoder_state_Fxx          *psEnc,             /* I/O                      */
    opus_int                         fs_kHz              /* I                        */
)
{
    opus_int   ret = SILK_NO_ERROR;
    SAVE_STACK;

    if( psEnc->sCmn.fs_kHz != fs_kHz || psEnc->sCmn.prev_API_fs_Hz != psEnc->sCmn.API_fs_Hz )
    {
        if( psEnc->sCmn.fs_kHz == 0 ) {
            /* Initialize the resampler for enc_API.c preparing resampling from API_fs_Hz to fs_kHz */
            ret += silk_resampler_init( &psEnc->sCmn.resampler_state, psEnc->sCmn.API_fs_Hz, fs_kHz * 1000, 1 );
        } else {
            VARDECL( opus_int16, x_buf_API_fs_Hz );
            VARDECL( silk_resampler_state_struct, temp_resampler_state );
#ifdef FIXED_POINT
            opus_int16 *x_bufFIX = psEnc->x_buf;
#else
            VARDECL( opus_int16, x_bufFIX );
            opus_int32 new_buf_samples;
#endif
            opus_int32 api_buf_samples;
            opus_int32 old_buf_samples;
            opus_int32 buf_length_ms;

            buf_length_ms = silk_LSHIFT( psEnc->sCmn.nb_subfr * 5, 1 ) + LA_SHAPE_MS;
            old_buf_samples = buf_length_ms * psEnc->sCmn.fs_kHz;

#ifndef FIXED_POINT
            new_buf_samples = buf_length_ms * fs_kHz;
            ALLOC( x_bufFIX, silk_max( old_buf_samples, new_buf_samples ),
                   opus_int16 );
            silk_float2short_array( x_bufFIX, psEnc->x_buf, old_buf_samples );
#endif

            /* Initialize resampler for temporary resampling of x_buf data to API_fs_Hz */
            ALLOC( temp_resampler_state, 1, silk_resampler_state_struct );
            ret += silk_resampler_init( temp_resampler_state, silk_SMULBB( psEnc->sCmn.fs_kHz, 1000 ), psEnc->sCmn.API_fs_Hz, 0 );

            /* Calculate number of samples to temporarily upsample */
            api_buf_samples = buf_length_ms * silk_DIV32_16( psEnc->sCmn.API_fs_Hz, 1000 );

            /* Temporary resampling of x_buf data to API_fs_Hz */
            ALLOC( x_buf_API_fs_Hz, api_buf_samples, opus_int16 );
            ret += silk_resampler( temp_resampler_state, x_buf_API_fs_Hz, x_bufFIX, old_buf_samples );

            /* Initialize the resampler for enc_API.c preparing resampling from API_fs_Hz to fs_kHz */
            ret += silk_resampler_init( &psEnc->sCmn.resampler_state, psEnc->sCmn.API_fs_Hz, silk_SMULBB( fs_kHz, 1000 ), 1 );

            /* Correct resampler state by resampling buffered data from API_fs_Hz to fs_kHz */
            ret += silk_resampler( &psEnc->sCmn.resampler_state, x_bufFIX, x_buf_API_fs_Hz, api_buf_samples );

#ifndef FIXED_POINT
            silk_short2float_array( psEnc->x_buf, x_bufFIX, new_buf_samples);
#endif
        }
    }

    psEnc->sCmn.prev_API_fs_Hz = psEnc->sCmn.API_fs_Hz;

    RESTORE_STACK;
    return ret;
}
Esempio n. 22
0
/* Find pitch lags */
void silk_find_pitch_lags_FIX(
    silk_encoder_state_FIX          *psEnc,                                 /* I/O  encoder state                                                               */
    silk_encoder_control_FIX        *psEncCtrl,                             /* I/O  encoder control                                                             */
    opus_int16                      res[],                                  /* O    residual                                                                    */
    const opus_int16                x[],                                    /* I    Speech signal                                                               */
    int                             arch                                    /* I    Run-time architecture                                                       */
)
{
    opus_int   buf_len, i, scale;
    opus_int32 thrhld_Q13, res_nrg;
    const opus_int16 *x_buf, *x_buf_ptr;
    VARDECL(opus_int16, Wsig);
    opus_int16 *Wsig_ptr;
    opus_int32 auto_corr[ MAX_FIND_PITCH_LPC_ORDER + 1 ];
    opus_int16 rc_Q15[    MAX_FIND_PITCH_LPC_ORDER ];
    opus_int32 A_Q24[     MAX_FIND_PITCH_LPC_ORDER ];
    opus_int16 A_Q12[     MAX_FIND_PITCH_LPC_ORDER ];
    SAVE_STACK;

    /******************************************/
    /* Set up buffer lengths etc based on Fs  */
    /******************************************/
    buf_len = psEnc->sCmn.la_pitch + psEnc->sCmn.frame_length + psEnc->sCmn.ltp_mem_length;

    /* Safety check */
    silk_assert(buf_len >= psEnc->sCmn.pitch_LPC_win_length);

    x_buf = x - psEnc->sCmn.ltp_mem_length;

    /*************************************/
    /* Estimate LPC AR coefficients      */
    /*************************************/

    /* Calculate windowed signal */

    ALLOC(Wsig, psEnc->sCmn.pitch_LPC_win_length, opus_int16);

    /* First LA_LTP samples */
    x_buf_ptr = x_buf + buf_len - psEnc->sCmn.pitch_LPC_win_length;
    Wsig_ptr  = Wsig;
    silk_apply_sine_window(Wsig_ptr, x_buf_ptr, 1, psEnc->sCmn.la_pitch);

    /* Middle un - windowed samples */
    Wsig_ptr  += psEnc->sCmn.la_pitch;
    x_buf_ptr += psEnc->sCmn.la_pitch;
    silk_memcpy(Wsig_ptr, x_buf_ptr, (psEnc->sCmn.pitch_LPC_win_length - silk_LSHIFT(psEnc->sCmn.la_pitch, 1)) * sizeof(opus_int16));

    /* Last LA_LTP samples */
    Wsig_ptr  += psEnc->sCmn.pitch_LPC_win_length - silk_LSHIFT(psEnc->sCmn.la_pitch, 1);
    x_buf_ptr += psEnc->sCmn.pitch_LPC_win_length - silk_LSHIFT(psEnc->sCmn.la_pitch, 1);
    silk_apply_sine_window(Wsig_ptr, x_buf_ptr, 2, psEnc->sCmn.la_pitch);

    /* Calculate autocorrelation sequence */
    silk_autocorr(auto_corr, &scale, Wsig, psEnc->sCmn.pitch_LPC_win_length, psEnc->sCmn.pitchEstimationLPCOrder + 1, arch);

    /* Add white noise, as fraction of energy */
    auto_corr[ 0 ] = silk_SMLAWB(auto_corr[ 0 ], auto_corr[ 0 ], SILK_FIX_CONST(FIND_PITCH_WHITE_NOISE_FRACTION, 16)) + 1;

    /* Calculate the reflection coefficients using schur */
    res_nrg = silk_schur(rc_Q15, auto_corr, psEnc->sCmn.pitchEstimationLPCOrder);

    /* Prediction gain */
    psEncCtrl->predGain_Q16 = silk_DIV32_varQ(auto_corr[ 0 ], silk_max_int(res_nrg, 1), 16);

    /* Convert reflection coefficients to prediction coefficients */
    silk_k2a(A_Q24, rc_Q15, psEnc->sCmn.pitchEstimationLPCOrder);

    /* Convert From 32 bit Q24 to 16 bit Q12 coefs */
    for(i = 0; i < psEnc->sCmn.pitchEstimationLPCOrder; i++) {
        A_Q12[ i ] = (opus_int16)silk_SAT16(silk_RSHIFT(A_Q24[ i ], 12));
    }

    /* Do BWE */
    silk_bwexpander(A_Q12, psEnc->sCmn.pitchEstimationLPCOrder, SILK_FIX_CONST(FIND_PITCH_BANDWIDTH_EXPANSION, 16));

    /*****************************************/
    /* LPC analysis filtering                */
    /*****************************************/
    silk_LPC_analysis_filter(res, x_buf, A_Q12, buf_len, psEnc->sCmn.pitchEstimationLPCOrder, psEnc->sCmn.arch);

    if(psEnc->sCmn.indices.signalType != TYPE_NO_VOICE_ACTIVITY && psEnc->sCmn.first_frame_after_reset == 0) {
        /* Threshold for pitch estimator */
        thrhld_Q13 = SILK_FIX_CONST(0.6, 13);
        thrhld_Q13 = silk_SMLABB(thrhld_Q13, SILK_FIX_CONST(-0.004, 13), psEnc->sCmn.pitchEstimationLPCOrder);
        thrhld_Q13 = silk_SMLAWB(thrhld_Q13, SILK_FIX_CONST(-0.1,   21 ), psEnc->sCmn.speech_activity_Q8);
        thrhld_Q13 = silk_SMLABB(thrhld_Q13, SILK_FIX_CONST(-0.15,  13), silk_RSHIFT(psEnc->sCmn.prevSignalType, 1));
        thrhld_Q13 = silk_SMLAWB(thrhld_Q13, SILK_FIX_CONST(-0.1,   14), psEnc->sCmn.input_tilt_Q15);
        thrhld_Q13 = silk_SAT16( thrhld_Q13);

        /*****************************************/
        /* Call pitch estimator                  */
        /*****************************************/
        if(silk_pitch_analysis_core(res, psEncCtrl->pitchL, &psEnc->sCmn.indices.lagIndex, &psEnc->sCmn.indices.contourIndex,
                &psEnc->LTPCorr_Q15, psEnc->sCmn.prevLag, psEnc->sCmn.pitchEstimationThreshold_Q16,
                (opus_int)thrhld_Q13, psEnc->sCmn.fs_kHz, psEnc->sCmn.pitchEstimationComplexity, psEnc->sCmn.nb_subfr,
                psEnc->sCmn.arch) == 0)
        {
            psEnc->sCmn.indices.signalType = TYPE_VOICED;
        } else {
            psEnc->sCmn.indices.signalType = TYPE_UNVOICED;
        }
    } else {
        silk_memset(psEncCtrl->pitchL, 0, sizeof(psEncCtrl->pitchL));
        psEnc->sCmn.indices.lagIndex = 0;
        psEnc->sCmn.indices.contourIndex = 0;
        psEnc->LTPCorr_Q15 = 0;
    }
    RESTORE_STACK;
}
Esempio n. 23
0
/**
  @brief Symmetric sifting to convergence algorithm.

  @details Assumes that no dead nodes are present.
    <ol>
    <li> Order all the variables according to the number of entries in
    each unique subtable.
    <li> Sift the variable up and down, remembering each time the total
    size of the %DD heap and grouping variables that are symmetric.
    <li> Select the best permutation.
    <li> Repeat 3 and 4 for all variables.
    <li> Repeat 1-4 until no further improvement.
    </ol>

  @return 1 plus the number of symmetric variables if successful; 0
  otherwise.

  @sideeffect None

  @see cuddSymmSifting

*/
int
cuddSymmSiftingConv(
  DdManager * table,
  int  lower,
  int  upper)
{
    int		i;
    IndexKey	*var;
    int		size;
    int		x;
    int		result;
    int		symvars;
    int		symgroups;
    int		classes;
    int		initialSize;
#ifdef DD_STATS
    int		previousSize;
#endif

    initialSize = (int) (table->keys - table->isolated);

    size = table->size;

    /* Find order in which to sift variables. */
    var = ALLOC(IndexKey,size);
    if (var == NULL) {
	table->errorCode = CUDD_MEMORY_OUT;
	goto ddSymmSiftingConvOutOfMem;
    }

    for (i = 0; i < size; i++) {
	x = table->perm[i];
	var[i].index = i;
	var[i].keys = table->subtables[x].keys;
    }

    util_qsort(var,size,sizeof(IndexKey),ddSymmUniqueCompare);

    /* Initialize the symmetry of each subtable to itself
    ** for first pass of converging symmetric sifting.
    */
    for (i = lower; i <= upper; i++) {
	table->subtables[i].next = i;
    }

    for (i = 0; i < ddMin(table->siftMaxVar, table->size); i++) {
	if (table->ddTotalNumberSwapping >= table->siftMaxSwap)
	    break;
        if (util_cpu_time() - table->startTime > table->timeLimit) {
            table->autoDyn = 0; /* prevent further reordering */
            break;
        }
        if (table->terminationCallback != NULL &&
            table->terminationCallback(table->tcbArg)) {
            table->autoDyn = 0; /* prevent further reordering */
            break;
        }
	x = table->perm[var[i].index];
	if (x < lower || x > upper) continue;
	/* Only sift if not in symmetry group already. */
	if (table->subtables[x].next == (unsigned) x) {
#ifdef DD_STATS
          previousSize = (int) (table->keys - table->isolated);
#endif
	    result = ddSymmSiftingAux(table,x,lower,upper);
	    if (!result) goto ddSymmSiftingConvOutOfMem;
#ifdef DD_STATS
	    if (table->keys < (unsigned) previousSize + table->isolated) {
		(void) fprintf(table->out,"-");
	    } else if (table->keys > (unsigned) previousSize +
		       table->isolated) {
		(void) fprintf(table->out,"+");
	    } else {
		(void) fprintf(table->out,"=");
	    }
	    fflush(table->out);
#endif
	}
    }

    /* Sifting now until convergence. */
    while ((unsigned) initialSize > table->keys - table->isolated) {
      initialSize = (int) (table->keys - table->isolated);
#ifdef DD_STATS
	(void) fprintf(table->out,"\n");
#endif
	/* Here we consider only one representative for each symmetry class. */
	for (x = lower, classes = 0; x <= upper; x++, classes++) {
	    while ((unsigned) x < table->subtables[x].next) {
		x = table->subtables[x].next;
	    }
	    /* Here x is the largest index in a group.
	    ** Groups consist of adjacent variables.
	    ** Hence, the next increment of x will move it to a new group.
	    */
	    i = table->invperm[x];
	    var[classes].keys = table->subtables[x].keys;
	    var[classes].index = i;
	}

	util_qsort(var,classes,sizeof(IndexKey),ddSymmUniqueCompare);

	/* Now sift. */
	for (i = 0; i < ddMin(table->siftMaxVar,classes); i++) {
	    if (table->ddTotalNumberSwapping >= table->siftMaxSwap)
		break;
            if (util_cpu_time() - table->startTime > table->timeLimit) {
              table->autoDyn = 0; /* prevent further reordering */
              break;
            }
            if (table->terminationCallback != NULL &&
                table->terminationCallback(table->tcbArg)) {
                table->autoDyn = 0; /* prevent further reordering */
                break;
            }
	    x = table->perm[var[i].index];
	    if ((unsigned) x >= table->subtables[x].next) {
#ifdef DD_STATS
              previousSize = (int) (table->keys - table->isolated);
#endif
		result = ddSymmSiftingConvAux(table,x,lower,upper);
		if (!result ) goto ddSymmSiftingConvOutOfMem;
#ifdef DD_STATS
		if (table->keys < (unsigned) previousSize + table->isolated) {
		    (void) fprintf(table->out,"-");
		} else if (table->keys > (unsigned) previousSize +
			   table->isolated) {
		    (void) fprintf(table->out,"+");
		} else {
		    (void) fprintf(table->out,"=");
		}
		fflush(table->out);
#endif
	    }
	} /* for */
    }

    ddSymmSummary(table, lower, upper, &symvars, &symgroups);

#ifdef DD_STATS
    (void) fprintf(table->out, "\n#:S_SIFTING %8d: symmetric variables\n",
		   symvars);
    (void) fprintf(table->out, "#:G_SIFTING %8d: symmetric groups",
		   symgroups);
#endif

    FREE(var);

    return(1+symvars);

ddSymmSiftingConvOutOfMem:

    if (var != NULL) FREE(var);

    return(0);

} /* end of cuddSymmSiftingConv */
Esempio n. 24
0
static int
sig_process(hx509_context context, void *ctx, hx509_cert cert)
{
    struct sigctx *sigctx = ctx;
    heim_octet_string buf, sigdata = { 0, NULL };
    SignerInfo *signer_info = NULL;
    AlgorithmIdentifier digest;
    size_t size;
    void *ptr;
    int ret;
    SignedData *sd = &sigctx->sd;
    hx509_path path;

    memset(&digest, 0, sizeof(digest));
    memset(&path, 0, sizeof(path));

    if (_hx509_cert_private_key(cert) == NULL) {
	hx509_set_error_string(context, 0, HX509_PRIVATE_KEY_MISSING,
			       "Private key missing for signing");
	return HX509_PRIVATE_KEY_MISSING;
    }

    if (sigctx->digest_alg) {
	ret = copy_AlgorithmIdentifier(sigctx->digest_alg, &digest);
	if (ret)
	    hx509_clear_error_string(context);
    } else {
	ret = hx509_crypto_select(context, HX509_SELECT_DIGEST,
				  _hx509_cert_private_key(cert), 
				  sigctx->peer, &digest);
    }
    if (ret)
	goto out;

    /*
     * Allocate on more signerInfo and do the signature processing
     */

    ptr = realloc(sd->signerInfos.val,
		  (sd->signerInfos.len + 1) * sizeof(sd->signerInfos.val[0]));
    if (ptr == NULL) {
	ret = ENOMEM;
	goto out;
    }
    sd->signerInfos.val = ptr;

    signer_info = &sd->signerInfos.val[sd->signerInfos.len];

    memset(signer_info, 0, sizeof(*signer_info));

    signer_info->version = 1;

    ret = fill_CMSIdentifier(cert, sigctx->cmsidflag, &signer_info->sid);
    if (ret) {
	hx509_clear_error_string(context);
	goto out;
    }			

    signer_info->signedAttrs = NULL;
    signer_info->unsignedAttrs = NULL;

    ret = copy_AlgorithmIdentifier(&digest, &signer_info->digestAlgorithm);
    if (ret) {
	hx509_clear_error_string(context);
	goto out;
    }

    /*
     * If it isn't pkcs7-data send signedAttributes
     */

    if (der_heim_oid_cmp(sigctx->eContentType, &asn1_oid_id_pkcs7_data) != 0) {
	CMSAttributes sa;	
	heim_octet_string sig;

	ALLOC(signer_info->signedAttrs, 1);
	if (signer_info->signedAttrs == NULL) {
	    ret = ENOMEM;
	    goto out;
	}

	ret = _hx509_create_signature(context,
				      NULL,
				      &digest,
				      &sigctx->content,
				      NULL,
				      &sig);
	if (ret)
	    goto out;

	ASN1_MALLOC_ENCODE(MessageDigest,
			   buf.data,
			   buf.length,
			   &sig,
			   &size,
			   ret);
	der_free_octet_string(&sig);
	if (ret) {
	    hx509_clear_error_string(context);
	    goto out;
	}
	if (size != buf.length)
	    _hx509_abort("internal ASN.1 encoder error");

	ret = add_one_attribute(&signer_info->signedAttrs->val,
				&signer_info->signedAttrs->len,
				&asn1_oid_id_pkcs9_messageDigest,
				&buf);
	if (ret) {
	    free(buf.data);
	    hx509_clear_error_string(context);
	    goto out;
	}


	ASN1_MALLOC_ENCODE(ContentType,
			   buf.data,
			   buf.length,
			   sigctx->eContentType,
			   &size,
			   ret);
	if (ret)
	    goto out;
	if (size != buf.length)
	    _hx509_abort("internal ASN.1 encoder error");

	ret = add_one_attribute(&signer_info->signedAttrs->val,
				&signer_info->signedAttrs->len,
				&asn1_oid_id_pkcs9_contentType,
				&buf);
	if (ret) {
	    free(buf.data);
	    hx509_clear_error_string(context);
	    goto out;
	}

	sa.val = signer_info->signedAttrs->val;
	sa.len = signer_info->signedAttrs->len;
	
	ASN1_MALLOC_ENCODE(CMSAttributes,
			   sigdata.data,
			   sigdata.length,
			   &sa,
			   &size,
			   ret);
	if (ret) {
	    hx509_clear_error_string(context);
	    goto out;
	}
	if (size != sigdata.length)
	    _hx509_abort("internal ASN.1 encoder error");
    } else {
	sigdata.data = sigctx->content.data;
	sigdata.length = sigctx->content.length;
    }

    {
	AlgorithmIdentifier sigalg;

	ret = hx509_crypto_select(context, HX509_SELECT_PUBLIC_SIG,
				  _hx509_cert_private_key(cert), sigctx->peer,
				  &sigalg);
	if (ret)
	    goto out;

	ret = _hx509_create_signature(context,
				      _hx509_cert_private_key(cert),
				      &sigalg,
				      &sigdata,
				      &signer_info->signatureAlgorithm,
				      &signer_info->signature);
	free_AlgorithmIdentifier(&sigalg);
	if (ret)
	    goto out;
    }

    sigctx->sd.signerInfos.len++;
    signer_info = NULL;

    /*
     * Provide best effort path
     */
    if (sigctx->certs) {
	unsigned int i;

	if (sigctx->pool) {
	    _hx509_calculate_path(context,
				  HX509_CALCULATE_PATH_NO_ANCHOR,
				  time(NULL),
				  sigctx->anchors,
				  0,
				  cert,
				  sigctx->pool,
				  &path);
	} else
	    _hx509_path_append(context, &path, cert);

	for (i = 0; i < path.len; i++) {
	    /* XXX remove dups */
	    ret = hx509_certs_add(context, sigctx->certs, path.val[i]);
	    if (ret) {
		hx509_clear_error_string(context);
		goto out;
	    }
	}
    }

 out:
    if (signer_info)
	free_SignerInfo(signer_info);
    if (sigdata.data != sigctx->content.data)
	der_free_octet_string(&sigdata);
    _hx509_path_free(&path);
    free_AlgorithmIdentifier(&digest);

    return ret;
}
Esempio n. 25
0
rev_list *
rev_list_merge (rev_list *head)
{
    int		count = rev_list_count (head);
    rev_list	*rl;
    rev_list	*l;
    rev_ref	*lh, *h;
    Tag		*t;
    rev_ref	**refs;
    int		nref;

    ALLOC((rl = calloc (1, sizeof (rev_list))), "rev_list_merge");
    ALLOC((refs = calloc (count, sizeof (rev_ref *))), "rev_list_merge");
    /*
     * Find all of the heads across all of the incoming trees
     * Yes, this is currently very inefficient
     */
    for (l = head; l; l = l->next) {
	for (lh = l->heads; lh; lh = lh->next) {
	    h = rev_find_head (rl, lh->name);
	    if (!h)
		rev_list_add_head (rl, NULL, lh->name, lh->degree);
	    else if (lh->degree > h->degree)
		h->degree = lh->degree;
	}
    }
    /*
     * Sort by degree so that finding branch points always works
     */
//    rl->heads = rev_ref_sel_sort (rl->heads);
    rl->heads = rev_ref_tsort (rl->heads, head);
    if (!rl->heads)
	return NULL;
//    for (h = rl->heads; h; h = h->next)
//	fprintf (stderr, "head %s (%d)\n",
//		 h->name, h->degree);
    /*
     * Find branch parent relationships
     */
    for (h = rl->heads; h; h = h->next) {
	rev_ref_set_parent (rl, h, head);
//	dump_ref_name (stderr, h);
//	fprintf (stderr, "\n");
    }
    /*
     * Merge common branches
     */
    for (h = rl->heads; h; h = h->next) {
	/*
	 * Locate branch in every tree
	 */
	nref = 0;
	for (l = head; l; l = l->next) {
	    lh = rev_find_head (l, h->name);
	    if (lh)
		refs[nref++] = lh;
	}
	if (nref)
	    rev_branch_merge (refs, nref, h, rl);
    }
    /*
     * Compute 'tail' values
     */
    rev_list_set_tail (rl);

    free(refs);
    /*
     * Find tag locations
     */
    for (t = all_tags; t; t = t->next) {
	rev_commit **commits = tagged(t);
	if (commits)
	    rev_tag_search(t, commits, rl);
	else
	    fprintf (stderr, "lost tag %s\n", t->name);
	free(commits);
    }
    rev_list_validate (rl);
    return rl;
}
Esempio n. 26
0
int
hx509_cms_create_signed(hx509_context context,
			int flags,
			const heim_oid *eContentType,
			const void *data, size_t length,
			const AlgorithmIdentifier *digest_alg,
			hx509_certs certs,
			hx509_peer_info peer,
			hx509_certs anchors,
			hx509_certs pool,
			heim_octet_string *signed_data)
{
    unsigned int i;
    hx509_name name;
    int ret;
    size_t size;
    struct sigctx sigctx;

    memset(&sigctx, 0, sizeof(sigctx));
    memset(&name, 0, sizeof(name));

    if (eContentType == NULL)
	eContentType = &asn1_oid_id_pkcs7_data;

    sigctx.digest_alg = digest_alg;
    sigctx.content.data = rk_UNCONST(data);
    sigctx.content.length = length;
    sigctx.eContentType = eContentType;
    sigctx.peer = peer;
    /**
     * Use HX509_CMS_SIGNATURE_ID_NAME to preferred use of issuer name
     * and serial number if possible. Otherwise subject key identifier
     * will preferred.
     */
    if (flags & HX509_CMS_SIGNATURE_ID_NAME)
	sigctx.cmsidflag = CMS_ID_NAME;
    else
	sigctx.cmsidflag = CMS_ID_SKI;

    ret = hx509_certs_init(context, "MEMORY:certs", 0, NULL, &sigctx.certs);
    if (ret)
	return ret;

    sigctx.anchors = anchors;
    sigctx.pool = pool;

    sigctx.sd.version = CMSVersion_v3;

    der_copy_oid(eContentType, &sigctx.sd.encapContentInfo.eContentType);

    /**
     * Use HX509_CMS_SIGNATURE_DETACHED to create detached signatures.
     */
    if ((flags & HX509_CMS_SIGNATURE_DETACHED) == 0) {
	ALLOC(sigctx.sd.encapContentInfo.eContent, 1);
	if (sigctx.sd.encapContentInfo.eContent == NULL) {
	    hx509_clear_error_string(context);
	    ret = ENOMEM;
	    goto out;
	}
	
	sigctx.sd.encapContentInfo.eContent->data = malloc(length);
	if (sigctx.sd.encapContentInfo.eContent->data == NULL) {
	    hx509_clear_error_string(context);
	    ret = ENOMEM;
	    goto out;
	}
	memcpy(sigctx.sd.encapContentInfo.eContent->data, data, length);
	sigctx.sd.encapContentInfo.eContent->length = length;
    }

    /**
     * Use HX509_CMS_SIGNATURE_NO_SIGNER to create no sigInfo (no
     * signatures).
     */
    if ((flags & HX509_CMS_SIGNATURE_NO_SIGNER) == 0) {
	ret = hx509_certs_iter(context, certs, sig_process, &sigctx);
	if (ret)
	    goto out;
    }

    if (sigctx.sd.signerInfos.len) {
	ALLOC_SEQ(&sigctx.sd.digestAlgorithms, sigctx.sd.signerInfos.len);
	if (sigctx.sd.digestAlgorithms.val == NULL) {
	    ret = ENOMEM;
	    hx509_clear_error_string(context);
	    goto out;
	}
	
	/* XXX remove dups */
	for (i = 0; i < sigctx.sd.signerInfos.len; i++) {
	    AlgorithmIdentifier *di =
		&sigctx.sd.signerInfos.val[i].digestAlgorithm;
	    ret = copy_AlgorithmIdentifier(di,
					   &sigctx.sd.digestAlgorithms.val[i]);
	    if (ret) {
		hx509_clear_error_string(context);
		goto out;
	    }
	}
    }

    if (sigctx.certs) {
	ALLOC(sigctx.sd.certificates, 1);
	if (sigctx.sd.certificates == NULL) {
	    hx509_clear_error_string(context);
	    ret = ENOMEM;
	    goto out;
	}

	ret = hx509_certs_iter(context, sigctx.certs, cert_process, &sigctx);
	if (ret)
	    goto out;
    }

    ASN1_MALLOC_ENCODE(SignedData,
		       signed_data->data, signed_data->length,
		       &sigctx.sd, &size, ret);
    if (ret) {
	hx509_clear_error_string(context);
	goto out;
    }
    if (signed_data->length != size)
	_hx509_abort("internal ASN.1 encoder error");

out:
    hx509_certs_free(&sigctx.certs);
    free_SignedData(&sigctx.sd);

    return ret;
}
Esempio n. 27
0
/*
 * Initialize the device.
 */
int
siop_init(int bus, int dev, int func)
{
	struct siop_adapter tmp;
	struct siop_xfer *xfer;
	struct scsipi_generic *cmd;
	struct scsi_request_sense *sense;
	uint32_t reg;
	u_long addr;
	uint32_t *script;
	int slot, id, i;
	void *scriptaddr;
	u_char *data;
	const int clock_div = 3;		/* 53c810 */

	slot = PCISlotnum(bus, dev, func);
	if (slot == -1)
		return ENOENT;

	addr = PCIAddress(slot, 1, PCI_MAPREG_TYPE_MEM);
	if (addr == 0xffffffff)
		return EINVAL;
	enablePCI(slot, 0, 1, 1);

	script = ALLOC(uint32_t, SIOP_SCRIPT_SIZE);
	if (script == NULL)
		return ENOMEM;
	scriptaddr = (void *)local_to_PCI((u_long)script);
	cmd = ALLOC(struct scsipi_generic, SIOP_SCSI_COMMAND_SIZE);
	if (cmd == NULL)
		return ENOMEM;
	sense = ALLOC(struct scsi_request_sense, SIOP_SCSI_COMMAND_SIZE);
	if (sense == NULL)
		return ENOMEM;
	data = ALLOC(u_char, SIOP_SCSI_DATA_SIZE);
	if (data == NULL)
		return ENOMEM;
	xfer = ALLOC(struct siop_xfer, sizeof(struct siop_xfer));
	if (xfer == NULL)
		return ENOMEM;
	siop_xfer_setup(xfer, scriptaddr);

	id = readb(addr + SIOP_SCID) & SCID_ENCID_MASK;

	/* reset bus */
	reg = readb(addr + SIOP_SCNTL1);
	writeb(addr + SIOP_SCNTL1, reg | SCNTL1_RST);
	delay(100);
	writeb(addr + SIOP_SCNTL1, reg);

	/* reset the chip */
	writeb(addr + SIOP_ISTAT, ISTAT_SRST);
	delay(1000);
	writeb(addr + SIOP_ISTAT, 0);

	/* init registers */
	writeb(addr + SIOP_SCNTL0, SCNTL0_ARB_MASK | SCNTL0_EPC | SCNTL0_AAP);
	writeb(addr + SIOP_SCNTL1, 0);
	writeb(addr + SIOP_SCNTL3, clock_div);
	writeb(addr + SIOP_SXFER, 0);
	writeb(addr + SIOP_DIEN, 0xff);
	writeb(addr + SIOP_SIEN0, 0xff & ~(SIEN0_CMP | SIEN0_SEL | SIEN0_RSL));
	writeb(addr + SIOP_SIEN1, 0xff & ~(SIEN1_HTH | SIEN1_GEN));
	writeb(addr + SIOP_STEST2, 0);
	writeb(addr + SIOP_STEST3, STEST3_TE);
	writeb(addr + SIOP_STIME0, (0xb << STIME0_SEL_SHIFT));
	writeb(addr + SIOP_SCID, id | SCID_RRE);
	writeb(addr + SIOP_RESPID0, 1 << id);
	writeb(addr + SIOP_DCNTL, DCNTL_COM);

	/* BeBox uses PCIC */
	writeb(addr + SIOP_STEST1, STEST1_SCLK);

	siop_pci_reset(addr);

	/* copy and patch the script */
	for (i = 0; i < __arraycount(siop_script); i++)
		script[i] = htoc32(siop_script[i]);
	for (i = 0; i < __arraycount(E_abs_msgin_Used); i++)
		script[E_abs_msgin_Used[i]] =
		    htoc32(scriptaddr + Ent_msgin_space);

	/* start script */
	_wbinv((u_long)script, SIOP_SCRIPT_SIZE);
	writel(addr + SIOP_DSP, (int)scriptaddr + Ent_reselect);

	memset(&tmp, 0, sizeof(tmp));
	tmp.id = id;
	tmp.clock_div = clock_div;
	tmp.addr = addr;
	tmp.script = script;
	tmp.xfer = xfer;
	tmp.cmd = cmd;
	tmp.sense = sense;
	tmp.data = data;
	tmp.currschedslot = 0;
	tmp.sel_t = -1;

	if (scsi_probe(&tmp) == 0)
		return ENXIO;
	adapt = tmp;
	return 0;
}
Esempio n. 28
0
int
hx509_cms_envelope_1(hx509_context context,
		     int flags,
		     hx509_cert cert,
		     const void *data,
		     size_t length,
		     const heim_oid *encryption_type,
		     const heim_oid *contentType,
		     heim_octet_string *content)
{
    KeyTransRecipientInfo *ri;
    heim_octet_string ivec;
    heim_octet_string key;
    hx509_crypto crypto = NULL;
    EnvelopedData ed;
    size_t size;
    int ret;

    memset(&ivec, 0, sizeof(ivec));
    memset(&key, 0, sizeof(key));
    memset(&ed, 0, sizeof(ed));
    memset(content, 0, sizeof(*content));

    if (encryption_type == NULL)
	encryption_type = &asn1_oid_id_aes_256_cbc;

    if ((flags & HX509_CMS_EV_NO_KU_CHECK) == 0) {
	ret = _hx509_check_key_usage(context, cert, 1 << 2, TRUE);
	if (ret)
	    goto out;
    }

    ret = hx509_crypto_init(context, NULL, encryption_type, &crypto);
    if (ret)
	goto out;

    if (flags & HX509_CMS_EV_ALLOW_WEAK)
	hx509_crypto_allow_weak(crypto);

    ret = hx509_crypto_set_random_key(crypto, &key);
    if (ret) {
	hx509_set_error_string(context, 0, ret,
			       "Create random key for EnvelopedData content");
	goto out;
    }

    ret = hx509_crypto_random_iv(crypto, &ivec);
    if (ret) {
	hx509_set_error_string(context, 0, ret,
			       "Failed to create a random iv");
	goto out;
    }

    ret = hx509_crypto_encrypt(crypto,
			       data,
			       length,
			       &ivec,
			       &ed.encryptedContentInfo.encryptedContent);
    if (ret) {
	hx509_set_error_string(context, 0, ret,
			       "Failed to encrypt EnvelopedData content");
	goto out;
    }

    {
	AlgorithmIdentifier *enc_alg;
	enc_alg = &ed.encryptedContentInfo.contentEncryptionAlgorithm;
	ret = der_copy_oid(encryption_type, &enc_alg->algorithm);
	if (ret) {
	    hx509_set_error_string(context, 0, ret,
				   "Failed to set crypto oid "
				   "for EnvelopedData");
	    goto out;
	}	
	ALLOC(enc_alg->parameters, 1);
	if (enc_alg->parameters == NULL) {
	    ret = ENOMEM;
	    hx509_set_error_string(context, 0, ret,
				   "Failed to allocate crypto paramaters "
				   "for EnvelopedData");
	    goto out;
	}

	ret = hx509_crypto_get_params(context,
				      crypto,
				      &ivec,
				      enc_alg->parameters);
	if (ret) {
	    goto out;
	}
    }

    ALLOC_SEQ(&ed.recipientInfos, 1);
    if (ed.recipientInfos.val == NULL) {
	ret = ENOMEM;
	hx509_set_error_string(context, 0, ret,
			       "Failed to allocate recipients info "
			       "for EnvelopedData");
	goto out;
    }

    ri = &ed.recipientInfos.val[0];

    ri->version = 0;
    ret = fill_CMSIdentifier(cert, CMS_ID_SKI, &ri->rid);
    if (ret) {
	hx509_set_error_string(context, 0, ret,
			       "Failed to set CMS identifier info "
			       "for EnvelopedData");
	goto out;
    }

    ret = _hx509_cert_public_encrypt(context,
				     &key, cert,
				     &ri->keyEncryptionAlgorithm.algorithm,
				     &ri->encryptedKey);
    if (ret) {
	hx509_set_error_string(context, HX509_ERROR_APPEND, ret,
			       "Failed to encrypt transport key for "
			       "EnvelopedData");
	goto out;
    }

    /*
     *
     */

    ed.version = 0;
    ed.originatorInfo = NULL;

    ret = der_copy_oid(contentType, &ed.encryptedContentInfo.contentType);
    if (ret) {
	hx509_set_error_string(context, 0, ret,
			       "Failed to copy content oid for "
			       "EnvelopedData");
	goto out;
    }

    ed.unprotectedAttrs = NULL;

    ASN1_MALLOC_ENCODE(EnvelopedData, content->data, content->length,
		       &ed, &size, ret);
    if (ret) {
	hx509_set_error_string(context, 0, ret,
			       "Failed to encode EnvelopedData");
	goto out;
    }
    if (size != content->length)
	_hx509_abort("internal ASN.1 encoder error");

out:
    if (crypto)
	hx509_crypto_destroy(crypto);
    if (ret)
	der_free_octet_string(content);
    der_free_octet_string(&key);
    der_free_octet_string(&ivec);
    free_EnvelopedData(&ed);

    return ret;
}
Esempio n. 29
0
File: data.c Progetto: Miraculix/dgd
/*
 * NAME:	data->alloc_call_out()
 * DESCRIPTION:	allocate a new callout
 */
static uindex d_alloc_call_out(dataspace *data, uindex handle, Uint time, 
	unsigned short mtime, int nargs, value *v)
{
    dcallout *co;

    if (data->ncallouts == 0) {
	/*
	 * the first in this object
	 */
	co = data->callouts = ALLOC(dcallout, 1);
	data->ncallouts = handle = 1;
	data->plane->flags |= MOD_NEWCALLOUT;
    } else {
	if (data->callouts == (dcallout *) NULL) {
	    d_get_callouts(data);
	}
	if (handle != 0) {
	    /*
	     * get a specific callout from the free list
	     */
	    co = &data->callouts[handle - 1];
	    if (handle == data->fcallouts) {
		data->fcallouts = co->co_next;
	    } else {
		data->callouts[co->co_prev - 1].co_next = co->co_next;
		if (co->co_next != 0) {
		    data->callouts[co->co_next - 1].co_prev = co->co_prev;
		}
	    }
	} else {
	    handle = data->fcallouts;
	    if (handle != 0) {
		/*
		 * from free list
		 */
		co = &data->callouts[handle - 1];
		if (co->co_next == 0 || co->co_next > handle) {
		    /* take 1st free callout */
		    data->fcallouts = co->co_next;
		} else {
		    /* take 2nd free callout */
		    co = &data->callouts[co->co_next - 1];
		    data->callouts[handle - 1].co_next = co->co_next;
		    if (co->co_next != 0) {
			data->callouts[co->co_next - 1].co_prev = handle;
		    }
		    handle = co - data->callouts + 1;
		}
		data->plane->flags |= MOD_CALLOUT;
	    } else {
		/*
		 * add new callout
		 */
		handle = data->ncallouts;
		co = data->callouts = REALLOC(data->callouts, dcallout, handle,
					      handle + 1);
		co += handle;
		data->ncallouts = ++handle;
		data->plane->flags |= MOD_NEWCALLOUT;
	    }
	}
    }

    co->time = time;
    co->mtime = mtime;
    co->nargs = nargs;
    memcpy(co->val, v, sizeof(co->val));
    switch (nargs) {
    default:
	ref_rhs(data, &v[3]);
    case 2:
	ref_rhs(data, &v[2]);
    case 1:
	ref_rhs(data, &v[1]);
    case 0:
	ref_rhs(data, &v[0]);
	break;
    }

    return handle;
}
Esempio n. 30
0
static DWORD unzlocal_SearchCentralDir(const zlib_filefunc_def *pzlib_filefunc_def, void *filestream)
{
  BYTE *buf;
  DWORD uSizeFile;
  DWORD uBackRead;
  DWORD uMaxBack = 0xffff; /* maximum size of global comment */
  DWORD uPosFound = 0;

  if (ZSEEK(*pzlib_filefunc_def, filestream, 0, SEEK_END) != 0)
  {
    return 0;
  }


  uSizeFile = ZTELL(*pzlib_filefunc_def, filestream);

  if (uMaxBack > uSizeFile)
  {
    uMaxBack = uSizeFile;
  }

  buf = (BYTE*)ALLOC(BUFREADCOMMENT + 4);
  if (buf == NULL)
  {
    return 0;
  }

  uBackRead = 4;
  while (uBackRead < uMaxBack)
  {
    DWORD uReadSize, uReadPos;
    int i;
    if (uBackRead + BUFREADCOMMENT > uMaxBack)
    {
      uBackRead = uMaxBack;
    }
    else
    {
      uBackRead += BUFREADCOMMENT;
    }
    uReadPos = uSizeFile - uBackRead;

    uReadSize = ((BUFREADCOMMENT + 4) < (uSizeFile - uReadPos)) ? (BUFREADCOMMENT + 4): (uSizeFile - uReadPos);
    if (ZSEEK(*pzlib_filefunc_def, filestream, uReadPos, SEEK_SET) != 0)
    {
      break;
    }

    if (ZREAD(*pzlib_filefunc_def, filestream, buf, uReadSize) != uReadSize)
    {
      break;
    }

    for (i = (int)uReadSize - 3; (i--) > 0;)
    if (((*(buf + i)) == 0x50) && ((*(buf + i + 1)) == 0x4b) && ((*(buf + i + 2)) == 0x05) && ((*(buf + i + 3)) == 0x06))
    {
      uPosFound = uReadPos + i;
      break;
    }

    if (uPosFound != 0)
    {
      break;
    }
  }
  TRYFREE(buf);
  return uPosFound;
}