void RNDEND_load_assets(void)
{
   rndend_win_gfx   = COMMON_load_texture(WIN_GFX_PATH);
   rndend_loss_gfx  = COMMON_load_texture(LOSS_GFX_PATH);

    if (exists(WIN_CHIME_PATH))
        rndend_win_chime = load_sample(WIN_CHIME_PATH);
    else
    {
        rndend_win_chime = create_sample(8, 0, 1, 1);
        OH_SMEG("missing sound: %s", WIN_CHIME_PATH);
    }

    if (exists(LOSS_CHIME_PATH))
        rndend_loss_chime = load_sample(LOSS_CHIME_PATH);
    else
    {
        rndend_loss_chime = create_sample(8, 0, 1, 1);
        OH_SMEG("missing sound: %s", LOSS_CHIME_PATH);
    }

   RNDEND_reset();

   rndend_uv_tmp[0].u = 0.0f;
   rndend_uv_tmp[0].v = 0.0f;

   rndend_uv_tmp[1].u = 1.0f;
   rndend_uv_tmp[1].v = 0.0f;

   rndend_uv_tmp[2].u = 1.0f;
   rndend_uv_tmp[2].v = 1.0f;

   rndend_uv_tmp[3].u = 0.0f;
   rndend_uv_tmp[3].v = 1.0f;
}
Exemplo n.º 2
0
int main(int argc, char **argv)
{
    Database *db = create_sample();

    check(argc == 3, "usage: %s <csvfile> <defindex>", argv[0]);

    char *csv_file = argv[1];
    int def_idx = atoi(argv[2]);

    check(def_idx < db->def_size, "unknown def index: %d", def_idx);

    FILE* stream = fopen(csv_file, "r");
    char line[1024];

    while (fgets(line, 1024, stream)) {
        char *tmp = strdup(line);
        Record *record = parse_line(tmp, db->record_ds[def_idx], def_idx);
        free(tmp);

        Database_push(db, record);
        Record_destroy(record);
    }

    fclose(stream);

    Database_print(db);
    Database_destroy(db);

    return 0;

error:
    return 1;
}
Exemplo n.º 3
0
void sinsp_table::flush(sinsp_evt* evt)
{	
	if(!m_paused)
	{
		if(m_next_flush_time_ns != 0)
		{
			//
			// Time to emit the sample! 
			// Add the proctable as a sample at the end of the second
			//
			process_proctable(evt);

			//
			// If there is a merging step, switch the types to point to the merging ones.
			//
			if(m_do_merging)
			{
				m_types = &m_postmerge_types;
				m_table = &m_merge_table;
				m_n_fields = m_n_postmerge_fields;
				m_vals_array_sz = m_postmerge_vals_array_sz;
				m_fld_pointers = m_postmerge_fld_pointers;
				m_extractors = &m_postmerge_extractors;
			}

			//
			// Emit the sample
			//
			create_sample();

			if(m_type == sinsp_table::TT_TABLE)
			{
				//
				// Switch the data storage so that the current one is still usable by the 
				// consumers of the table.
				//
				switch_buffers();

				//
				// Clear the current data storage
				//
				m_buffer->clear();
			}

			//
			// Reinitialize the tables
			//
			m_premerge_table.clear();
			m_merge_table.clear();
		}
	}

	uint64_t ts = evt->get_ts();

	m_prev_flush_time_ns = m_next_flush_time_ns;
	m_next_flush_time_ns = ts - (ts % m_refresh_interval_ns) + m_refresh_interval_ns;

	return;
}
Exemplo n.º 4
0
SAMPLE *alogg_create_sample_from_ogg(ALOGG_OGG *ogg) {
  SAMPLE *sample;
  char *data;
  int i, sample_len_bytes, sample_len, size_done, done;

  /* first we need to calculate the len of the sample in bytes */
  sample_len = ov_pcm_total(&(ogg->vf), -1);
  sample_len_bytes = (sample_len * (ogg->stereo ? 2 : 1)) * 2; /* / 2 = 16 bits */
  
  /* create the sample */
  sample = create_sample(16, ogg->stereo, ogg->freq, sample_len);

  /* return NULL if we were not able to allocate the memory for it */
  if (sample == NULL)
    return NULL;

  /* we need to stop and rewind the ogg */
  alogg_stop_ogg(ogg);
  alogg_rewind_ogg(ogg);

  /* set our pointer */
  data = (char *)sample->data;
  /* clear the sample buffer in unsigned format */
  {
    int i;
    unsigned short *j = (unsigned short *)data;
    for (i = 0; i < (sample_len_bytes / 2); i++, j++)
      *j = 0x8000;
  }

  /* decode */
  done = FALSE;
  size_done = 0;
  for (i = sample_len_bytes; !done && (i > 0); i -= size_done) {

    /* decode */
    size_done = ov_read(&(ogg->vf), data, i, 0, 2, 0, &(ogg->current_section));

    /* check if the decoding was not successful */
    if (size_done < 0) {
      if (size_done == OV_HOLE)
        size_done = 0;
      else {
        alogg_rewind_ogg(ogg);
        destroy_sample(sample);
        return NULL;
      }
    }
    else if (size_done == 0)
      done = TRUE;

    data += size_done;
  }

  alogg_rewind_ogg(ogg);

  return sample;
}
Exemplo n.º 5
0
/* the metapopulation. */
struct sample * draw_sample(struct metapopulation *in, int n, struct param *par){
	int i, j, *nIsolatesPerPop, count;
	double *nAvailPerPop;
	struct pathogen *ppat;

	/* create pointer to pathogens */
	struct sample *out=create_sample(n);

	/* escape if no isolate available */
	if(get_total_ninf(in) + get_total_nexp(in) < 1){
		printf("\nMetapopulation without infections - sample will be empty.\n");
		out->n = 0;
		out->pathogens = NULL;
		out->popid = NULL;
		return out;
	}

	/* get nb of isolates available in each population */
	nAvailPerPop = (double *) calloc(get_npop(in), sizeof(double));
	if(nAvailPerPop == NULL){
		fprintf(stderr, "\n[in: population.c->draw_sample]\nNo memory left to isolate available pathogens. Exiting.\n");
		exit(1);
	}

	for(j=0;j<get_npop(in);j++){
		nAvailPerPop[j] = (double) get_nexp(get_populations(in)[j]) + get_ninf(get_populations(in)[j]);
	}

	/* get nb of isolates sampled in each population*/
	nIsolatesPerPop = (int *) calloc(get_npop(in), sizeof(int));
	if(nIsolatesPerPop == NULL){
		fprintf(stderr, "\n[in: population.c->draw_sample]\nNo memory left to isolate available pathogens. Exiting.\n");
		exit(1);
	}

	gsl_ran_multinomial(par->rng, get_npop(in), n, nAvailPerPop, (unsigned int *) nIsolatesPerPop);

	/* fill in the sample pathogens */
	count = 0;
	for(j=0;j<get_npop(in);j++){ /* for each population */
		for(i=0;i<nIsolatesPerPop[j];i++){
			ppat = select_random_pathogen(get_populations(in)[j], par);
			/* free_pathogen(out->pathogens[count]); */
			out->pathogens[count] = reconstruct_genome(ppat);
			out->popid[count++] = j;
		}
	}

	/* free local pointers */
	free(nAvailPerPop);
	free(nIsolatesPerPop);

