Example #1
0
// generates the sum of L_Ev components in Terhardt (4)
// see also (5), (7)
double get_inter_mask(double *amp_dB, int *tonal_indices, int num_tonal, int u)
{ //{{{
	// TODO only go through TONAL INDICES
	double f_u = get_freq(u);
	double z_u = hz_to_bark(f_u);
	double sum = 0;
	
	// calculate the masking effect from other frequencies by using a linear
	// approximation of the masking curve
	for(int i = 1; i < num_tonal; i++){
		int v = tonal_indices[i];

		double L_v = amp_dB[v];
		double f_v = get_freq(v);
		double z_v = hz_to_bark(f_v);

		double s; // slope of masking curve is different for above/below v
		if(v < u)
			s = -24.0 - (230.0/f_v) + 0.2*L_v; // slope of masking curve above masker
		else if(v > u)
			s = 27; // slope below masker
		else continue;

	  double exp = (L_v - s * (z_v - z_u))/20.0;
		sum += pow(10,exp);
	}

	return sum*sum;
} //}}}
Example #2
0
void sound_byte(ubyte iobyte) {      // if a noise program byte, return
    if ((iobyte & 0xE0) == 0xE0) return;

    if ((iobyte & 0x90) == 0x90) get_vol(iobyte);  // if a volume byte
    if ((iobyte & 0x90) == 0x80) get_freq(iobyte); // if a frequency byte
    if (!(iobyte & 0x80)) get_freq(iobyte);      // if a frequency byte
    if (soundyesno) update_sound();            // update sound

}
Example #3
0
/*
 * This function retrieves the exact note for the given frequency. The ideal
 * frequency is based upon the ISO 16:1975 standard frequency of the A4 note
 * (i.e. 440 Hz) in twelve-tone equal temperament.  The cents member of the
 * note struct will be given a value in the (inclusive) range -50.0 to +50.0.
 *
 * Returns the note if everything works as expected.  Returns an invalid note
 * for illegal arguments or internal error.
 */
struct note get_exact_note(double freq)
{
	struct note	note;
	double		approx_note_freq;

	/* use our handy-dandy get_approx_note() fxn to get a ballpark note */
	note = get_approx_note(freq);
	if (UNKNOWN_SEMITONE == note.semitone) {
		return note;
	}

	/*
	 * In order to calculate the cents value for the exact note, we first
	 * must know the ideal frequency of the approximate note.
	 *
	 * We assume that get_freq() is called without any illegal arguments,
	 * since we have successfully gotten the approximate note if we have
	 * made it this far.
	 */
	approx_note_freq = get_freq(&note);
	assert(INVALID_FREQUENCY != approx_note_freq);

	/*
	 * Calculate the number of cents from the ideal frequency of the
	 * approximate note.  This is done by multiplying the number of cents
	 * per octave by the logarithm base two of the quotient of the
	 * frequencies.
	 */
	note.cents = SEMITONE_INTERVAL_CENTS * SEMITONES_PER_OCTAVE
		* log2(freq / approx_note_freq);

	return note;
}
void calc_value(int pos) {
    double fr[100000];
    int first = pos*segment_len;
    int len = segment_len;
    
    memcpy(in, &data[first], sizeof(double)*len);
    for (int i = 0; i < len; i++) {
        in[i] *= 1.0*(1-cos(2*3.14159*i/(len-1)));
    }
    plan = fftw_plan_dft_r2c_1d(len, in, out, FFTW_ESTIMATE);
    fftw_execute(plan);
    
    for (int i = 0; i < len/2; i++) {
        double x = sqrt(out[i][0]*out[i][0]+out[i][1]*out[i][1]);
        double y = sqrt(out[i+1][0]*out[i+1][0]+out[i+1][1]*out[i+1][1]);
        int a = i*sample_rate/len;
        int b = (i+1)*sample_rate/len;
        int p = b-a;
        for (int j = a; j < b; j++) {
            double v = x*(double)(b-j)/p+y*(double)(j-a)/p;
            fr[j] = v;
        }
    }
    for (int i = real_min_note; i <= real_max_note; i++) {
        double f = fr[get_freq(i)];
        if (rowmax[i] < f) rowmax[i] = f;
        if (colmax[pos] < f) colmax[pos] = f;
        freq[pos][i] = f;
    }
}
Example #5
0
void print_elapsed_time (INT64 start, INT64 end)
{
  INT64 freq = get_freq ();
  std::cout.precision(5);
  std::cout << (((double) (end - start)) / ((double) freq)) << " seconds";
  std::cout.flush();
}
Example #6
0
double get_intra_mask(complex *freq_buf, int f, int cb)
{ //{{{
	int bandwidth = 0;  // the number of frequencies within the critical band
	while((f+bandwidth < FREQ_LEN) && get_freq(f+bandwidth) <= cb_limits[cb])
		bandwidth++;

	// get tonal components
	for(int i = 0; i < bandwidth; i++) ;

} //}}}
Example #7
0
void up_lowserialinit(void)
{
  uint32_t freq = get_freq();
  uint16_t brg;
  uint8_t  val;

#ifdef CONFIG_UART0_SERIAL_CONSOLE
  /* Set the baudrate */

  brg = (freq +(uint32_t)CONFIG_UART0_BAUD * 8) /((uint32_t)CONFIG_UART0_BAUD * 16) ;

  putreg8(brg >> 8, U0BRH);
  putreg8(brg & 0xff, U0BRL);

  /* Configure GPIO Port A pins 4 & 5 for alternate function */

  putreg8(0x02, PAADDR);
  val = getreg8(PACTL) | 0x30;    /* Set bits in alternate function register */
  putreg8(val, PACTL);
  putreg8(0x07, PAADDR);
  val = getreg8(PACTL) & 0xcf;    /* Reset bits in alternate function set-1 register */
  putreg8(val, PACTL);
  putreg8(0x08, PAADDR);
  val = getreg8(PACTL) & 0xcf;    /* Reset bits in alternate function set-2 register */
  putreg8(val, PACTL);
  putreg8(0x00, PAADDR);

  putreg8(0x00, U0CTL1);          /* no multi-processor operation mode */
  putreg8(0xc0, U0CTL0);          /* Transmit enable, Receive enable, no Parity, 1 Stop bit */

#elif defined(EZ8_UART1) && defined(CONFIG_UART1_SERIAL_CONSOLE)
  /* Set the baudrate */

  brg = (freq +(uint32_t)CONFIG_UART1_BAUD * 8) /((uint32_t)CONFIG_UART1_BAUD * 16) ;

  putreg8(brg >> 8, U1BRH);
  putreg8(brg & 0xff, U1BRL);

  /* Configure GPIO Port D pins 4 & 5 for alternate function */

  putreg8(0x02, PAADDR);
  val = getreg8(PDCTL) | 0x30;    /* Set bits in alternate function register */
  putreg8(val, PDCTL);
  putreg8(0x07, PDADDR);
  val = getreg8(PDCTL) & 0xcf;    /* Reset bits in alternate function set-1 register */
  putreg8(val, PDCTL);
  putreg8(0x08, PDADDR);
  val = getreg8(PDCTL) & 0xcf;    /* Reset bits in alternate function set-2 register */
  putreg8(val, PDCTL);
  putreg8(0x00, PDADDR);

  putreg8(0x00, U1CTL1);          /* no multi-processor operation mode */
  putreg8(0xc0, U1CTL0);          /* Transmit enable, Receive enable, no Parity, 1 Stop bit */
#endif
}
Example #8
0
/* set everything to zero */
void
init_timer()
{
	frequency = get_freq();

	count_frames = 0;

	tim.dct = tim.quant = tim.idct = tim.iquant = tim.motion = tim.conv =
		tim.edges = tim.inter = tim.interlacing = tim.trans = tim.trans =
		tim.coding = tim.global = tim.overall = 0;
}
Example #9
0
/*
 * This function verifies that the provided frequency falls within the range of
 * notes this library can represent.  This range is from C0 -50.0 cents to B12
 * +50 cents.
 */