	return out;
} /* end draw_sample */
Exemplo n.º 6
0
int
main(void)
{
	create_sample();
	test_flock();
	test_flock64();
#ifdef TEST_F_OWNER_EX
	test_f_owner_ex();
#endif

	puts("+++ exited with 0 +++");
	return 0;
}
Exemplo n.º 7
0
SAMPLE * create_silence_sample(unsigned long ms)
{
	SAMPLE * sp = NULL;
	int bits;
	int stereo;
	int freq;
	unsigned long samples, i;
	unsigned channels;

	eof_log("create_silence_sample() entered", 1);

	if(eof_music_track)
	{
		bits = alogg_get_wave_bits_ogg(eof_music_track);
		stereo = alogg_get_wave_is_stereo_ogg(eof_music_track);
		freq = alogg_get_wave_freq_ogg(eof_music_track);
		samples = msec_to_samples(ms);
		channels = stereo ? 2 : 1;
	}
	else
	{
		bits = 16;
		stereo = 1;
		freq = 44100;
		samples = (double)(ms * freq) / 1000.0;
		channels = 2;
	}

	sp = create_sample(bits, stereo, freq, samples);
	if(!sp)
		return NULL;	//Return error

	if(bits == 8)
	{
		for(i = 0; i < samples * channels; i++)
		{
			((unsigned char *)(sp->data))[i] = 0x80;
		}
	}
	else
	{
		for(i = 0; i < samples * channels; i++)
		{
			((unsigned short *)(sp->data))[i] = 0x8000;
		}
	}

	return sp;
}
Exemplo n.º 8
0
+=j!=I&&i!=J&&i!=I&&j!=J&&*c(I,J)&&q(p(i),p(j),p(I),p(J));return f;}main(){int i
,I,j,J,f,F,a,b,s=-1,X,Y,H,h;BITMAP*B;SAMPLE*S;allegro_init();*c(0,1)=*c(0,2)=*c(
0,3)=1;set_gfx_mode(GFX_AUTODETECT_WINDOWED,w,w,0,0);install_sound(DIGI_DIRECTX(
0),MIDI_NONE,0);B=create_bitmap(w,w);install_keyboard();install_mouse();*c(2,3)=
*c(1,2)=*c(1,3)=1;text_mode(-1);S=create_sample(8,0,9999,9999);for(i=0;i<9999;i
++){((unsigned char*)S->data)[i]=(((i+(fixsin(i<<13)>>13))%100+(i)%152)*i)/9000;
}for(l=4;l<99;l++){play_sample(S,255,55,1600,0);play_sample(S,255,200,1604,0);
for(i=0;i<l;i++){x[i]=((fixcos((i<<24)/l)*w/3)>>16)+w/2;y[i]=((fixsin((i<<24)/l)
*w/3)>>16)+w/2;}do{F=0;key[KEY_ESC]?exit(0):0;clear_to_color(B,15);for(i=0;i<l;i
++){for(j=0;j<l;j++){f=0;if(*c(j,i)){f=M(i,j);for(a=-1;a<2;a++)for(b=-1;b<2;b++)
line(B,a+p(i)+b,a+p(j)+b,f?12:10);}F|=f;}}for(i=0;i<l;i++){circlefill(B,p(i),8,0
);circlefill(B,p(i),6,s==i?7:8);s=mouse_b?s:-1;if(mouse_b&&s<0&&_(mouse_x-x[i],-
7,7)&&_(mouse_y-y[i],-7,7))s=i;}if(s>=0){x[s]=mouse_x;y[s]=mouse_y;}textprintf(B
,font,10,10,0,"Level %d",l-3);draw_sprite(B,mouse_sprite,mouse_x,mouse_y);blit(B
,screen,0,0,0,0,w,w);}while(F||mouse_b);H=0;for(j=0;j<2000;j++){h=0;x[l]=rand()%
w*2-w/2;y[l]=rand()%w*2-w/2;for(i=0;i<l;i++){h+=M(i,l)==0;}if(h>H){H=h;X=x[l];Y=
y[l];}}x[l]=X;y[l]=Y;for(i=0;i<l;i++){*c(i,l)=M(i,l)==0;*c(rand()%l,rand()%l)=0;
}}}END_OF_MAIN();///////////////////////////////////////////////////////////////
Exemplo n.º 9
0
/* merge several samples together */
struct sample * merge_samples(struct sample **in, int nsamp, struct param *par){
	int i, j, newsize=0, counter=0;


	/* create output */
	for(i=0;i<nsamp;i++) newsize += get_n(in[i]);
	struct sample * out = create_sample(newsize);

	/* fill in output */
	for(i=0;i<nsamp;i++){
		for(j=0;j<get_n(in[i]);j++){
			out->pathogens[counter] = copy_pathogen(in[i]->pathogens[j]);
			out->popid[counter++] = in[i]->popid[j];
		}
	}

	out->n = newsize;
	return out;
}
Exemplo n.º 10
0
QVector<QVector<double> > createMatrix(int k, int n, double m, double g, QVector<double> trend_mean,
                                       QVector<double> trend_s)
{
    QVector<QVector<double> > matrix;
    if((trend_mean.size()!=2)||(trend_s.size()!=2))
    {
        qDebug() << "uncorrect number trend parametr";
        return matrix;
    }

    double mi, gi;
    for(int i = 0; i<k; i++)
    {
        mi = m + trend_mean[0]*i + trend_mean[1]*i*i;
        gi = g + trend_s[0]*i + trend_s[1]*i*i;
        matrix.push_back(create_sample(n,mi,gi,i));
    }
    return matrix;
}
Exemplo n.º 11
0
/* (`allegro_init()' is already defined by Allegro itself.)  */
static int allegro_init_sound(const char *param, int *speed,
                              int *fragsize, int *fragnr, int *channels)
{
    unsigned int i;

    /* No stereo capability. */
    *channels = 1;

    if (allegro_startup(*speed) < 0)
        return 1;

    fragment_size = *fragsize * sizeof(SWORD);

    buffer_len = fragment_size * *fragnr;
    buffer = create_sample(16, 0, *speed, buffer_len / sizeof(SWORD));

    for (i = 0; i < buffer_len / 2; i++)
        *((WORD *)buffer->data + i) = 0x8000;

    voice = allocate_voice(buffer);
    if (voice < 0) {
        log_debug("Cannot allocate Allegro voice!\n");
        destroy_sample(buffer);
        return 1;
    }

    buffer_offset = 0;
    been_suspended = 1;
    written_samples = 0;

    voice_set_playmode(voice, PLAYMODE_LOOP);
    voice_set_volume(voice, 255);
    voice_set_pan(voice, 128);

    return 0;
}
Exemplo n.º 12
0
int main(int argc, const char *argv[])
{
    if (create_sample(1,1000))
        printf("write sample succeful\n");
    return 0;
}
Exemplo n.º 13
0
static SAMPLE *load_ov(OggVorbis_File *vf)
{
  int ret;
  vorbis_info *info;
  SAMPLE *sample=NULL;
  ogg_int64_t num_samples;
  size_t offset;
  AL_CONST size_t max_read=4096;
  size_t buffer_size;
  size_t buffer_inc=65536;
  int stereo;

  info=ov_info(vf,-1);
  if (!info) {
    TRACE("ov_info failed\n");
    goto load_error_file;
  }
  stereo=(info->channels>1);

  num_samples=ov_pcm_total(vf,-1);
  TRACE("ov_pcm_total says %lld samples\n",num_samples);
  if (num_samples<0) {
    TRACE("ov_pcm_total failed: %lld - not fatal\n",(ogg_int64_t)num_samples);
  }
  TRACE(
    "ov_load: create sample: %d bits, %d channels (%s), %ld Hz, %lld samples\n",
    16,info->channels,stereo?"stereo":"mono",info->rate,num_samples
  );
  sample=create_sample(16,stereo,info->rate,num_samples>0?num_samples:1);
  if (!sample) {
    TRACE(
      "Failed creating a sample (%d channels, %ld Hz, %u samples",
      info->channels,info->rate,(size_t)num_samples
    );
    goto load_error_file;
  }

  /* decode the encoded data */
  for (offset=0,buffer_size=0;;) {
    if (num_samples<0) {
      /* If we could not determine the size of the sample, allocate as we go */
      if (offset+max_read>buffer_size) {
        TRACE("Buffer too small: adding %u bytes\n",buffer_inc);
        buffer_size+=buffer_inc;
        buffer_inc+=buffer_inc/2;
#ifdef FORTIFY
        {
          /* Fortify won't have seen the allocation which was done in Allegro */
          void *tmpdata=malloc(buffer_size);
          memcpy(tmpdata,sample->data,offset);
          destroy_sample(sample);
          sample=create_sample(16,stereo,info->rate,buffer_size/(stereo?2:1)/2);
          memcpy(sample->data,tmpdata,offset);
          free(tmpdata);
        }
#else
        sample->data=realloc(sample->data,buffer_size);
#endif
      }
      if (!sample->data) {
        TRACE("Failed allocating sample data\n");
        goto load_error_sample;
      }
    }
    ret=read_ogg_data(vf,((char*)sample->data)+offset,max_read,2,0,NULL);
    if (ret==0) break;
    if (ret<0) {
      TRACE("read_ogg_data failed: %d\n",ret);
      alogg_error_code=ret;
      goto load_error_sample;
    }
    offset+=ret;
  }
  TRACE("ov_load: clearing\n");
  ov_clear(vf);
  /* ov_clear will have closed the PACKFILE, so no need to do it there */

  /* If we couldn't allocate up front, update the size related fields */
  if (num_samples<0) {
    ASSERT(offset%(stereo?2:1)/2==0);
    sample->len=offset/(stereo?2:1)/2;
    TRACE("Final size: %lu samples\n",sample->len);
    sample->loop_end=sample->len;
    lock_sample(sample);
  }

  return sample;

load_error_sample:
  destroy_sample(sample);
load_error_file:
  ov_clear(vf);
  return NULL;
}
Exemplo n.º 14
0
DATASET *read_seq_file(
  char *file_name,		/* name of file to open */
  char *alpha,			/* alphabet used in sequences */
  BOOLEAN use_comp,		/* use complementary strands, too */
  double seqfrac 		/* fraction of input sequences to use */
)
{
  int i, j;
  FILE *data_file;		/* file with samples to read */
  FILE *prior_file=NULL;	/* file with positional priors to read */
  char *sample_name;		/* name of sample read */
  char *sample_de;		/* descriptor text for sample */
  char *sequence;		/* sequence read */
  long length;			/* length of sequence */
  BOOLEAN error=FALSE;		/* none yet */
  SAMPLE *sample;		/* sample created */
  DATASET *dataset;		/* dataset created */
  int n_samples=0;		/* number of samples read */
  double *seq_weights=NULL;	/* sequence weights */
  int n_wgts=0;			/* number of sequence weights given */

  /* create a hash table of sequence names */
  if (!ht_seq_names) ht_seq_names = hash_create(DATA_HASH_SIZE);

  /* create a dataset */
  dataset = (DATASET *) mymalloc(sizeof(DATASET));
  dataset->alength = strlen(alpha);
  dataset->alphabet = alpha;
  dataset->psp_w = 0;			// indicates no PSP was read
  dataset->log_psp_w = 0;		// so log_psp will get initialized

  /* open data file */
  if (file_name == NULL) {
    fprintf(stderr, "You must specify a data file or `stdin'.\n");
    exit(1);
  } else if (strcmp(file_name, "stdin")) {
    data_file = fopen(file_name, "r"); 
    if (data_file == NULL) {
      fprintf(stderr, "Cannot open file `%s'.\n", file_name);
      exit(1);
    }
  } else {
    data_file = stdin;
  }

  /* initialize maximum length of sequences */
  dataset->max_slength = 0;
  dataset->min_slength = 10000000;

  dataset->n_samples = 0;	/* no samples yet */
  dataset->samples = NULL;	/* no samples */

  while (read_sequence(data_file, &sample_name, &sample_de, &sequence, 
    &length)) {

    /* skip sequence if an error occurred */
    if (length < 0) continue;

    /* parse weights if given; make (more than enough) room in array */
    if (strcmp(sample_name, "WEIGHTS")==0) {
      double wgt; 
      char *wgt_str = sample_de;
      Resize(seq_weights, n_wgts+(int)strlen(wgt_str), double);
      while (sscanf(wgt_str, "%lf", &wgt) == 1) {
        if (wgt <= 0 || wgt > 1) {
	  fprintf(stderr, 
            "Weights must be larger than zero and no greater than 1.\n");
	  exit(1);
        }
        seq_weights[n_wgts++] = wgt;			/* save weight */
        wgt_str += strspn(wgt_str, "      ");		/* skip white */
        wgt_str += strcspn(wgt_str, "     ");		/* skip token */
      }
      myfree(sample_name);
      myfree(sample_de);
      myfree(sequence);
      continue;
    }

    /* ignore duplicate (same sample name) sequences */ 
    if (hash_lookup_str(sample_name, ht_seq_names) != NULL) {
      fprintf(stderr, "Skipping sequence '%s'.\n", sample_name);
      myfree(sample_name);
      myfree(sample_de);
      myfree(sequence);
      continue;
    }
    hash_insert_str(sample_name, ht_seq_names);  /* put name in hash table */

    n_samples++;

    /* see if sequence will be used in random sample; store it if yes */
    if (drand48() >= 1 - seqfrac) {

      HASH_TABLE_ENTRY *hash_entry; // needed to add pointer to sample

      /* create the sample */
      sample = create_sample(alpha, length, sample_name, sequence, sample_de, use_comp);
      if (sample == NULL) {error = TRUE; continue;}

      /* record maximum length of actual sequences */
      dataset->max_slength = MAX(sample->length, dataset->max_slength);
      dataset->min_slength = MIN(sample->length, dataset->min_slength);

      /* put the sample in the array of samples */
      if ((dataset->n_samples % RCHUNK) == 0) {
        Resize(dataset->samples, dataset->n_samples + RCHUNK, SAMPLE *);
      }
Exemplo n.º 15
0
int save_wav_with_silence_appended(const char * fn, SAMPLE * sp, unsigned long ms)
{
	unsigned long i, samples, channels, index = 0;
	SAMPLE * silence, * combined;
	int retval;

 	eof_log("save_wav_with_silence_appended() entered", 1);

	if(!fn || !sp)
		return 0;	//Invalid parameters

	if(!ms)
	{	//If the calling function specified writing the WAV with no silence appended
		return save_wav(fn, sp);	//Write the audio normally
	}

	//Generate the silent audio to conform to the input sample's specifications
	samples = (double)ms * (double)sp->freq / 1000.0;
	channels = sp->stereo ? 2 : 1;
	silence = create_sample(sp->bits, sp->stereo, sp->freq, samples);
	if(!silence)
		return 0;	//Return failure
	if(sp->bits == 8)
	{
		for(i = 0; i < samples * channels; i++)
		{
			((unsigned char *)(silence->data))[i] = 0x80;
		}
	}
	else
	{
		for(i = 0; i < samples * channels; i++)
		{
			((unsigned short *)(silence->data))[i] = 0x8000;
		}
	}

	//Combine the input audio and silence
	combined = create_sample(sp->bits, sp->stereo, sp->freq, sp->len + samples);
	if(!combined)
	{
		free(silence);
		return 0;	//Return failure
	}
	if(sp->bits == 8)
	{
		for(i = 0; i < sp->len * channels; i++)
		{	//For each sample in the input audio
			((unsigned char *)(combined->data))[index++] = ((unsigned char *)(sp->data))[i];	//Copy it into the combined audio sample
		}
		for(i = 0; i < silence->len * channels; i++)
		{	//For each sample in the silent audio
			((unsigned char *)(combined->data))[index++] = ((unsigned char *)(silence->data))[i];	//Copy it into the combined audio sample
		}
	}
	else
	{
		for(i = 0; i < sp->len * channels; i++)
		{	//For each sample in the input audio
			((unsigned short *)(combined->data))[index++] = ((unsigned short *)(sp->data))[i];	//Copy it into the combined audio sample
		}
		for(i = 0; i < silence->len * channels; i++)
		{	//For each sample in the silent audio
			((unsigned short *)(combined->data))[index++] = ((unsigned short *)(silence->data))[i];	//Copy it into the combined audio sample
		}
	}

	//Write the combined audio to file and return
	retval = save_wav(fn, combined);	//Write the combined audio
	destroy_sample(combined);
	destroy_sample(silence);
	return retval;
}
Exemplo n.º 16
0
int osd_start_audio_stream(int stereo)
{
#ifdef USE_SEAL
	int channel;
#endif

	if (stereo) stereo = 1;	/* make sure it's either 0 or 1 */

	stream_cache_stereo = stereo;

	/* determine the number of samples per frame */
	samples_per_frame = (double)Machine->sample_rate / (double)Machine->drv->frames_per_second;

	/* compute how many samples to generate this frame */
	samples_left_over = samples_per_frame;
	samples_this_frame = (UINT32)samples_left_over;
	samples_left_over -= (double)samples_this_frame;

	audio_buffer_length = NUM_BUFFERS * samples_per_frame + 20;


	if (Machine->sample_rate == 0) return 0;

#ifdef USE_SEAL
	for (channel = 0;channel <= stereo;channel++)
	{
		if (ACreateAudioVoice(&hVoice[channel]) != AUDIO_ERROR_NONE)
			return 0;

		if ((lpWave[channel] = (LPAUDIOWAVE)malloc(sizeof(AUDIOWAVE))) == 0)
		{
			ADestroyAudioVoice(hVoice[channel]);
			return 0;
		}

		lpWave[channel]->wFormat = AUDIO_FORMAT_16BITS | AUDIO_FORMAT_MONO | AUDIO_FORMAT_LOOP;
		lpWave[channel]->nSampleRate = nominal_sample_rate;
		lpWave[channel]->dwLength = 2*audio_buffer_length;
		lpWave[channel]->dwLoopStart = 0;
		lpWave[channel]->dwLoopEnd = lpWave[channel]->dwLength;
		if (ACreateAudioData(lpWave[channel]) != AUDIO_ERROR_NONE)
		{
			free(lpWave[channel]);
			lpWave[channel] = 0;

			return 0;
		}

		memset(lpWave[channel]->lpData,0,lpWave[channel]->dwLength);
		APrimeVoice(hVoice[channel],lpWave[channel]);
		ASetVoiceFrequency(hVoice[channel],nominal_sample_rate);
	}

	if (stereo)
	{
		/* SEAL doubles volume for panned channels, so we have to compensate */
		ASetVoiceVolume(hVoice[0],32);
		ASetVoiceVolume(hVoice[1],32);

		ASetVoicePanning(hVoice[0],0);
		ASetVoicePanning(hVoice[1],255);

		AStartVoice(hVoice[0]);
		AStartVoice(hVoice[1]);
	}
	else
	{
		ASetVoiceVolume(hVoice[0],64);
		ASetVoicePanning(hVoice[0],128);
		AStartVoice(hVoice[0]);
	}
#endif

#ifdef USE_ALLEGRO
	mysample = create_sample(16,stereo,nominal_sample_rate,audio_buffer_length);
	if (mysample == 0) return 0;
	myvoice = allocate_voice(mysample);
	voice_set_playmode(myvoice,PLAYMODE_LOOP);
	if (stereo)
	{
		INT16 *buf = mysample->data;
		int p = 0;
		while (p != audio_buffer_length)
		{
			buf[2*p] = (INT16)0x8000;
			buf[2*p+1] = (INT16)0x8000;
			p++;
		}
	}
	else
	{
		INT16 *buf = mysample->data;
		int p = 0;
		while (p != audio_buffer_length)
		{
			buf[p] = (INT16)0x8000;
			p++;
		}
	}
	voice_start(myvoice);
#endif

	stream_playing = 1;
	voice_pos = 0;

	return samples_this_frame;
}
Exemplo n.º 17
0
/* creates a new sample object */
static void *makenew_sample(long *size)
{
   return create_sample(8, FALSE, 11025, 1024);
}
Exemplo n.º 18
0
extern DATASET *read_seq_file(
  AjPSeqall seqa,		/* name of file to open */
  char *alpha,			/* alphabet used in sequences */
  BOOLEAN use_comp,		/* use complementary strands, too */
  double seqfrac		/* fraction of input sequences to use */
)
{
  int i, j, pcol;
  /*FILE *data_file;*/		/* file with samples to read */
  char *sample_name;		/* name of sample read */
  char *sample_de;		/* descriptor text for sample */
  char *sequence;		/* sequence read */
  int length;			/* length of sequence */
  BOOLEAN error=FALSE;		/* none yet */
  SAMPLE *sample;		/* sample created */
  DATASET *dataset;		/* dataset created */
  int n_samples=0;		/* number of samples read */
  double *seq_weights=NULL;	/* sequence weights */
  int n_wgts=0;			/* number of sequence weights given */

  /* create a hash table of sequence names */
  if (!ht_seq_names) ht_seq_names = hash_create(DATA_HASH_SIZE);

  /* create a dataset */
  dataset = (DATASET *) malloc(sizeof(DATASET));
  dataset->alength = strlen(alpha);
  dataset->alphabet = alpha;
  dataset->pal = 0;		/* not looking for palindromes */


  /* initialize maximum length of sequences */
  dataset->max_slength = 0;
  dataset->min_slength = 10000000;

  dataset->n_samples = 0;	/* no samples yet */
  dataset->samples = NULL;	/* no samples */

  while (read_sequence(seqa, &sample_name, &sample_de, &sequence, 
    &length)) {

    /* skip sequence if an error occurred */
    if (length < 0) continue;

    /* parse weights if given; make (more than enough) room in array */
    if (strcmp(sample_name, "WEIGHTS")==0) {
      double wgt; 
      char *wgt_str = sample_de;
      Resize(seq_weights, n_wgts+strlen(wgt_str), double);
      while (sscanf(wgt_str, "%lf", &wgt) == 1) {
        if (wgt <= 0 || wgt > 1) {
	  fprintf(stderr, 
            "Weights must be larger than zero and no greater than 1.\n");
	  exit(1);
        }
        seq_weights[n_wgts++] = wgt;			/* save weight */
        wgt_str += strspn(wgt_str, "      ");		/* skip white */
        wgt_str += strcspn(wgt_str, "     ");		/* skip token */
      }
      myfree(sample_name);
      myfree(sample_de);
      myfree(sequence);
      continue;
    }

    /* ignore duplicate (same sample name) sequences */ 
    if (hash_lookup(sample_name, 0, ht_seq_names)) {
      fprintf(stderr, "Skipping %s\n", sample_name);
      myfree(sample_name);
      myfree(sample_de);
      myfree(sequence);
      continue;
    }
    hash_insert(sample_name, 0, ht_seq_names);  /* put name in hash table */

    n_samples++;

    /* see if sequence will be used in random sample; store it if yes */
    if (drand48() >= 1 - seqfrac) {

      /* create the sample */
      sample = create_sample(alpha, length, sample_name, sequence);
      if (sample == NULL) {error = TRUE; continue;}

      /* record maximum length of actual sequences */
      dataset->max_slength = MAX(sample->length, dataset->max_slength);
      dataset->min_slength = MIN(sample->length, dataset->min_slength);

      /* put the sample in the array of samples */
      if ((dataset->n_samples % RCHUNK) == 0) {
        Resize(dataset->samples, dataset->n_samples + RCHUNK, SAMPLE *);
      }
Exemplo n.º 19
0
ConfigurationSet *Sampler::get_sample() const {
  IMPKERNEL_DEPRECATED_METHOD_DEF(2.1, "Use create_sample instead");
  return create_sample();
}
Exemplo n.º 20
0
int main() 
	{
         
           
        
	    int audio, working_format, bitcap,stereocap,ratecap;
	  int ofs = 0;
	    int len;
	    int interval;
	  SAMPLE *sample;
	    int foo;
	    int size = 1024*1024;
	    unsigned char *buf;
	    init();
	       show_mouse(screen);
	  bitcap = get_sound_input_cap_bits();
	    if (bitcap == 0) 
	        allegro_message("No Audio input capabilty?");
	    stereocap = get_sound_input_cap_stereo();
	  if (stereocap == 0) 
	    allegro_message("No Sterecordingreo ");
	    ratecap = get_sound_input_cap_rate(bitcap, 0);
	    working_format = get_sound_input_cap_parm(ratecap, bitcap, 0);
	    if (working_format == 0) 
	        allegro_message("We Are not a go!"); 
	    else if (working_format == 1) 
	    allegro_message("We Are a go but can't record and playback at the same time!");
	    else if (working_format == 2) 
	    allegro_message("We Are a go!");
	    BITMAP *catli=NULL,*catmo=NULL,*catmc=NULL;
	    catli=load_bitmap("listen.bmp",NULL);
	    catmo=load_bitmap("mo.bmp",NULL);
	    catmc=load_bitmap("mc.bmp",NULL);
	  
	    sample = create_sample(bitcap, 0, ratecap, size);
	    buf=(unsigned char*)(sample->data);

	    allegro_message("Start Recording");
	    len = start_sound_input(ratecap, 16, 0);
	     masked_blit(catli,screen,0,0,200,50,500,500);
	    
	    interval = 1000 / ((len / 2) / ratecap);
	    
	    interval *= 9;
	    interval /= 10;
 	  
	    
	   
	    while (!keypressed() && ofs < size) 
	    {
	        foo = read_sound_input(buf);        
	        if (foo > 0) 
	        {
	            ofs += len;
	            buf += len;
	        }
	        rest(interval);
	    }
	 if (keypressed()) 
	    {
	        foo = read_sound_input(buf);        
	        if (foo > 0) 
	        {
	            ofs += len;
	            buf += len;
	        }
	    }
	    
	   
       	    stop_sound_input();
	     BITMAP *bit=NULL,*bit2=NULL;
	    bit=load_bitmap("play.bmp",NULL);
	   masked_blit(bit,screen,0,0,100,100,400,400);
bit2=load_bitmap("pause.bmp",NULL);
	   masked_blit(bit2,screen,0,0,100,200,400,400);
	audio= allocate_voice(sample);
int u=0;
	  while (!key[KEY_ESC]) {
          	if((mouse_x>=100 && mouse_x<=200)&&(mouse_y>=100 && mouse_y<=200)&& mouse_b&0x1)
	{ play_sample(sample,255,128,1400,0);
         //voice_start(audio);
           while(!((mouse_x>=100 && mouse_x<=200)&&(mouse_y>=200 && mouse_y<=300)&& mouse_b&0x1u<=10)&& u<size)
          { masked_blit(catmo,screen,0,0,200,100,500,500);
            rest(300);
             masked_blit(catmc,screen,0,0,200,100,500,500);
             rest(300);
             u++;
             }
}
    if((mouse_x>=100 && mouse_x<=200)&&(mouse_y>=200 && mouse_y<=300)&& mouse_b&0x1)
	  {
                     voice_stop(audio);
                      masked_blit(catmc,screen,0,0,200,100,500,500);}
    /* put your code here */
	  }
	 
	  deinit();
	  return 0;
	}
Exemplo n.º 21
0
int _apeg_audio_reset_parameters(APEG_LAYER *layer)
{
	int buffer_padding;

	_apeg_audio_close(layer);

	if(layer->stream.audio.freq <= 0)
	{
		snprintf(apeg_error, sizeof(apeg_error), "Illegal audio frequency (%dhz)",
		         layer->stream.audio.freq);
		return APEG_ERROR;
	}
	if(layer->stream.audio.channels <= 0)
	{
		snprintf(apeg_error, sizeof(apeg_error), "Illegal channel count (%d)",
		         layer->stream.audio.channels);
		return APEG_ERROR;
	}

	buffer_padding = 0;
#ifndef DISABLE_MPEG_AUDIO
	if(layer->stream.audio.layer == 3)
		buffer_padding = (128>>layer->stream.audio.down_sample) * SSLIMIT *
		                 layer->stream.audio.channels;
	if(layer->stream.audio.layer == 2)
		buffer_padding = (128>>layer->stream.audio.down_sample) * 3 *
		                 layer->stream.audio.channels;
	if(layer->stream.audio.layer == 1)
		buffer_padding = (128>>layer->stream.audio.down_sample) * SCALE_BLOCK *
		                 layer->stream.audio.channels;
#endif

	if(layer->audio.callback_init)
	{
		int channels = layer->stream.audio.channels;
		int freq = layer->stream.audio.freq;
		int ret;

		ret = layer->audio.callback_init((APEG_STREAM*)layer, &channels, &freq,
		                                 layer->audio.callback_arg);
		if(ret < 0)
		{
			snprintf(apeg_error, sizeof(apeg_error), "Audio callback init failed (code: %d)", ret);
			return APEG_ERROR;
		}

		if(channels > layer->stream.audio.channels || channels <= 0 ||
		   freq <= 0)
		{
			snprintf(apeg_error, sizeof(apeg_error), "Illegal audio mode requested (%dhz %d channels)",
			         freq, channels);
			return APEG_ERROR;
		}

		if(ret > 0)
			layer->audio.bufsize = (ret+255)&(~255);

		free(layer->audio.pcm.samples);
		layer->audio.pcm.samples = malloc(layer->audio.bufsize+buffer_padding);
		if(!layer->audio.pcm.samples)
		{
			snprintf(apeg_error, sizeof(apeg_error), "Error allocating %d bytes for audio buffer",
			         layer->audio.bufsize+buffer_padding);
			return APEG_ERROR;
		}

		if(channels == 1 && layer->stream.audio.channels > 1)
			layer->stream.audio.down_channel = TRUE;

		layer->stream.audio.channels = channels;
		layer->stream.audio.freq = freq;

		layer->audio.samples_per_update = layer->audio.bufsize / 2 /
		                                  layer->stream.audio.channels;

		layer->audio.last_pos = -1;
		layer->audio.pos = -layer->audio.samples_per_update*2;

		return APEG_OK;
	}

	free(layer->audio.pcm.samples);
	layer->audio.pcm.samples = malloc(layer->audio.bufsize+buffer_padding);
	if(!layer->audio.pcm.samples)
	{
		snprintf(apeg_error, sizeof(apeg_error), "Error allocating %d bytes for audio buffer",
		         layer->audio.bufsize+buffer_padding);
		return APEG_ERROR;
	}

	if(layer->stream.audio.channels > 2)
		layer->stream.audio.channels = 2;

	layer->audio.samples_per_update = layer->audio.bufsize / 2 /
	                                  layer->stream.audio.channels;

	/* Start the audio stream */
	layer->audio.stream = create_sample(16, layer->stream.audio.channels != 1,
	                                    layer->stream.audio.freq,
	                                    layer->audio.samples_per_update*2);
	if(layer->audio.stream)
	{
		int i;
		for(i = 0;i < layer->audio.bufsize;++i)
			((short*)layer->audio.stream->data)[i] = 0x8000;
	}
	else
	{
		snprintf(apeg_error, sizeof(apeg_error), "Error starting stream playback");
		return APEG_ERROR;
	}

	layer->audio.voice = play_sample(layer->audio.stream, 255, 127, 1000, TRUE);
	voice_set_priority(layer->audio.voice, 255);

	layer->audio.last_pos = -1;
	layer->audio.pos = -layer->audio.samples_per_update*2;

	_apeg_audio_set_speed_multiple(layer, layer->multiple);

	return APEG_OK;
}
Exemplo n.º 22
0
int eof_add_silence_recode(char * oggfn, unsigned long ms)
{
	char sys_command[1024] = {0};
	char backupfn[1024] = {0};
	char wavfn[1024] = {0};
	char soggfn[1024] = {0};
	ALOGG_OGG *oggfile = NULL;
	SAMPLE *decoded = NULL, *combined = NULL;
	int bits;
	int stereo;
	int freq;
	unsigned long samples;
	int channels;
	unsigned long ctr,index;
	void * oggbuffer = NULL;
	int bitrate;

 	eof_log("eof_add_silence_recode() entered", 1);

	if(!oggfn || (ms == 0) || eof_silence_loaded)
	{
		return 41;	//Return failure:  Invalid parameters
	}
	set_window_title("Adjusting Silence...");

	/* back up original file */
	(void) snprintf(backupfn, sizeof(backupfn) - 1, "%s.backup", oggfn);
	if(!exists(backupfn))
	{
		(void) eof_copy_file(oggfn, backupfn);
	}

	/* Decode the OGG file into memory */
	//Load OGG file into memory
	oggbuffer = eof_buffer_file(oggfn, 0);	//Decode the OGG from buffer instead of from file because the latter cannot support special characters in the file path due to limitations with fopen()
	if(!oggbuffer)
	{
		(void) snprintf(eof_log_string, sizeof(eof_log_string) - 1, "\tError reading OGG:  \"%s\"", strerror(errno));	//Get the Operating System's reason for the failure
		eof_log(eof_log_string, 1);
		return 42;	//Return failure:  Could not buffer chart audio into memory
	}
	oggfile=alogg_create_ogg_from_buffer(oggbuffer, (int)file_size_ex(oggfn));
	if(oggfile == NULL)
	{
		eof_log("ALOGG failed to open input audio file", 1);
		free(oggbuffer);
		return 43;	//Return failure:  Could not process buffered chart audio
	}

	//Decode OGG into memory
	decoded=alogg_create_sample_from_ogg(oggfile);
	if(decoded == NULL)
	{
		alogg_destroy_ogg(oggfile);
		free(oggbuffer);
		return 44;	//Return failure:  Could not decode chart audio to memory
	}

	/* Create a SAMPLE array large enough for the leading silence and the decoded OGG */
	bits = alogg_get_wave_bits_ogg(oggfile);
	stereo = alogg_get_wave_is_stereo_ogg(oggfile);
	freq = alogg_get_wave_freq_ogg(oggfile);
	alogg_destroy_ogg(oggfile);	//This is no longer needed
	oggfile = NULL;
	samples = msec_to_samples(ms);
	channels = stereo ? 2 : 1;
	combined = create_sample(bits,stereo,freq,samples+decoded->len);	//Create a sample array long enough for the silence and the OGG file
	if(combined == NULL)
	{
		destroy_sample(decoded);
		return 45;	//Return failure:  Could not create a sample array for the combined audio
	}

	/* Add the PCM data for the silence */
	if(bits == 8)
	{	//Create 8 bit PCM data
		for(ctr=0,index=0;ctr < samples * channels;ctr++)
		{
			((unsigned char *)(combined->data))[index++] = 0x80;
		}
	}
	else
	{	//Create 16 bit PCM data
		for(ctr=0,index=0;ctr < samples * channels;ctr++)
		{
			((unsigned short *)(combined->data))[index++] = 0x8000;
		}
	}

	/* Add the decoded OGG PCM data*/
	if(bits == 8)
	{	//Copy 8 bit PCM data
		for(ctr=0;ctr < decoded->len * channels;ctr++)
		{
			((unsigned char *)(combined->data))[index++] = ((unsigned char *)(decoded->data))[ctr];
		}
	}
	else
	{	//Copy 16 bit PCM data
		for(ctr=0;ctr < decoded->len * channels;ctr++)
		{
			((unsigned short *)(combined->data))[index++] = ((unsigned short *)(decoded->data))[ctr];
		}
	}

	/* encode the audio */
	destroy_sample(decoded);	//This is no longer needed
	free(oggbuffer);
	(void) replace_filename(wavfn, eof_song_path, "encode.wav", 1024);
	(void) save_wav(wavfn, combined);
	destroy_sample(combined);	//This is no longer needed
	(void) replace_filename(soggfn, eof_song_path, "encode.ogg", 1024);
	bitrate = alogg_get_bitrate_ogg(eof_music_track) / 1000;
	if(!bitrate)
	{	//A user found that in an audio file with a really high sample rate (ie. 96KHz), alogg_get_bitrate_ogg() may return zero instead of an expected value
		bitrate = 256;	//In case this happens, use a bitrate of 256Kbps, which should be good enough for a very high quality file
	}
	#ifdef ALLEGRO_WINDOWS
		(void) uszprintf(sys_command, (int) sizeof(sys_command) - 1, "oggenc2 -o \"%s\" -b %d \"%s\"", soggfn, bitrate, wavfn);
	#else
		(void) uszprintf(sys_command, (int) sizeof(sys_command) - 1, "oggenc -o \"%s\" -b %d \"%s\"", soggfn, bitrate, wavfn);
	#endif

	(void) snprintf(eof_log_string, sizeof(eof_log_string) - 1, "\tCalling oggenc as follows:  %s", sys_command);
	eof_log(eof_log_string, 1);
	if(eof_system(sys_command))
	{	//If oggenc failed, retry again by specifying a quality level (specifying bitrate can fail in some circumstances)
		eof_log("\t\toggenc failed.  Retrying by specifying a quality level instead of a target bitrate", 1);
		#ifdef ALLEGRO_WINDOWS
			(void) uszprintf(sys_command, (int) sizeof(sys_command) - 1, "oggenc2 -o \"%s\" -q 9 \"%s\"", soggfn, wavfn);
		#else
			(void) uszprintf(sys_command, (int) sizeof(sys_command) - 1, "oggenc -o \"%s\" -q 9 \"%s\"", soggfn, wavfn);
		#endif
		(void) snprintf(eof_log_string, sizeof(eof_log_string) - 1, "\tCalling oggenc as follows:  %s", sys_command);
		eof_log(eof_log_string, 1);
		if(eof_system(sys_command))
		{	//If oggenc failed again
			char tempfname[30] = {0};
			char redirect[35] = {0};

			if(eof_validate_temp_folder())
			{	//Ensure the correct working directory and presence of the temporary folder
				eof_log("\tCould not validate working directory and temp folder", 1);
				return 46;	//Return failure:  Could not validate cwd and temp folder
			}

			(void) snprintf(tempfname, sizeof(tempfname) - 1, "%soggenc.log", eof_temp_path_s);
			(void) snprintf(redirect, sizeof(redirect) - 1, " 2> %s", tempfname);
			(void) ustrzcat(sys_command, (int) sizeof(sys_command) - 1, redirect);	//Append a redirection to the command to capture the output of oggenc
			if(eof_system(sys_command))
			{	//Run one last time to catch the error output
				(void) snprintf(eof_log_string, sizeof(eof_log_string) - 1, "\tOggenc failed.  Please see %s for any errors it gave.", tempfname);
				eof_log(eof_log_string, 1);
				eof_fix_window_title();
				return 47;	//Return failure:  Could not encode combined audio
			}
		}
	}

	/* replace the current OGG file with the new file */
	(void) eof_copy_file(soggfn, oggfn);	//Copy encode.ogg to the filename of the original OGG

	/* clean up */
	(void) delete_file(soggfn);	//Delete encode.ogg
	(void) delete_file(wavfn);		//Delete encode.wav
	if(eof_load_ogg(oggfn, 0))
	{	//If the combined audio was loaded
		eof_fix_waveform_graph();
		eof_fix_spectrogram();
		eof_fix_window_title();
		eof_chart_length = eof_music_length;
		return 0;	//Return success
	}
	eof_fix_window_title();

	return 48;	//Return error:  Could not load new audio
}
Exemplo n.º 23
0
/* -------------------------------------
 * LBFGS
 * IN
 * func:  Function to be minimized.
 * nRow:  Number of rows (length) of x.
 * N_max: Maximum number of CG iterates.
 * TOL:   Minimum size for gradient of f.
 * OUT
 * x: Local minimum of func.
 * -------------------------------------
 */
double * SLM_LBFGS(double (* func)(double*, int),
                   int nRow, int m, double TOL, int N_max, int verbose){
  // Variable declaration.
  double **s, **y;
  double *x, *grad, *p, *x_new, *grad_new;
  double alpha, norm_grad0;
  int i, k, MAX_ITER, exploredDataPoints;
  // Space allocation.
  x = (double *)malloc(nRow * sizeof(double));
  s = (double **)malloc((nRow*m) * sizeof(double));
  y = (double **)malloc((nRow*m) * sizeof(double));
  // Initialize x.
  for(i = 0; i < nRow; i++){
    x[i] = ((double) rand() / INT_MAX) ;
  }
  // Stochastic Mode
  if(stocMode){
    exploredDataPoints = 0;
    //printf("\nRUNNING STOCASTIC MODE\n");
    SAMPLE      = rand() % (int)(MAX_FILE_ROWS * sampProp);
    create_sample(0);
    exploredDataPoints += SAMPLE;
  }

  // Until Convergence or MAX_ITER.
  MAX_ITER = 6e6;
  grad     = gradCentralDiff(func, x, nRow);
  // Update s, y.
  k = 0;
  // Initial norm of gradient.
  norm_grad0 = norm(grad, nRow);
  while(norm(grad, nRow) > TOL*(1 + norm_grad0) && ((run_logistic*exploredDataPoints + ((1 - run_logistic)*k)) < MAX_ITER)){
    if(stocMode){
      printf("\nRUNNING STOCASTIC MODE\n");
      SAMPLE      = rand() % (int)(MAX_FILE_ROWS * sampProp);
      create_sample(k);
      exploredDataPoints += SAMPLE;
    }

    // p = -Hgrad(f)
    if(k > 0){
      p = vProd(findHSLM(func, x, s,
                         y, nRow, m,
                         k, N_max),
                -1, nRow);
    }else{
      p = vProd(grad, -1, nRow);
    }
    // Alpha that statifies Wolfe conditions.
    alpha    = backTrack(func, x, p, nRow, verbose);
    x_new    = vSum(x, vProd(p, alpha, nRow), nRow);
    //imprimeTit("X_NEW");
    //imprimeMatriz(x_new, 1, nRow);
    grad_new = gradCentralDiff(func, x_new, nRow);
    //imprimeTit("GRAD_NEW");
    //imprimeMatriz(grad_new, 1, nRow);
    // Update s, y.
    updateSY(s, y, vProd(p, alpha, nRow),
             vSum(grad_new, vProd(grad, -1, nRow), nRow), m, k);

    // ---------------- PRINT ------------------- //
    if(verbose){
      if(stocMode){
        printf("\n ITER = %d; f(x) = %.10e ; "
               "||x|| = %.10e ; ||grad|| =  %.10e ; "
               "||p|| =  %.10e ; sTy =  %.10e ; "
               "alpha = %.10e; explored data points = %d; precision = %fl ",
               k,
               func(x, nRow),
               norm(x, nRow),
               norm(grad, nRow),
               norm(p, nRow),
               dotProd(s[(int)min(k , (m - 1))],
                       y[(int)min(k , (m - 1))], nRow),
               alpha,
               exploredDataPoints,
               class_precision(x, nRow, 0));

      }else{
      printf("\n ITER = %d; f(x) = %.10e ; "
             "||x|| = %.10e ; ||grad|| =  %.10e ; "
             "||p|| =  %.10e ; sTy =  %.10e ; "
             "alpha = %.10e",
             k,
             func(x, nRow),
             norm(x, nRow),
             norm(grad, nRow),
             norm(p, nRow),
             dotProd(s[(int)min(k , (m - 1))],
                     y[(int)min(k , (m - 1))], nRow),
             alpha);
      }
    }
    // ---------------- PRINT ------------------- //y
    // Update k, x, grad.
    x    = x_new;
    grad = grad_new;
    k    = k + 1;
  }
  free(grad);
  free(s);
  free(y);
  return x;
}
Exemplo n.º 24
0
int eof_add_silence_recode_mp3(char * oggfn, unsigned long ms)
{
	char sys_command[1024] = {0};
	char backupfn[1024] = {0};
	char wavfn[1024] = {0};
	char soggfn[1024] = {0};
	char mp3fn[1024] = {0};
	SAMPLE * decoded = NULL;
	SAMPLE * combined = NULL;
	int bits;
	int stereo;
	int freq;
	unsigned long samples;
	int channels;
	unsigned long ctr,index;

 	eof_log("eof_add_silence_recode_mp3() entered", 1);

	if(!oggfn || (ms == 0) || eof_silence_loaded)
	{
		return 21;	//Return error:  Invalid parameters
	}
	set_window_title("Adjusting Silence...");

	/* back up original file */
	(void) snprintf(backupfn, sizeof(backupfn) - 1, "%s.backup", oggfn);
	if(!exists(backupfn))
	{
		(void) eof_copy_file(oggfn, backupfn);
	}

	/* decode MP3 */
	(void) replace_filename(wavfn, eof_song_path, "decode.wav", 1024);
	(void) replace_filename(mp3fn, eof_song_path, "original.mp3", 1024);
	(void) uszprintf(sys_command, (int) sizeof(sys_command) - 1, "lame --decode \"%s\" \"%s\"", mp3fn, wavfn);
	(void) eof_system(sys_command);

	/* insert silence */
	decoded = load_sample(wavfn);
	if(!decoded)
	{
		allegro_message("Error opening file.\nMake sure there are no Unicode or extended ASCII characters in this chart's file path.");
		return 22;	//Return failure:  Could not load decoded MP3 file
	}
	bits = decoded->bits;
	stereo = decoded->stereo;
	freq = decoded->freq;
	samples = (decoded->freq * ms) / 1000;	//Calculate this manually instead of using msec_to_samples() because that function assumes the sample rate matches the current chart audio, and this may not be the case with the original MP3 file the user provided
	channels = stereo ? 2 : 1;
	combined = create_sample(bits,stereo,freq,samples+decoded->len);	//Create a sample array long enough for the silence and the OGG file
	if(combined == NULL)
	{
		destroy_sample(decoded);
		return 23;	//Return failure:  Could not create a sample array for the combined audio
	}
	/* Add the PCM data for the silence */
	if(bits == 8)
	{	//Create 8 bit PCM data
		for(ctr=0,index=0;ctr < samples * channels;ctr++)
		{
			((unsigned char *)(combined->data))[index++] = 0x80;
		}
	}
	else
	{	//Create 16 bit PCM data
		for(ctr=0,index=0;ctr < samples * channels;ctr++)
		{
			((unsigned short *)(combined->data))[index++] = 0x8000;
		}
	}
	/* Add the decoded OGG PCM data*/
	if(bits == 8)
	{	//Copy 8 bit PCM data
		for(ctr=0;ctr < decoded->len * channels;ctr++)
		{
			((unsigned char *)(combined->data))[index++] = ((unsigned char *)(decoded->data))[ctr];
		}
	}
	else
	{	//Copy 16 bit PCM data
		for(ctr=0;ctr < decoded->len * channels;ctr++)
		{
			((unsigned short *)(combined->data))[index++] = ((unsigned short *)(decoded->data))[ctr];
		}
	}

	/* save combined WAV */
	(void) replace_filename(wavfn, eof_song_path, "encode.wav", 1024);
	if(!save_wav(wavfn, combined))
	{
		destroy_sample(decoded);	//This is no longer needed
		destroy_sample(combined);	//This is no longer needed
		return 24;	//Return failure:  Could not create the combined audio WAV file
	}

	/* destroy samples */
	destroy_sample(decoded);	//This is no longer needed
	destroy_sample(combined);	//This is no longer needed

	/* encode the audio */
	printf("%s\n%s\n", eof_song_path, wavfn);
	(void) replace_filename(soggfn, eof_song_path, "encode.ogg", 1024);
	#ifdef ALLEGRO_WINDOWS
		(void) uszprintf(sys_command, (int) sizeof(sys_command) - 1, "oggenc2 -o \"%s\" -b %d \"%s\"", soggfn, alogg_get_bitrate_ogg(eof_music_track) / 1000, wavfn);
	#else
		(void) uszprintf(sys_command, (int) sizeof(sys_command) - 1, "oggenc -o \"%s\" -b %d \"%s\"", soggfn, alogg_get_bitrate_ogg(eof_music_track) / 1000, wavfn);
	#endif

	(void) snprintf(eof_log_string, sizeof(eof_log_string) - 1, "\tCalling oggenc as follows:  %s", sys_command);
	eof_log(eof_log_string, 1);
	if(eof_system(sys_command))
	{	//If oggenc failed, retry again by specifying a quality level (specifying bitrate can fail in some circumstances)
		eof_log("\t\toggenc failed.  Retrying by specifying a quality level instead of a target bitrate", 1);
		#ifdef ALLEGRO_WINDOWS
			(void) uszprintf(sys_command, (int) sizeof(sys_command) - 1, "oggenc2 -o \"%s\" -q 9 \"%s\"", soggfn, wavfn);
		#else
			(void) uszprintf(sys_command, (int) sizeof(sys_command) - 1, "oggenc -o \"%s\" -q 9 \"%s\"", soggfn, wavfn);
		#endif
		(void) snprintf(eof_log_string, sizeof(eof_log_string) - 1, "\tCalling oggenc as follows:  %s", sys_command);
		eof_log(eof_log_string, 1);
		if(eof_system(sys_command))
		{	//If oggenc failed again
			char tempfname[30] = {0};
			char redirect[35] = {0};

			if(eof_validate_temp_folder())
			{	//Ensure the correct working directory and presence of the temporary folder
				eof_log("\tCould not validate working directory and temp folder", 1);
				return 25;	//Return failure:  Could not validate cwd and temp folder
			}

			(void) snprintf(tempfname, sizeof(tempfname) - 1, "%soggenc.log", eof_temp_path_s);
			(void) snprintf(redirect, sizeof(redirect) - 1, " 2> %s", tempfname);
			(void) ustrzcat(sys_command, (int) sizeof(sys_command) - 1, redirect);	//Append a redirection to the command to capture the output of oggenc
			if(eof_system(sys_command))
			{	//Run one last time to catch the error output
				(void) snprintf(eof_log_string, sizeof(eof_log_string) - 1, "\tOggenc failed.  Please see %s for any errors it gave.", tempfname);
				eof_log(eof_log_string, 1);
				eof_fix_window_title();
				return 26;	//Return failure:  Could not encode combined audio
			}
		}
	}

	/* replace the current OGG file with the new file */
	(void) eof_copy_file(soggfn, oggfn);	//Copy encode.ogg to the filename of the original OGG

	/* clean up */
	(void) replace_filename(wavfn, eof_song_path, "decode.wav", 1024);
	(void) delete_file(wavfn);		//Delete decode.wav
	(void) replace_filename(wavfn, eof_song_path, "encode.wav", 1024);
	(void) delete_file(wavfn);		//Delete encode.wav
	(void) delete_file(soggfn);	//Delete encode.ogg
	if(eof_load_ogg(oggfn, 0))
	{	//If the combined audio was loaded
		eof_fix_waveform_graph();
		eof_fix_spectrogram();
		eof_fix_window_title();
		eof_chart_length = eof_music_length;
		return 0;	//Return success
	}
	eof_fix_window_title();

	return 27;	//Return error:  Could not load new audio
}
Exemplo n.º 25
0
void saPlayBufferedStreamedSampleBase( int channel, signed char *data, int len, int freq, int volume, int bits , int pan ){
  /* This version works at low level, creating a sample, and following its
     advancement directly in the voice_position... */
  int i;
  short *dout;
  short *dfin;
  signed short *din;
  //fprintf(stderr,"saPlayBuffer %d freq %d bits %d pan %d len %d\n",channel,freq,bits,pan,len);
  if( audio_sample_rate == 0 || channel >= NUMVOICES )	return;
  if( SndMachine == NULL )  return;
  if( !playing[channel] ){
#ifdef USE_COMPENS
    int fin = stream_buffer_max * freq * 2 / fps;
#else
    int fin = stream_buffer_max * len;
#endif
    if( lpWave[channel] ){
      destroy_sample( lpWave[channel] );
      lpWave[channel] = 0;
    }

    if (!(lpWave[channel] = create_sample(16,0,freq,fin/2))){
      lpWave[channel] = 0;
      return;
    }

    //	  memset( lpWave[channel]->data, 0, fin );
    dout=lpWave[channel]->data;
    dfin=(short*) (((char*)lpWave[channel]->data)+fin);
    // Fill the buffer with 0 (signed) in case the soundcards reads what
    // is after the sample...
    while (dout < dfin)
      *(dout++) = 0x8000;
    vend[channel] = dfin;
    counter[channel] = 0;

    hVoice[channel] = allocate_voice( lpWave[channel] );
    if (hVoice[channel]<0) {
      allegro_message("allocate_voice failed !\n");
      exit(1);
    }

    voice_set_playmode(hVoice[channel],PLAYMODE_LOOP);

    playing[channel] = 1;	/* use front surface */

    init_mixing_buff(len);

    /**** make sound temp. buffer ****/
    if (enh_stereo && SamplePan[channel] == PAN_LEFT)
      dout=(short*) (((char*)lpWave[channel]->data)+len*(MODEB_UPDATE_COUNT+1)); //+len*MODEB_UPDATE_COUNT);
    else
      dout=(short*) (((char*)lpWave[channel]->data)+len*MODEB_UPDATE_COUNT); //+len*MODEB_UPDATE_COUNT);
    din = ((signed short*)data);
    //	      memcpy( dout, din, len );
    for (i=0; i<len; i+=2){
      *(dout++) = *(din++)^0x8000;
    }

    update_recording(channel,data);

    if (dout ==dfin){
      dout=(short*) (((char*)lpWave[channel]->data));
    }
#ifdef DUMP_CHANNELS
    fwrite( lpWave[channel]->data+len*MODEB_UPDATE_COUNT, 1, len, stream_out[channel]);
#endif

    vout[channel] = dout;
    saSetVolume(channel,SampleVol[channel]);
    saSetPan(channel,SamplePan[channel]);
    voice_set_position(hVoice[channel],0);
    voice_start(hVoice[channel]);
    pos_counter[channel] = 0;
  } else{
    int pos = voice_get_position(hVoice[channel]);
    int th_pos;
    int count = (enh_stereo && SamplePan[channel] == PAN_LEFT ?
		 MODEB_UPDATE_COUNT + 1 : MODEB_UPDATE_COUNT);

    // this difference between the theorical position and the actual
    // position is because clearly the reported position is directly
    // dependant of when the sound driver updated the voice for the
    // last time. Luckily the difference is big only when the voice
    // starts. After starting it gets more or less updated when it
    // should, depending on external factors too like the cpu load.

    dout=vout[channel];
    th_pos = (dout - ((INT16 *)lpWave[channel]->data)-
	      count*len/2);
    if (th_pos < 0) th_pos += stream_buffer_max * len/2;

    // if there is more than count frames between pos and th_pos, then
    // wait for the voice.
    if (pos < th_pos) {
      if (th_pos - pos < count * len/2) {
	more_stream = -1; // drop next frame
      }
    }
    din = ((signed short*)data);
    dfin = vend[channel];
    //	  memcpy(dout,din,len);

    for (i=0; i<len; i+=2){
      *(dout++) = *(din++)^0x8000;
    }
    update_recording(channel,data);
    if (dout >=dfin){
      dout=(short*) (((char*)lpWave[channel]->data));

    }

#ifdef DUMP_CHANNELS

    fwrite( lpWave[channel]->data+len*s_pos, 1, len, stream_out[channel]);
#endif
    vout[channel] = dout;

    // more than count frames of advance : more stream !
    pos -= count*len/2;
    if (pos > th_pos && pos > 0) {
      // send more
      more_stream = 1;
    }
  }
}
Exemplo n.º 26
0
// return: 0: okay; 1: needs more sample; 2: needs reconfiguring; 3: more data available
int receive_sample(IMFTransform *transform, DWORD out_stream_id, IMFSample** out_sample) {
	HRESULT hr;
	MFT_OUTPUT_DATA_BUFFER out_buffers;
	IMFSample *sample = NULL;
	MFT_OUTPUT_STREAM_INFO out_info;
	DWORD status = 0;
	bool mft_create_sample = false;

	if (!out_sample)
	{
		ReportError(L"NULL pointer passed to receive_sample()", MF_E_SAMPLE_NOT_WRITABLE);
		return -1;
	}

	SafeRelease(out_sample);

	hr = transform->GetOutputStreamInfo(out_stream_id, &out_info);

	if (FAILED(hr))
	{
		ReportError(L"MFT: Failed to get stream info", hr);
		return -1;
	}
	mft_create_sample = (out_info.dwFlags & MFT_OUTPUT_STREAM_PROVIDES_SAMPLES) || (out_info.dwFlags & MFT_OUTPUT_STREAM_CAN_PROVIDE_SAMPLES);

	while (true)
	{
		sample = NULL;
		*out_sample = NULL;
		status = 0;

		if (!mft_create_sample)
		{
			sample = create_sample(NULL, out_info.cbSize, out_info.cbAlignment);
			if (!sample)
			{
				ReportError(L"MFT: Unable to allocate memory for samples", hr);
				return -1;
			}
		}

		out_buffers.dwStreamID = out_stream_id;
		out_buffers.pSample = sample;

		hr = transform->ProcessOutput(0, 1, &out_buffers, &status);

		if (!FAILED(hr))
		{
			*out_sample = out_buffers.pSample;
			break;
		}

		if (hr == MF_E_TRANSFORM_NEED_MORE_INPUT) {
			// TODO: better handling try again and EOF cases using drain value
			return 1;
		}

		if (hr == MF_E_TRANSFORM_STREAM_CHANGE)
		{
			ReportError(L"MFT: stream format changed, re-configuration required", hr);
			return 2;
		}

		break;
	}


	if (out_buffers.dwStatus & MFT_OUTPUT_DATA_BUFFER_INCOMPLETE)
	{
		return 3;
	}

	// TODO: better handling try again and EOF cases using drain value
	if (*out_sample == NULL)
	{
		ReportError(L"MFT: decoding failure", hr);
		return -1;
	}

	return 0;
}