static bool is_allowable_freq(double freq)
{
	double		lowest_freq;
	double		highest_freq;
	struct note	lowest_note;
	struct note	highest_note;

	lowest_note.semitone	= C;  /* the "lowest" semitone enumeration */
	lowest_note.octave	= OCTAVE_MIN;
	lowest_note.cents	= -(SEMITONE_INTERVAL_CENTS / 2.0);  /* -50.0 */

	highest_note.semitone	= B;  /* the "highest" semitone enumeration */
	highest_note.octave	= OCTAVE_MAX;
	highest_note.cents	= SEMITONE_INTERVAL_CENTS / 2.0;  /* +50.0 */

	lowest_freq	= get_freq(&lowest_note);
	highest_freq	= get_freq(&highest_note);

	return (freq >= lowest_freq) && (freq <= highest_freq);
}
Example #10
0
tint usec_time(void)
{
	static LARGE_INTEGER last_time;
	LARGE_INTEGER cur_time;
	QueryPerformanceCounter(&cur_time);
	if (cur_time.QuadPart<last_time.QuadPart)
		print_error("QueryPerformanceCounter wrapped"); // does this happen?
	last_time = cur_time;
	static float freq = 1000000.0/get_freq().QuadPart;
	tint usec = cur_time.QuadPart * freq;
	return usec;
}
Example #11
0
int search(int dir, int mode, int forced_mono)
{
	unsigned char radio[5] = {0};
	double freq;

	freq = get_freq();

	if (dir) freq += 0.1;
	else freq -= 0.1;

	if (freq >= 108.0 || freq <= 76.0)
		return -1;

	frequencyB = 4 * (freq * 1000000 + 225000) / 32768; //calculating PLL word
	frequencyH = frequencyB >> 8;
	frequencyH = frequencyH | 0x40; // triggers search
	frequencyL = frequencyB & 0xFF;

	//nothing to set in array #2 as up is the normal search direction
	radio[0] = frequencyH; //FREQUENCY H
	radio[0] |= 0x80; // MUTE
	radio[1] = frequencyL; //FREQUENCY L
	radio[2] = 0x10; // high side LO injection is on,.
	radio[2] |= (mode & 0x03) << 5; // high side LO injection is on,.
	if (dir) radio[2] |= 0x80;	// search up/down
	if (forced_mono) radio[2] |= 0x08; 
	radio[3] = 0x10; // Xtal is 32.768 kHz
	//if (freq < 87.5) radio[3] |= 0x20;
	if (HCC_DEFAULT) radio[3] |= 0x04;
	if (SNC_DEFAULT) radio[3] |= 0x02;
	radio[4] = 0x40; // deemphasis is 75us in Korea and US

	write(fd, radio, 5);

	wait_ready();
	set_freq(get_freq(), HCC_DEFAULT, SNC_DEFAULT, forced_mono, 0, 0); // unmute
	
	return 0;
}
Example #12
0
void up_timerinit(void)
{
  uint32_t reload;
 
  up_disable_irq(Z8_IRQ_SYSTIMER);

  /* Write to the timer control register to disable the timer, configure
   * the timer for continuous mode, and set up the pre-scale value for
   * divide by 4.
   */

  putreg8((Z8_TIMERCTL_DIV4|Z8_TIMERCTL_CONT), T0CTL);

  /* Write to the timer high and low byte registers to set a starting
   * count value (this effects only the first pass in continuous mode)
   */

  putreg16(0x0001, T0);

  /* Write to the timer reload register to set the reload value.
   *
   * In continuous mode:
   *
   *   timer_period = reload_value x prescale / system_clock_frequency
   * or
   *   reload_value = (timer_period * system_clock_frequency) / prescale
   *
   * For system_clock_frequency=18.432MHz, timer_period=10mS, and prescale=4,
   * then reload_value=46,080 - OR:
   *
   *   reload_value = system_clock_frequency / 400
   */

   reload = get_freq() / 400;
   putreg16((uint16_t)reload, T0R);

  /* Write to the timer control register to enable the timer and to
   * initiate counting
   */

  putreg8((getreg8(T0CTL)|Z8_TIMERCTL_TEN), T0CTL);

  /* Set the timer priority */

  /* Attach and enable the timer interrupt (leaving at priority 0 */

  irq_attach(Z8_IRQ_SYSTIMER, (xcpt_t)up_timerisr);
  up_enable_irq(Z8_IRQ_SYSTIMER);
}
Example #13
0
int v4l2_get_frequency (void ** session_data){
  fm_v4l2_data* session;
  int ret;

  ALOGI("%s:\n", __FUNCTION__);
  session = get_session_data(session_data);

  ret = get_freq(session->fd);
  if (ret < 0)
      return -1;

  session->freq = get_standard_freq(ret, session->fact);

  return session->freq;
}
Example #14
0
// returns the masking effect of the noise (non-tonal) components around u, 
// I_Nu
double get_noise_mask(double *amp_dB, int *tonal_indices, int num_tonal, int u)
{ //{{{
	// Sum all the frequency components within .5 barks of u, skipping the five
	// central samples of each tonal component (if i is tonal, no i-2...i+2)
	double u_hz = get_freq(u);
	double u_bark = hz_to_bark(u_hz);
	double cb_width = cb_limits[(int)(u_bark+1)]; // upper bound on freq width

	int lo = get_i(u_hz - (cb_width/2));
	while(u_bark - hz_to_bark(get_freq(lo)) > .5) lo++;

	int hi = get_i(u_hz + (cb_width/2));
	while(hz_to_bark(get_freq(hi)) - u_bark > .5) hi--;

	int i_i = 0;
	double sum = 0;
	for(int i = lo; i <= hi; i++){
		// ensure tonal_indices[i_i] >= i-2 now
		while(i+i < num_tonal && tonal_indices[i_i] < i-2){
			i_i++;
		}

		// no tonal components above i-2
		if(i_i >= num_tonal){
			sum += amp_dB[i];
			continue;
		}

		if(tonal_indices[i_i] > i+2){
			sum += amp_dB[i];
		}
		// otherwise tonal_indices[i_i] <= i+2, and we're in a tonal component
	}

	return sum;
} //}}}
Example #15
0
static int z8_setup(FAR struct uart_dev_s *dev)
{
#ifndef CONFIG_SUPPRESS_UART_CONFIG
    struct z8_uart_s *priv = (struct z8_uart_s*)dev->priv;
    uint32_t freq = get_freq();
    uint16_t brg;
    uint8_t ctl0;
    uint8_t ctl1;

    /* Calculate and set the baud rate generation register.
     * BRG = (freq + baud * 8)/(baud * 16)
     */

    brg = (freq + (priv->baud << 3))/(priv->baud << 4);
    z8_putuart(priv, brg >> 8, Z8_UART_BRH);
    z8_putuart(priv, brg & 0xff, Z8_UART_BRL);

    /* Configure STOP bits */

    ctl0 = ctl1 = 0;
    if (priv->stopbits2)
    {
        ctl0 |= Z8_UARTCTL0_STOP;
    }

    /* Configure parity */

    if (priv->parity == 1)
    {
        ctl0 |= (Z8_UARTCTL0_PEN|Z8_UARTCTL0_PSEL);
    }
    else if (priv->parity == 2)
    {
        ctl0 |= Z8_UARTCTL0_PEN;
    }

    z8_putuart(priv, ctl0, Z8_UART_CTL0);
    z8_putuart(priv, ctl1, Z8_UART_CTL1);

    /* Enable UART receive (REN) and transmit (TEN) */

    ctl0 |= (Z8_UARTCTL0_TEN|Z8_UARTCTL0_REN);
    z8_putuart(priv, ctl0, Z8_UART_CTL0);
#endif
    return OK;
}
Example #16
0
void preset_move(int dir)
{
	int preset;

	if (station_info_num <= 0) return;

	preset = find_station_info(get_freq());
	if (preset >= 0) {
		if (dir) {
			if (++preset >= station_info_num) preset = 0;
		}
		else {
			if (--preset < 0) preset = station_info_num - 1;
		}
	}
	else preset = 1; 

	set_freq(station_info[preset].freq, HCC_DEFAULT, SNC_DEFAULT, FORCED_MONO, 0, 0);
}
Example #17
0
int auto_pll_divisor(enum dev_id dev, enum clk_cmd cmd, int unit, int freq)
{
	int last_freq, divisor, en_count;

	switch (cmd) {
		case CLK_DISABLE:
			if (dev < 128) {
				en_count = disable_dev_clk(dev);
				return en_count;
			} else {
				printf("device has not clock enable register");
				return -1;
			}
		case CLK_ENABLE:
			if (dev < 128) {
				en_count = enable_dev_clk(dev);
				return en_count;
			} else {
				printf("device has not clock enable register");
				return -1;
			}
		case GET_FREQ:
			last_freq = get_freq(dev, &divisor);
			return last_freq;
		case SET_DIV:
			divisor = 0;
			last_freq = set_divisor(dev, unit, freq, &divisor);
			return last_freq;
		case SET_PLL:
			divisor = 0;
			last_freq = set_pll_speed(dev, unit, freq, &divisor);
			return last_freq;
		case SET_PLLDIV:
			divisor = 0;
			last_freq = set_pll_divisor(dev, unit, freq, &divisor);
			return last_freq;
		default:
		printf("clock cmd unknow");
		return -1;
	}
}
Example #18
0
void fp_node::merge(fp_node *right_node)
{
	// merges two nodes
	// w.r.t. this node is left node an in node is right node

	// adapt frequency and interval
	set_freq( get_freq() + right_node->get_freq());
	set_max( right_node->get_max() );

	// merge children
	fp_nodelist &right_childs = right_node->get_childs();

	fp_nodelist::iterator left_it = m_childs.begin();
	fp_nodelist::iterator right_it = right_childs.begin();

	while (right_it != right_childs.end()){
		if ((left_it == m_childs.end()) || (*right_it)->left_of(*(*left_it))) {
			add_child(*right_it);
			fp_nodelist::iterator tmpit = right_it;
			right_it++;
			right_childs.erase(tmpit);
		} else if ((*left_it)->contains(*(*right_it))) {
			(*left_it)->merge(*right_it); // recursive step
			fp_nodelist::iterator tmpit = right_it;
			right_it++;
			right_childs.erase(tmpit);
		} else if ((*right_it)->contains(*(*left_it))) {
			(*right_it)->merge(*left_it);
			fp_nodelist::iterator tmpit = left_it;
			left_it++;
			m_childs.erase(tmpit);
		} else {
			left_it++;
		}
	}

	// cleanup right node
	delete right_node;
}
Example #19
0
File: spicd.c Project: raszi/spicd
/*
 * Main function.
 */
int main(int argc, char **argv) {
	__u8 value8, current, last = 0;
	int first = 1;
	int pid;
	int fd;
	int c;
	int ac_brightness = SONYPI_DEFAULT_AC_BN;
	int dc_brightness = SONYPI_DEFAULT_DC_BN;

	int cpufreq = 0;
	unsigned int freq;
	unsigned int minimal_frequency = get_freq(CPUFREQ_MIN_DEVICE);
	unsigned int maximal_frequency = get_freq(CPUFREQ_MAX_DEVICE);

	unsigned int dc_freq = minimal_frequency;
	unsigned int ac_freq = maximal_frequency;

	int disable_cpufreq = 0;

	FILE *str;

	static struct option longopts[] = {
		{ "debug", 0, 0, 'd' },
		{ "dc-brightness", 1, 0, 'D' },
		{ "ac-brightness", 1, 0, 'A' },
		{ "version", 0, 0, 'V' },
		{ "help", 0, 0, '?' },
		{ "dc-frequency", 1, 0, 'm' },
		{ "ac-frequency", 1, 0, 'M' },
		{ "disable-cpufreq", 0, 0, 'C' },
		{ NULL, 0, 0, 0 }
	};

	while((c = getopt_long(argc, argv, "?dVCD:A:m:M:", longopts, NULL)) != -1) {
		switch(c) {
			case 'd':
				debug = 1;
				break;
			case 'D':
				dc_brightness = atoi(optarg);
				break;
			case 'A':
				ac_brightness = atoi(optarg);
				break;
			case 'V':
				version();
				break;
			case 'm':
				dc_freq = strtoul(optarg, NULL, 10);
				break;
			case 'M':
				ac_freq = strtoul(optarg, NULL, 10);
				break;
			case 'C':
				disable_cpufreq = 1;
				break;
			case '?':
			default:
				usage();
		}
	}

	if ((dc_brightness < SONYPI_MIN_BRIGHTNESS) || (dc_brightness > SONYPI_MAX_BRIGHTNESS)) {
		if (debug) {
			char *errorstr;
			asprintf(&errorstr, "DC brigthness is out of range. Setting to default value (%d).", SONYPI_DEFAULT_DC_BN);
			error(errorstr, 0);
		}

		dc_brightness = SONYPI_DEFAULT_DC_BN;
	}

	if ((ac_brightness < SONYPI_MIN_BRIGHTNESS) || (ac_brightness > SONYPI_MAX_BRIGHTNESS)) {
		if (debug) {
			char *errorstr;
			asprintf(&errorstr, "spicd: AC brigthness is out of range. Setting to default value (%d).", SONYPI_DEFAULT_AC_BN);
			error(errorstr, 0);
		}

		ac_brightness = SONYPI_DEFAULT_DC_BN;
	}

	if ((dc_freq > maximal_frequency) || (dc_freq < minimal_frequency)) {
		if (debug) {
			char *errorstr;
			asprintf(&errorstr, "DC frequency is out of range. Setting to default value (%d).", minimal_frequency);
			error(errorstr, 0);
		}

		dc_freq =  minimal_frequency;
	}
	if ((ac_freq > maximal_frequency) || (ac_freq < minimal_frequency)) {
		if (debug) {
			char *errorstr;
			asprintf(&errorstr, "AC frequency is out of range. Setting to default value (%d).", maximal_frequency);
			error(errorstr, 0);
		}

		ac_freq =  maximal_frequency;
	}

	if (!access(PID_FILE, R_OK)) {
		if ((str = fopen(PID_FILE, "r"))) {
			fscanf(str, "%d", &pid);
			fclose(str);

			if (!kill(pid, 0) || errno == EPERM) {
				fprintf(stderr,
					"A spicd already appears to be running as process %d\n"
					"If in reality no spicd is running, remove %s\n",
					pid, PID_FILE);
				exit(1);
			}
		}
	}

	if ((spicd_uid = getuid())) {
		fprintf(stderr, "spicd: must be run as root\n");
		exit(1);
	}

	openlog("spicd", LOG_PID | LOG_CONS, LOG_DAEMON);
	if (signal(SIGINT, SIG_IGN) != SIG_IGN) signal(SIGINT, sig_handler);
	if (signal(SIGQUIT, SIG_IGN) != SIG_IGN) signal(SIGQUIT, sig_handler);
	if (signal(SIGTERM, SIG_IGN) != SIG_IGN) signal(SIGTERM, sig_handler);

	if ((pid = fork())) { /* parent */
		if (pid < 0) {
			syslog(LOG_INFO, "fork() failed: %m");
			unlink(PID_FILE);
			exit(1);
		}

		if ((str = fopen(PID_FILE, "w"))) {
			fprintf(str, "%d\n", pid);
			fclose(str);
		}
		exit(0);
	} /* endif parent */

	/* Child.  Follow the daemon rules in
	 * W. Richard Stevens. Advanced Programming
	 * in the UNIX Environment (Addison-Wesley
	 * Publishing Co., 1992). Page 417.).
	 */
	if (setsid() < 0) {
		syslog(LOG_INFO, "setsid() failed: %m");
		unlink(PID_FILE);
		exit(1);
	}
	chdir("/");
	close(0);
	close(1);
	close(2);
	umask(0);

	syslog(LOG_INFO, "daemon starting");

	if ((cpufreq = cpufreq_open()) < 0) {
		if (debug) syslog(LOG_INFO, "cpufreq does not suppported");
	} else if (!disable_cpufreq) {
		cpufreq_fd = cpufreq;
	} else if (debug) {
		syslog(LOG_INFO, "cpufreq support present, but disabled");
	}

	if ((fd = sonypi_open()) < 0) {
		syslog(LOG_INFO, "sonypi_open() failed: %m");
		unlink(PID_FILE);
		exit(1);
	} else {
		sonypi_fd = fd;
	}

	while(1) {
		if (spic_ioctl(sonypi_fd, SONYPI_IOCGBATFLAGS, &value8) < 0) exit(2);
		current = value8 & SONYPI_BFLAGS_AC;
		if ((current != last) && !first) {
			last = current;

			if (debug) syslog(LOG_DEBUG, "AC status changed");

			if (current) {
				/* AC adaptor plugged in */
				value8 = ac_brightness;
				freq = ac_freq;
			} else {
				value8 = dc_brightness;
				freq = dc_freq;
			}

			if (debug) {
				char *debugmsg;

				asprintf(&debugmsg, "Setting LCD brightness to %d", value8);
				syslog(LOG_DEBUG, debugmsg);

				if (cpufreq_fd != -1) {
					asprintf(&debugmsg, "Setting CPU speed to %dKHz", freq);
					syslog(LOG_DEBUG, debugmsg);
				}
			}

			spic_ioctl(sonypi_fd, SONYPI_IOCSBRT, &value8);

			if (cpufreq_fd != -1) cpufreq_ioctl(cpufreq_fd, dc_freq);
		} else if (first) {
			first = 0;
			last = current;
		}

		/* sleep 2 seconds */
		sleep(2);
	}
}
Example #20
0
/* The decrementer counts at the system (internal) clock frequency divided by
 * sixteen, or external oscillator divided by four.  We force the processor
 * to use system clock divided by sixteen.
 */
void __init mpc8xx_calibrate_decr(void)
{
	struct device_node *cpu;
	cark8xx_t __iomem *clk_r1;
	car8xx_t __iomem *clk_r2;
	sitk8xx_t __iomem *sys_tmr1;
	sit8xx_t __iomem *sys_tmr2;
	int irq, virq;

	clk_r1 = immr_map(im_clkrstk);

	/* Unlock the SCCR. */
	out_be32(&clk_r1->cark_sccrk, ~KAPWR_KEY);
	out_be32(&clk_r1->cark_sccrk, KAPWR_KEY);
	immr_unmap(clk_r1);

	/* Force all 8xx processors to use divide by 16 processor clock. */
	clk_r2 = immr_map(im_clkrst);
	setbits32(&clk_r2->car_sccr, 0x02000000);
	immr_unmap(clk_r2);

	/* Processor frequency is MHz.
	 */
	ppc_proc_freq = 50000000;
	if (!get_freq("clock-frequency", &ppc_proc_freq))
		printk(KERN_ERR "WARNING: Estimating processor frequency "
		                "(not found)\n");

	ppc_tb_freq = ppc_proc_freq / 16;
	printk("Decrementer Frequency = 0x%lx\n", ppc_tb_freq);

	/* Perform some more timer/timebase initialization.  This used
	 * to be done elsewhere, but other changes caused it to get
	 * called more than once....that is a bad thing.
	 *
	 * First, unlock all of the registers we are going to modify.
	 * To protect them from corruption during power down, registers
	 * that are maintained by keep alive power are "locked".  To
	 * modify these registers we have to write the key value to
	 * the key location associated with the register.
	 * Some boards power up with these unlocked, while others
	 * are locked.  Writing anything (including the unlock code?)
	 * to the unlocked registers will lock them again.  So, here
	 * we guarantee the registers are locked, then we unlock them
	 * for our use.
	 */
	sys_tmr1 = immr_map(im_sitk);
	out_be32(&sys_tmr1->sitk_tbscrk, ~KAPWR_KEY);
	out_be32(&sys_tmr1->sitk_rtcsck, ~KAPWR_KEY);
	out_be32(&sys_tmr1->sitk_tbk, ~KAPWR_KEY);
	out_be32(&sys_tmr1->sitk_tbscrk, KAPWR_KEY);
	out_be32(&sys_tmr1->sitk_rtcsck, KAPWR_KEY);
	out_be32(&sys_tmr1->sitk_tbk, KAPWR_KEY);
	immr_unmap(sys_tmr1);

	init_internal_rtc();

	/* Enabling the decrementer also enables the timebase interrupts
	 * (or from the other point of view, to get decrementer interrupts
	 * we have to enable the timebase).  The decrementer interrupt
	 * is wired into the vector table, nothing to do here for that.
	 */
	cpu = of_find_node_by_type(NULL, "cpu");
	virq= irq_of_parse_and_map(cpu, 0);
	irq = virq_to_hw(virq);

	sys_tmr2 = immr_map(im_sit);
	out_be16(&sys_tmr2->sit_tbscr, ((1 << (7 - (irq/2))) << 8) |
					(TBSCR_TBF | TBSCR_TBE));
	immr_unmap(sys_tmr2);

	if (setup_irq(virq, &tbint_irqaction))
		panic("Could not allocate timer IRQ!");
}
Example #21
0
File: misc.cpp Project: jeeb/MPGDec
void init_first(ts* timers) {
    memset(timers,0,sizeof(ts));
    timers->div = 0; timers->sum = 0;
    timers->freq = get_freq()/1000;
//  timers->freq = 1412*1000000; // shortcut for my athlon xp 1600+ (1.4 Gz)
}
Example #22
0
int main(int argc, char *argv[])
{
	double freq;
	size_t len;
	int hcc = HCC_DEFAULT, snc = SNC_DEFAULT;
	int forced_mono = FORCED_MONO, mode = SEARCH_MODE_DEFAULT;

	prog_name = basename(argv[0]);

	//open access to the board, send error msg if fails
	if((fd = wiringPiI2CSetup(dID)) < 0) {
		fprintf(stderr, "error opening i2c channel\n");
		exit(1);
	}

	get_station_info();

	if (argc < 2) {
		if ((freq = get_tuned_freq())) {
			set_freq(freq, HCC_DEFAULT, SNC_DEFAULT, FORCED_MONO, 0, 0);
			print_status();
			printf("HCC: %s, SNC: %s\n", HCC_DEFAULT ? "On" : "Off", SNC_DEFAULT ? "On" : "Off");
		}
		else usage();
		exit(0);
	}

	len = strlen(argv[1]);
	if (!strncmp(argv[1], "scan", len)) {
		if (argc > 2) {
			mode = atoi(argv[2]);
			if (mode < 1) mode  = 1;
			else if (mode > 3) mode = 3;
			if (argc > 3) {
				len = strlen(argv[3]);
				if (!strncmp(argv[3], "mono", len)) forced_mono = 1;
				else forced_mono = 0;
			}
		}
		freq_scan(mode, forced_mono);
	}
	else if (!strncmp(argv[1], "status", len)) {
		print_status();
	}
	else if (!strncmp(argv[1], "next", len)) {
		preset_move(1);
		print_status();
	}
	else if (!strncmp(argv[1], "prev", len)) {
		preset_move(0);
		print_status();
	}
	else if (!strncmp(argv[1], "stereo", len)) {
		set_freq(get_freq(), HCC_DEFAULT, SNC_DEFAULT, 0, 0, 0);
	}
	else if (!strncmp(argv[1], "mono", len)) {
		set_freq(get_freq(), HCC_DEFAULT, SNC_DEFAULT, 1, 0, 0);
	}
	else if (!strncmp(argv[1], "up", len) || !strncmp(argv[1], "down", len)) {
		int dir;
		if (!strncmp(argv[1], "up", len)) dir = 1;
		else dir = 0;
		if (argc > 2) {
			mode = atoi(argv[2]);
			if (mode < 1) mode  = 1;
			else if (mode > 3) mode = 3;
			if (argc > 3) {
				len = strlen(argv[3]);
				if (!strncmp(argv[3], "mono", len)) forced_mono = 1;
				else forced_mono = 0;
			}
		}
		search(dir, mode, forced_mono);
		print_status();
		save_freq(get_freq());
	}
	else if (!strncmp(argv[1], "stepup", len)) {
		freq = get_freq() + 0.1;
		if (freq < 76.0 || freq > 108.0) exit(2);
		set_freq(get_freq()+0.1, HCC_DEFAULT, SNC_DEFAULT, FORCED_MONO, 0, 0);
		print_status();
		save_freq(get_freq());
	}
	else if (!strncmp(argv[1], "stepdown", len)) {
		freq = get_freq() - 0.1;
		if (freq < 76.0 || freq > 108.0) exit(2);
		set_freq(freq, HCC_DEFAULT, SNC_DEFAULT, FORCED_MONO, 0, 0);
		print_status();
		save_freq(get_freq());
	}
	else if (!strncmp(argv[1], "mute", len)) {
		set_freq(get_freq(), HCC_DEFAULT, SNC_DEFAULT, FORCED_MONO, 1, 0);
	}
	else if (!strncmp(argv[1], "unmute", len)) {
		set_freq(get_freq(), HCC_DEFAULT, SNC_DEFAULT, FORCED_MONO, 0, 0);
	}
	else if (!strncmp(argv[1], "off", len)) {
		set_freq(get_freq(), HCC_DEFAULT, SNC_DEFAULT, FORCED_MONO, 0, 1);
	}
	else if (!strncmp(argv[1], "on", len)) {
		set_freq(get_freq(), HCC_DEFAULT, SNC_DEFAULT, FORCED_MONO, 0, 0);
	}
	else {
		int preset;

		freq = strtod(argv[1], NULL);
		preset = (int)freq - 1;

		if ((freq >= 76.0 && freq <= 108.0) || (preset >= 0 && preset < station_info_num)) {
			if (freq >= 76.0 && freq <= 108.0) freq = strtod(argv[1], NULL);
			else freq = station_info[preset].freq;

			if (argc > 2) {
				if (atoi(argv[2]) != 0) hcc = 1;
				else hcc = 0;
				if (argc > 3) {
					if (atoi(argv[3]) != 0) snc = 1;
					else snc = 0;
					if (argc > 4) {
						len = strlen(argv[4]);
						if (!strncmp(argv[4], "mono", len)) forced_mono = 1;
						else forced_mono = 0;
					}
				}
			}
			set_freq(freq, hcc, snc, forced_mono, 0, 0);
			print_status();
			printf("HCC: %s, SNC: %s\n", hcc ? "On" : "Off", snc ? "On" : "Off");
		}
		else usage();
	}

	close(fd);
	return 0;
}
Example #23
0
static bool gridseed_detect_one(libusb_device *dev, struct usb_find_devices *found)
{
	struct cgpu_info *gridseed;
	GRIDSEED_INFO *info;
	int err, wrote, def_freq_inx;
	unsigned char rbuf[GRIDSEED_READ_SIZE];
#if 0
	const char detect_cmd[] =
		"55aa0f01"
		"4a548fe471fa3a9a1371144556c3f64d"
		"2500b4826008fe4bbf7698c94eba7946"
		"ce22a72f4f6726141a0b3287eeeeeeee";
	unsigned char detect_data[52];
#else
	const char detect_cmd[] = "55aac000909090900000000001000000";
	unsigned char detect_data[16];
#endif

	gridseed = usb_alloc_cgpu(&gridseed_drv, GRIDSEED_MINER_THREADS);
	if (!usb_init(gridseed, dev, found))
		goto shin;

	libusb_reset_device(gridseed->usbdev->handle);

	info = (GRIDSEED_INFO*)calloc(sizeof(GRIDSEED_INFO), 1);
	if (unlikely(!info))
		quit(1, "Failed to calloc gridseed_info data");
	gridseed->device_data = (void *)info;

	info->baud = GRIDSEED_DEFAULT_BAUD;
	info->freq = GRIDSEED_DEFAULT_FREQUENCY;
	def_freq_inx = gc3355_find_freq_index(GRIDSEED_DEFAULT_FREQUENCY);
	memcpy(info->freq_cmd, bin_frequency[def_freq_inx], 8);
	info->chips = GRIDSEED_DEFAULT_CHIPS;
	info->voltage = 0;
	info->per_chip_stats = 0;
	info->serial = strdup(gridseed->usbdev->serial_string);
	memset(info->nonce_count, 0, sizeof(info->nonce_count));
	memset(info->error_count, 0, sizeof(info->error_count));

	get_options(info, opt_gridseed_options);
	get_freq(info, opt_gridseed_freq);
	get_chips(info, opt_gridseed_chips);

	update_usb_stats(gridseed);

	gridseed->usbdev->usb_type = USB_TYPE_STD;
	gridseed_initialise(gridseed, info);

	/* get MCU firmware version */
	hex2bin(detect_data, detect_cmd, sizeof(detect_data));
	if (gc3355_write_data(gridseed, detect_data, sizeof(detect_data))) {
		applog(LOG_DEBUG, "Failed to write work data to %i, err %d",
			gridseed->device_id, err);
		goto unshin;
	}

	/* waiting for return */
	if (gc3355_get_data(gridseed, rbuf, GRIDSEED_READ_SIZE)) {
		applog(LOG_DEBUG, "No response from %i", gridseed->device_id);
		goto unshin;
	}

	if (memcmp(rbuf, "\x55\xaa\xc0\x00\x90\x90\x90\x90", GRIDSEED_READ_SIZE-4) != 0) {
		applog(LOG_DEBUG, "Bad response from %i",
			gridseed->device_id);
		goto unshin;
	}

	info->fw_version = le32toh(*(uint32_t *)(rbuf+8));
	applog(LOG_NOTICE, "Device found, firmware version %08X, driver version %s",
		info->fw_version, gridseed_version);

	gc3355_init(gridseed, info);

	gridseed->algorithm = default_algorithm;

	if (!add_cgpu(gridseed))
		goto unshin;

	return true;

unshin:
	usb_uninit(gridseed);
	free(gridseed->device_data);
	gridseed->device_data = NULL;

shin:
	gridseed = usb_free_cgpu(gridseed);
	return false;
}
Example #24
0
int
main(int argc, char * argv[])
{
	struct timeval timeout;
	fd_set fdset;
	int nfds;
	struct pidfh *pfh = NULL;
	const char *pidfile = NULL;
	int freq, curfreq, initfreq, *freqs, i, j, *mwatts, numfreqs, load;
	int minfreq = -1, maxfreq = -1;
	int ch, mode, mode_ac, mode_battery, mode_none, idle, to;
	uint64_t mjoules_used;
	size_t len;

	/* Default mode for all AC states is adaptive. */
	mode_ac = mode_none = MODE_HIADAPTIVE;
	mode_battery = MODE_ADAPTIVE;
	cpu_running_mark = DEFAULT_ACTIVE_PERCENT;
	cpu_idle_mark = DEFAULT_IDLE_PERCENT;
	poll_ival = DEFAULT_POLL_INTERVAL;
	mjoules_used = 0;
	vflag = 0;

	/* User must be root to control frequencies. */
	if (geteuid() != 0)
		errx(1, "must be root to run");

	while ((ch = getopt(argc, argv, "a:b:i:m:M:n:p:P:r:v")) != -1)
		switch (ch) {
		case 'a':
			parse_mode(optarg, &mode_ac, ch);
			break;
		case 'b':
			parse_mode(optarg, &mode_battery, ch);
			break;
		case 'i':
			cpu_idle_mark = atoi(optarg);
			if (cpu_idle_mark < 0 || cpu_idle_mark > 100) {
				warnx("%d is not a valid percent",
				    cpu_idle_mark);
				usage();
			}
			break;
		case 'm':
			minfreq = atoi(optarg);
			if (minfreq < 0) {
				warnx("%d is not a valid CPU frequency",
				    minfreq);
				usage();
			}
			break;
		case 'M':
			maxfreq = atoi(optarg);
			if (maxfreq < 0) {
				warnx("%d is not a valid CPU frequency",
				    maxfreq);
				usage();
			}
			break;
		case 'n':
			parse_mode(optarg, &mode_none, ch);
			break;
		case 'p':
			poll_ival = atoi(optarg);
			if (poll_ival < 5) {
				warnx("poll interval is in units of ms");
				usage();
			}
			break;
		case 'P':
			pidfile = optarg;
			break;
		case 'r':
			cpu_running_mark = atoi(optarg);
			if (cpu_running_mark <= 0 || cpu_running_mark > 100) {
				warnx("%d is not a valid percent",
				    cpu_running_mark);
				usage();
			}
			break;
		case 'v':
			vflag = 1;
			break;
		default:
			usage();
		}

	mode = mode_none;

	/* Poll interval is in units of ms. */
	poll_ival *= 1000;

	/* Look up various sysctl MIBs. */
	len = 2;
	if (sysctlnametomib("kern.cp_times", cp_times_mib, &len))
		err(1, "lookup kern.cp_times");
	len = 4;
	if (sysctlnametomib("dev.cpu.0.freq", freq_mib, &len))
		err(EX_UNAVAILABLE, "no cpufreq(4) support -- aborting");
	len = 4;
	if (sysctlnametomib("dev.cpu.0.freq_levels", levels_mib, &len))
		err(1, "lookup freq_levels");

	/* Check if we can read the load and supported freqs. */
	if (read_usage_times(NULL))
		err(1, "read_usage_times");
	if (read_freqs(&numfreqs, &freqs, &mwatts, minfreq, maxfreq))
		err(1, "error reading supported CPU frequencies");
	if (numfreqs == 0)
		errx(1, "no CPU frequencies in user-specified range");

	/* Run in the background unless in verbose mode. */
	if (!vflag) {
		pid_t otherpid;

		pfh = pidfile_open(pidfile, 0600, &otherpid);
		if (pfh == NULL) {
			if (errno == EEXIST) {
				errx(1, "powerd already running, pid: %d",
				    otherpid);
			}
			warn("cannot open pid file");
		}
		if (daemon(0, 0) != 0) {
			warn("cannot enter daemon mode, exiting");
			pidfile_remove(pfh);
			exit(EXIT_FAILURE);

		}
		pidfile_write(pfh);
	}

	/* Decide whether to use ACPI or APM to read the AC line status. */
	acline_init();

	/*
	 * Exit cleanly on signals.
	 */
	signal(SIGINT, handle_sigs);
	signal(SIGTERM, handle_sigs);

	freq = initfreq = curfreq = get_freq();
	i = get_freq_id(curfreq, freqs, numfreqs);
	if (freq < 1)
		freq = 1;

	/*
	 * If we are in adaptive mode and the current frequency is outside the
	 * user-defined range, adjust it to be within the user-defined range.
	 */
	acline_read();
	if (acline_status > SRC_UNKNOWN)
		errx(1, "invalid AC line status %d", acline_status);
	if ((acline_status == SRC_AC &&
	    (mode_ac == MODE_ADAPTIVE || mode_ac == MODE_HIADAPTIVE)) ||
	    (acline_status == SRC_BATTERY &&
	    (mode_battery == MODE_ADAPTIVE || mode_battery == MODE_HIADAPTIVE)) ||
	    (acline_status == SRC_UNKNOWN &&
	    (mode_none == MODE_ADAPTIVE || mode_none == MODE_HIADAPTIVE))) {
		/* Read the current frequency. */
		len = sizeof(curfreq);
		if (sysctl(freq_mib, 4, &curfreq, &len, NULL, 0) != 0) {
			if (vflag)
				warn("error reading current CPU frequency");
		}
		if (curfreq < freqs[numfreqs - 1]) {
			if (vflag) {
				printf("CPU frequency is below user-defined "
				    "minimum; changing frequency to %d "
				    "MHz\n", freqs[numfreqs - 1]);
			}
			if (set_freq(freqs[numfreqs - 1]) != 0) {
				warn("error setting CPU freq %d",
				    freqs[numfreqs - 1]);
			}
		} else if (curfreq > freqs[0]) {
			if (vflag) {
				printf("CPU frequency is above user-defined "
				    "maximum; changing frequency to %d "
				    "MHz\n", freqs[0]);
			}
			if (set_freq(freqs[0]) != 0) {
				warn("error setting CPU freq %d",
				    freqs[0]);
			}
		}
	}

	idle = 0;
	/* Main loop. */
	for (;;) {
		FD_ZERO(&fdset);
		if (devd_pipe >= 0) {
			FD_SET(devd_pipe, &fdset);
			nfds = devd_pipe + 1;
		} else {
			nfds = 0;
		}
		if (mode == MODE_HIADAPTIVE || idle < 120)
			to = poll_ival;
		else if (idle < 360)
			to = poll_ival * 2;
		else
			to = poll_ival * 4;
		timeout.tv_sec = to / 1000000;
		timeout.tv_usec = to % 1000000;
		select(nfds, &fdset, NULL, &fdset, &timeout);

		/* If the user requested we quit, print some statistics. */
		if (exit_requested) {
			if (vflag && mjoules_used != 0)
				printf("total joules used: %u.%03u\n",
				    (u_int)(mjoules_used / 1000),
				    (int)mjoules_used % 1000);
			break;
		}

		/* Read the current AC status and record the mode. */
		acline_read();
		switch (acline_status) {
		case SRC_AC:
			mode = mode_ac;
			break;
		case SRC_BATTERY:
			mode = mode_battery;
			break;
		case SRC_UNKNOWN:
			mode = mode_none;
			break;
		default:
			errx(1, "invalid AC line status %d", acline_status);
		}

		/* Read the current frequency. */
		if (idle % 32 == 0) {
			if ((curfreq = get_freq()) == 0)
				continue;
			i = get_freq_id(curfreq, freqs, numfreqs);
		}
		idle++;
		if (vflag) {
			/* Keep a sum of all power actually used. */
			if (mwatts[i] != -1)
				mjoules_used +=
				    (mwatts[i] * (poll_ival / 1000)) / 1000;
		}

		/* Always switch to the lowest frequency in min mode. */
		if (mode == MODE_MIN) {
			freq = freqs[numfreqs - 1];
			if (curfreq != freq) {
				if (vflag) {
					printf("now operating on %s power; "
					    "changing frequency to %d MHz\n",
					    modes[acline_status], freq);
				}
				idle = 0;
				if (set_freq(freq) != 0) {
					warn("error setting CPU freq %d",
					    freq);
					continue;
				}
			}
			continue;
		}

		/* Always switch to the highest frequency in max mode. */
		if (mode == MODE_MAX) {
			freq = freqs[0];
			if (curfreq != freq) {
				if (vflag) {
					printf("now operating on %s power; "
					    "changing frequency to %d MHz\n",
					    modes[acline_status], freq);
				}
				idle = 0;
				if (set_freq(freq) != 0) {
					warn("error setting CPU freq %d",
					    freq);
					continue;
				}
			}
			continue;
		}

		/* Adaptive mode; get the current CPU usage times. */
		if (read_usage_times(&load)) {
			if (vflag)
				warn("read_usage_times() failed");
			continue;
		}

		if (mode == MODE_ADAPTIVE) {
			if (load > cpu_running_mark) {
				if (load > 95 || load > cpu_running_mark * 2)
					freq *= 2;
				else
					freq = freq * load / cpu_running_mark;
				if (freq > freqs[0])
					freq = freqs[0];
			} else if (load < cpu_idle_mark &&
			    curfreq * load < freqs[get_freq_id(
			    freq * 7 / 8, freqs, numfreqs)] *
			    cpu_running_mark) {
				freq = freq * 7 / 8;
				if (freq < freqs[numfreqs - 1])
					freq = freqs[numfreqs - 1];
			}
		} else { /* MODE_HIADAPTIVE */
			if (load > cpu_running_mark / 2) {
				if (load > 95 || load > cpu_running_mark)
					freq *= 4;
				else
					freq = freq * load * 2 / cpu_running_mark;
				if (freq > freqs[0] * 2)
					freq = freqs[0] * 2;
			} else if (load < cpu_idle_mark / 2 &&
			    curfreq * load < freqs[get_freq_id(
			    freq * 31 / 32, freqs, numfreqs)] *
			    cpu_running_mark / 2) {
				freq = freq * 31 / 32;
				if (freq < freqs[numfreqs - 1])
					freq = freqs[numfreqs - 1];
			}
		}
		if (vflag) {
		    printf("load %3d%%, current freq %4d MHz (%2d), wanted freq %4d MHz\n",
			load, curfreq, i, freq);
		}
		j = get_freq_id(freq, freqs, numfreqs);
		if (i != j) {
			if (vflag) {
				printf("changing clock"
				    " speed from %d MHz to %d MHz\n",
				    freqs[i], freqs[j]);
			}
			idle = 0;
			if (set_freq(freqs[j]))
				warn("error setting CPU frequency %d",
				    freqs[j]);
		}
	}
	if (set_freq(initfreq))
		warn("error setting CPU frequency %d", initfreq);
	free(freqs);
	free(mwatts);
	devd_close();
	if (!vflag)
		pidfile_remove(pfh);

	exit(0);
}
Example #25
0
void show_temp_internal2(int num)
{
	int nc, x, y, krp, nm;
	double  norm;
	double tleft, tright, norml, normr;
	PARTICLE *p;
	VECTOR v0;
	nc = 0;
	for (y = 0; y < KY ; y++)
	{
		for (x = 0; x < KX; x++)
		{
			norm = 0.0;
			v0.x = v0.y = v0.z = 0.0;
			norml = tleft = 0.0;
			normr = tright = 0.0;
			for (nc = 0; nc < NC; nc++)
			{
				for (nm = 0; nm < NM; nm++)
				{
					for (krp = 0; krp < KRP; krp++)
					{
						p = &camera[krp][x][y][nc][nm];
						v0.x += p->v.x * p->weight;
						v0.y += p->v.y * p->weight;
						v0.z += p->v.z * p->weight;
						norm += p->weight;
					}
				}
				multiply(&v0, &v0, (1.0/norm));
			}
			for (nc = 0; nc < NC; nc++)
			{
				for (nm = 0; nm < NM; nm++)
				{
					for (krp = 0; krp < KRP; krp++)
					{
						p = &camera[krp][x][y][nc][nm];
						tleft += get_temp(p, &v0);
						tright += p->rot_energy*p->weight;
					}
				}
			}
			tleft /= norm;
			tright = tright * 4.0 / (norm * 2.0 * 2.0*K);
			fprintf(plot_file, "%.6f %.6f; %.6f; %.6f; %.6f\n", num*dtp,tleft, tright, (tleft * 3.0 + 2.0*tright) / (3.0 + 2.0), num*dtp*get_freq(tleft));
			printf("trans = %.5f;  rotational = %.5f; overal = %.5f\n", tleft, tright, (tleft * 3.0 + 2.0*tright) / (3.0 + 2.0));
		}
	}
}
Example #26
0
int main(int argc, char *argv[])
{
	/* Packet counter */
	int cnt = 0;

	/* Packet number of last acked data frame */
	int last_acked = 0;

	/* Packet number of last roam */
	int last_swap = 0;
	struct ether_addr dut_addr, *tmp_eth, tmp_ta;
	uint16_t tmp_seqnr;

	/* Details of packet from previous BSS */
	struct pcap_pkthdr last_data_hdr = {};
	struct ether_addr last_bss = {};
	uint16_t last_freq = 0;

	/* Details packet from current BSS */
	struct pcap_pkthdr curr_data_hdr;
	struct ether_addr curr_bss = {};
	uint16_t curr_freq;

	struct pcap_pkthdr *hdr;
	uint16_t radiotap_len;

	int ret;
	char pcap_err[PCAP_ERRBUF_SIZE];
	const uint8_t *rp, *wp;
	unsigned char ftype;

	if (argc != 3)
		usage(argv);

	tmp_eth = ether_aton(argv[2]);
	if (!tmp_eth)
		usage(argv);
	memcpy(&dut_addr, tmp_eth, sizeof(dut_addr));

	pcap_t *pcap = pcap_open_offline(argv[1], pcap_err);
	if (!pcap) {
		printf("Error %s\n", pcap_err);
		exit(1);
	}

	printf("BSSID                                  Frame#              Time (ms)   Freq\n");
	while (1) {
		ret = pcap_next_ex(pcap, &hdr, &rp);
		cnt++;
		if (ret < 0)
			break;

		radiotap_len = rp[2] | rp[3] << 8;
		wp = rp + radiotap_len;

		ftype = get_pkt_type(wp);

		/* Match data packets with dut's RA or TA */
		if ((ftype == 0x28 || ftype == 0x20) &&
		    (cmp_eth(wp + RA_POS, &dut_addr) ||
		     cmp_eth(wp + TA_POS, &dut_addr))) {

			/* Get BSS of current packet */
			if (cmp_eth(wp + TA_POS, &dut_addr))
				memcpy(&curr_bss, wp + RA_POS, 6);
			else
				memcpy(&curr_bss, wp + TA_POS, 6);

			/* Save info about the data packet. Checking for the ack
			   will overwrite */
			memcpy(&tmp_ta, wp + TA_POS, 6);
			memcpy(&curr_data_hdr, hdr, sizeof(curr_data_hdr));
			curr_freq = get_freq(rp);
			tmp_seqnr = get_seqnr(wp);

			/* Check if packet was ACKed */
			ret = pcap_next_ex(pcap, &hdr, &rp);
			radiotap_len = rp[2] | rp[3] << 8;
			wp = rp + radiotap_len;
			cnt++;
			if (ret < 0)
				break;
			if (is_pkt_acked(wp, &tmp_ta, tmp_seqnr)) {
//				printf("Packet # %06d %d:%d %08d %02x\n", cnt, (int)hdr->ts.tv_sec, (int)hdr->ts.tv_usec, hdr->len, ftype);
//				printf("%d Acked %s--", cnt, ether_ntoa(&tmp_bss));
//				printf("%s\n", ether_ntoa(&tmp_ta));

				/* BSS changed? */
				if (memcmp(&last_bss, &curr_bss, sizeof(last_bss)) != 0) {
					if (last_swap) {
						double delta = (get_timestamp(&curr_data_hdr) - get_timestamp(&last_data_hdr)) / 1000;
						printf("%s", ether_ntoa(&last_bss));
						printf(" -> %s %7d -> %7d ", ether_ntoa(&curr_bss), last_acked-1, cnt-1);
						printf("%12f ", delta);
						printf("%04d -> %04d ", last_freq, curr_freq);
//						printf("(%f - %f)", get_timestamp(&curr_data_hdr), get_timestamp(&last_data_hdr));
						printf("\n");
					}
					memcpy(&last_bss, &curr_bss, sizeof(last_bss));
					last_swap = cnt;
				}
				last_acked = cnt;
				last_freq = curr_freq;
				memcpy(&last_data_hdr, &curr_data_hdr, sizeof(last_data_hdr));
			}
		}
	}
	printf("Analyzed %d frames\n", cnt);
	return 0;
}
Example #27
0
void
handle_common_option(int opt) {
	unsigned				num;
	char 					*cp;
	
   	if(!cpu_handle_common_option(opt)) {
		switch(opt) {
		case 'D':
			/* kprintf output channel */
			debug_opt[0] = optarg;
			break;
		case 'f':
			/* cpu frequency, clock cycles frequency, timer chip frequency */
			get_freq(&cpu_freq);
			get_freq(&cycles_freq);
			get_freq(&timer_freq);
			break;
		case 'K':
			/* kdebug remote debug protocol channel */
			debug_opt[1] = optarg;
			break;
		case 'N':
			add_typed_string(_CS_HOSTNAME, optarg);
			break;
		case 'R':
			reserved_size = getsize(optarg, &cp);
			if(*cp == ',') {
				reserved_align = getsize(cp + 1, &cp);
			}
			break;
		case 'S':
			//This gets handled later so that debug code isn't brought in all
			//the time.
			break;
		case 'P':
			num = strtoul(optarg, &optarg, 10);
			if(num > 0) max_cpus = num;
			break;
		case 'v':
			debug_flag++;
			break;
		case 'F':	
		case 'A':
		case 'M':
		case 'r':
		case 'j':
			// All handled later, see init_system_private...
			break;
		case 'I':
			// Fastboot/Restore IFS
			rifs_flag |= RIFS_FLAG_ENABLE;

			num = strtoul(optarg, &optarg, 10);
			if(num) {
				rifs_flag |= RIFS_FLAG_CKSUM;
			}
			break;
		case 'i':
			// Fastboot/Secondary IFS
			rifs_flag |= RIFS_FLAG_IFS2;
			ifs2_size = strtoul(optarg, &optarg, 0);

			// Valid flags are: 'R', 'RK', or 'K' (equivalent to 'RK')
			if(cp = strchr(optarg, ',')) {
				if(*(cp + 1) == 'R') {
					rifs_flag |= RIFS_FLAG_IFS2_RESTORE;
					cp++;
				}
				if(*(cp + 1) == 'K') {
					rifs_flag |= RIFS_FLAG_IFS2_RESTORE;
					rifs_flag |= RIFS_FLAG_IFS2_CKSUM;
					cp++;
				}
			}
			if(cp = strchr(cp, ',')) {
				rifs_flag |= RIFS_FLAG_IFS2_SRC;
				ifs2_paddr_src = strtoul(cp + 1, &cp, 0);
			}
			if(cp = strchr(cp, ',')) {
				rifs_flag |= RIFS_FLAG_IFS2_DST;
				// Get destination value and make sure it is at a 4K page boundary
				ifs2_paddr_dst = 0xFFFFF000 & strtoul(cp + 1, &cp, 0);
			}
			break;
		}
	}
}
Example #28
0
char MySniff::cfg_chann(char *channels)
{
	int tmp;
	uint8_t default_channels[]=
	{
		1, 7, 13, 2, 8, 3, 9, 4, 10, 5, 11, 6, 12, 0
		//1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 0
	};
	
	if (is_offline() != 0){
		xlog_err(LEVEL1,parent,"Alert","Can't set channels in offline mode");
		return -1;
	}
	
	if ((settings & XSNIFF_SETTING_IS_SET_INTERFACE) == 0){
		xlog_err(LEVEL2,parent,"Alert","First you must configure interface!");
		return -1;
	}
	
	if (channels==NULL){
		if (init_default_channels(default_channels) < 0){
			xlog_err(LEVEL2,parent,"Alert","Can't init default channels");
			return -1;
		}
		
	}else{
		if (parse_own_channels(channels)<0){
			xlog_err(LEVEL2,parent,"Alert","Can't parse channels. You must enter just positive numbers (lower than 255) and comas Eg: 1,2,3,4,5");
			return -1;
		}
	}
	
	tmp=verify_freq();
	if (tmp!=0){
		if (tmp>0){
			xlog_err(LEVEL2,parent,"Alert","Unsuported channel %d (%d MHz)",get_channel(tmp-1),get_freq(tmp-1));
			return -1;
		}else{
			xlog_err(LEVEL2,parent,"Alert","Can't set channels");
			return -1;
		}
	}
		
	settings = settings | XSNIFF_SETTING_IS_SET_FREQ; 
	
	return 0;
	
}
Example #29
0
int get_pitch_saliencies(complex *buffer, int **indices, double **weights)
{ //{{{
	// CALCULATION OF SIMULTANEOUS MASKING COEFFICIENTS

	// calculate tonal simultaneous masking
	// see "Algorithm for extraction of pitch and pitch salience from
	// complex tonal signals", by Terhardt, Stoil, Seewann

	double amp_dB[FREQ_LEN]; // the amplitude of each freq component in dB
	get_amp_dB(buffer,amp_dB);

	int *tonal_indices = NULL;
	int num_tonal = get_tonal_freqs(amp_dB, &tonal_indices);

	// iterate through tonal frequency components, and calculate the sound
	// pressure level excess of each one.
	double *pitch_weights = (double *)malloc(num_tonal * sizeof(double));
	double intra_mask = 0;
	for(int j = 0; j < num_tonal; j++){
		int i = tonal_indices[j];

		// calculate frequency and critical band of the component

		// effect of other frequencies on spl_excess
		double inter_mask = get_inter_mask(amp_dB, tonal_indices, num_tonal, i);
		printf("freq = %lf, inter_mask = %lf, ", get_freq(i), inter_mask);

		// effect of non-tonal components on spl_excess.
		double noise_mask = get_noise_mask(amp_dB, tonal_indices, num_tonal, i);
		printf("noise_mask = %lf, ", noise_mask);

		// effect of the threshold of quiet - even in silence a frequency of this
		double freq = get_freq(i);
		double q_mask = get_quiet_thresh(freq);
		q_mask = pow(10,q_mask/10);
		printf("q_mask = %lf, ", q_mask);

		// see equation (4) of terhardt
		double spl_excess = amp_dB[i] - (10*log(inter_mask + noise_mask + q_mask));
		printf("SPL excess = %lf\n", spl_excess);

		// "the extent to which each tonal component contributes to the entire tonal
		// percept is considered to depend on (1) the SPL excess and (2) the
		// frequency of the component."  See eqn (12)
		pitch_weights[j] = get_pitch_weight(spl_excess, get_freq(i));
	}

	*indices = tonal_indices;
	*weights = pitch_weights;

	// Temporal masking: ~1:25 Ambikairajah
	//  Jesteadt et al. : M_f(t,m) = a*(b-log_10 dt)(L(t,m)-c)
	// a, b, c are parameters that can be derived from psychoacoustic data
	// a is based on the slope of the time course of masking
	// b = log_10(forward masking duratioin = 200)


	// Masking threshold = (TM^P + SN^P)^{1/P},
	// where TM = temporal masking, SM = simultaneous masking
	// often P = 5 seems to work pretty well

	// TODO change return value
	return num_tonal;
} //}}}
Example #30
0
// Input: Command, a string containing the encoded note (or chord) information
// Currel: which element of the freq and duration arrays we should start at
// Output: freq, an array containing the index of the frequency to be
// played. If pause, the array element will be -1.
// duration: double array giving the duration of the tone in milliseconds.
// num_els: How many elements were actually added by this command (for chords,
// it will typically be several)
void resolve_command(char command[], int currel, int freq[], double duration[], int *num_els)
{
    int currpos = 0;
    int numfound;
    int searchlen;
    int numerator, denominator;
    int currdivision;
    int octave;
    int tone;
    int dum;
    int oct_offset;
    int i;
    duration[currel] = 0;
    if (command[0] == 'P')
    {
        *num_els = 1;
        freq[currel] = -1;
        // We want a pause - must find its length
        currpos++;
        do
        {
            if (command[currpos] == '[')
            {
                numfound = sscanf(command + currpos, "[%d/%d]%n", &numerator, &denominator, &searchlen);
                if (numfound != 3)
                {
                    printf("Error in Pause resolution - number of arguments found are wrong\n");
                    printf("%d\n", numfound);
                    exit(0);
                }
                currpos += searchlen;
                duration[currel] += (double)numerator / (double)denominator;
            }
            else
            {
                //Input should be a number
                currdivision = command[currpos] - '0';
                duration[currel] += pow(0.5, currdivision);
                currpos++;
            }
        } while (command[currpos] != 0);
        duration[currel] *= ref_time;
    }
    // We want a chord (two tones per chord as of now). Will have the general
    // form "C3DfEs012'
    else if (command[0] == 'C')
    {
        *num_els = 2;
        currpos++;
        //Go through the two notes
        for (i=0; i<2; i++)
        {
            octave = command[currpos] -'0';
            currpos++;
            tone = freq_map[command[currpos]];
            oct_offset = octave_offset[command[currpos]];
            if (tone == -400)
            {
                printf("Error in note resolution - note has invalid value\n");
                exit(0);
            }
            currpos++;
            if (islower(command[currpos]))
            {
                dum = offset_map[command[currpos]];
                if (dum == -1000)
                {
                    printf("Error in note resolution - sharp/flat has invalid value\n");
                    exit(0);
                }
                tone += dum;
                currpos++;
            }
            freq[currel+i] = get_freq(octave+oct_offset, tone);
        }
        duration[currel] = ref_time * pow(0.5, CHORD_LENGTH);
        do
        {
            if (command[currpos] == '[')
            {
                numfound = sscanf(command + currpos, "[%d/%d]%n", &numerator, &denominator, &searchlen);
                if (numfound != 3)
                {
                    printf("Error in note resolution - number of arguments found are wrong\n");
                    printf("%d\n", numfound);
                    exit(0);
                }
                currpos += searchlen;
                duration[currel + 1] += (double)numerator / (double)denominator;
            }
            else
            {
                //Input should be a number
                currdivision = command[currpos] - '0';
                duration[currel + 1] += pow(0.5, currdivision);
                currpos++;
            }
        } while (command[currpos] != 0);
        duration[currel+1] *= ref_time;
    }
    else
    {
        *num_els = 1;
        // We want a tone - must find its frequency and length
        octave = command[0] - '0';
//        printf("octave %d\n", octave);
        currpos++;
        tone = freq_map[command[currpos]];
        oct_offset = octave_offset[command[currpos]];
        if (tone == -400)
        {
            printf("Error in note resolution - note has invalid value\n");
            exit(0);
        }
//        printf("commandcurrpos %d\n", command[currpos]);
        currpos++;
        if (isalpha(command[currpos]))
        {
            // Means we want a 'sharp' or 'flat' tone
            dum = offset_map[command[currpos]];
            if (dum == -1000)
            {
                printf("Error in note resolution - sharp/flat has invalid value\n");
                exit(0);
            }
            tone += dum;
            currpos++;
        }
        freq[currel] = get_freq(octave + oct_offset, tone); 
        do
        {
            if (command[currpos] == '[')
            {
                numfound = sscanf(command + currpos, "[%d/%d]%n", &numerator, &denominator, &searchlen);
                if (numfound != 3)
                {
                    printf("Error in note resolution - number of arguments found are wrong\n");
                    printf("%d\n", numfound);
                    exit(0);
                }
                currpos += searchlen;
                duration[currel] += (double)numerator / (double)denominator;
            }
            else
            {
                //Input should be a number
                currdivision = command[currpos] - '0';
                duration[currel] += pow(0.5, currdivision);
                currpos++;
            }
        } while (command[currpos] != 0);
        duration[currel] *= ref_time;
    }
}