예제 #1
0
int main( void )
{
	SWORD a, b;
	SWORD a1, b1;
	SWORD mina = 0, minb = 0;
	FILE *IN, *OUT;
	int firsttime = 1;
	if ((IN = fopen("gcm.in", "rt")) == NULL)
		return 1;
	if ((OUT = fopen("gcm.out", "wt")) == NULL)
	{
		fclose(IN);
		return 1;
	}
	
	fscanf(IN, "%I64d", &a);
	fscanf(IN, "%I64d", &b);

	for (a1 = min(a, b); a1 <= max(a, b); a1++)
	{
		b1 = a * b / a1;
		if (NOD(a, b) == NOD(a1, b1) && NOK(a, b) == NOK(a1, b1))
			if ((my_abs(a1 - b1) < my_abs(mina - minb)) || firsttime)
			{
			mina = a1;
			minb = b1;
			firsttime = 0;
			}
	}

	fprintf(OUT, "%I64d %I64d", mina, minb);
	fclose(IN);
	fclose(OUT);
	return 0;
}
예제 #2
0
/* imprime les nombres avec la base voulu */
int my_putnbr(int nombre, int base) 
{
	int flag = 0;
	char base16[16]={'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'}; 	/* tableau utilisé avec les bases */
	char base_16[16]={'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};	/* tableau utilisé pour le spécifieur 'X'
												   appelé avec la base '-16'
	les utilisation de my_abs sont pour faire en sorte que la fonction marche même quand la base '-16' sera appelé */
	if (nombre>=my_abs(base))
	{

		my_putnbr(nombre /my_abs(base),base);
	}
	if (base<0)
	{
	

		my_putchar(base_16[nombre%my_abs(base)]);	

	}
	else
	{
		my_putchar(base16[nombre%my_abs(base)]);
	}
	

	


	return 0;
}
예제 #3
0
ostream &
operator<< (ostream &stream, const ACE_Time_Value &tv)
{
  if (tv.usec () < 0 || tv.sec () < 0)
    stream << "-";

  stream << my_abs (int (tv.sec ())) << "."
//       << setw (6) << setfill ('0')
         << my_abs (int (tv.usec ()));
  return stream;
}
예제 #4
0
float fast_sine(float x)
{
    const float B = 4/pi;
    const float C = -4/(pi*pi);

    float y = B * x + C * x * my_abs(x);

    //  const float Q = 0.775;
    const float P = 0.225;

    y = P * (y * my_abs(y) - y) + y;   // Q * y + P * y * abs(y)


    return y;
}
예제 #5
0
파일: 8.c 프로젝트: likalella/C-practice
int main(void)
{
		int num=0;
		printf("input num : ");
		scanf("%d", &num);
		printf("result : %d \n ", my_abs(num));		
}
예제 #6
0
const IR_Command identify_command(const int *blinks, int num_blinks)
{
  init();
  if (num_blinks < 10) return IR_Command::NO_COMMAND;
  //Serial.println("Identifying. ");
  for (unsigned int i = 0; i < commands_length; ++i)
  {
    Command *command = commands[i];
    bool matching = true;
    //Serial.println(command->name);
    for (int i = 0; i < my_min(num_blinks, command->blinks_length) - 1; i++)
    {
      /*Serial.print(blinks[i], 10);
      Serial.print("\t");
      Serial.print(command->blinks[i], 10);
      Serial.println("") ; */
       if (my_abs(blinks[i] - command->blinks[i]) > 100)
      {
        matching = false;
        //Serial.println("NO MATCH");
        break;
      }
    }
    //Serial.println("MATCH ");
    if (matching) return command->command;
  }
  return IR_Command::NO_COMMAND;
}
 int largest()
 {
     int r = 0;    // r is local (smallest non-negative int)
     for (int i = 0; i<v.size(); ++i)
         r = max(r,my_abs(v[i]));    // i is in the  for's statement scope
     // no i here
     return r;
 }
예제 #8
0
/// Solve symmetric eigenvalue problem using CLAPACK routines.
void quantfin::interfaceCLAPACK::SymmetricEigenvalueProblem(
                                   const Array<double,2>& A,      ///< Symmetric Array to be decomposed.
                                   Array<double,1>& eigval,       ///< Array (vector) containing all non-zero eigenvalues.
                                   Array<double,2>& eigvec,       ///< Array of eigenvectors (Array, each column is an eigenvector)
                                   double eps                     ///< Threshold for comparison to zero, default 1e-12
                                   )
{
  int i,j;
  long int n = A.rows();
  if (n!=A.columns()) throw(std::logic_error("Array must be square"));
  double* ap  = new double[(n*(n+1))/2];
  double* pos = ap;
  for (i=0;i<n;i++) {
    for (j=0;j<=i;j++) *pos++ = A(j,i); }
  double* w = new double[n];
  double* z = new double[n*n];
  double* work = new double[3*n];
  long int ldz  = n;
  long int info = 0;
  char jobz = 'V';
  char uplo = 'U';
  dspev_(&jobz,&uplo,&n,ap,w,z,&ldz,work,&info);
  if (!info) {
    int k = n;
    for (i=0;i<n;i++) {
      if (my_abs(w[i])<=eps) k--; }
    Array<double,1> val(k);
    Array<double,2> vec(n,k);
    int l = 0;
    pos = z;
    for (i=0;i<n;i++) {
      if (my_abs(w[i])>eps) {
        val(l) = w[i];
        for (j=0;j<n;j++) vec(j,l) = *pos++;
        l++; }
      else pos += n; }
    eigval.resize(k);
    eigvec.resize(n,k);
    eigval = val;
    eigvec = vec; }
  delete[] ap;
  delete[] w;
  delete[] z;
  delete[] work;
  if (info) throw(std::logic_error("Eigenvalue decomposition failed"));
}
예제 #9
0
파일: test.cpp 프로젝트: mhchia/practice
 bool isBalanced(TreeNode* root) {
     if (!root) return true;
     if (isBalanced(root->left) && isBalanced(root->right) &&
         my_abs(GetHeight(root->left) - GetHeight(root->right)) <= 1) {
         return true;
     }
     return false;
 }
예제 #10
0
int main(void)
{
	printf("Abstests: %d %d %d %d %d %d %d\n",
	       my_abs(-1), my_abs(1), my_abs(INT_MAX), my_abs(INT_MIN),
	       my_abs(0), my_abs(42), my_abs(-42));
	printf("singlebit0: %x %x %x %x %x\n",
	       mux_singlebit0(0),
	       mux_singlebit0(1),
	       mux_singlebit0((unsigned)-1),
	       mux_singlebit0(64),
	       mux_singlebit0(12345));
	printf("singlebit1: %x %x %x %x %x\n",
	       mux_singlebit1(0, v),
	       mux_singlebit1(1, v),
	       mux_singlebit1((unsigned)-1, v),
	       mux_singlebit1(64, v),
	       mux_singlebit1(12345, v));
	printf("singlebit2: %x %x %x %x %x\n",
	       mux_singlebit2(0, v),
	       mux_singlebit2(1, v),
	       mux_singlebit2((unsigned)-1, v),
	       mux_singlebit2(64, v),
	       mux_singlebit2(12345, v));

	return 0;
}
예제 #11
0
파일: altivec-3.c 프로젝트: 0day-ci/gcc
void
compare_float4 (float *a, float *b)
{
  int i;

  for (i = 0; i < 4; ++i)
    if (my_abs(a[i] - b[i]) >= 1.0e-6)
      abort ();
}
예제 #12
0
int	my_man(int pos, int exit, int pv, int taille)
{
  int xa;
  int xb;
  int ya;
  int yb;

  xa = pos / taille;
  xb = pos % taille;
  ya = exit / taille;
  yb = exit % taille;
  ya = ya - xa;
  xa = yb - xb;
  xa = my_abs(xa);
  ya = my_abs(ya);
  xa = xa + ya;
  return (xa);
}
예제 #13
0
int main(){
long long N,M;
scanf("%I64d  %I64d",&N,&M);
long long o_N,o_M;
long long cr_n_n=1,cr_n_m=0,cr_m_n=0,cr_m_m=1;
long long tmp;
if(N==1&&M==1){
    printf("1");
    return 0;
}
else if(N==1||M==1){
    printf("2");
    return 0;
}
o_N=N;
o_M=M;
while(N!=0&&M!=0){
    if(N>M){
        tmp=N/M;
        cr_n_n-=(cr_m_n*tmp);
        cr_n_m-=(cr_m_m*tmp);
        N%=M;
    }
    else{
        tmp=M/N;
        cr_m_n-=(cr_n_n*tmp);
        cr_m_m-=(cr_n_m*tmp);
        M%=N;
    }
}
if(N==0){
if(M!=1){
    printf("%I64d",o_N*(o_M/M));
}
else{
    if(my_abs(&cr_m_n)*o_N>my_abs(&cr_m_m)*o_M)
        printf("%I64d",my_abs(&cr_m_n)*o_N);
    else
        printf("%I64d",my_abs(&cr_m_m)*o_M);
}
}
else{
if(N!=1){
    printf("%I64d",o_N*(o_M/N));
}
else{
    if(my_abs(&cr_n_n)*o_N>my_abs(&cr_n_m)*o_M)
        printf("%I64d",my_abs(&cr_n_n)*o_N);
    else
        printf("%I64d",my_abs(&cr_n_m)*o_M);
}
}
return 0;
}
예제 #14
0
int	my_put_nbr(long nb, char *base)
{
  int	j;

  j = my_strlen(base);
  if (nb / j != 0)
    my_put_nbr(my_abs(nb / j), base);
  my_putchar(base[nb % j]);
  return (0);
}
예제 #15
0
int main()
{
	float x = 27.0, y = x, y_ = 0.0;
	do
	{
		y_ = y;
		y = 0.5 *(y + (3 * x / (2 * y * y + x / y)));
	} while (my_abs(y - y_) >= my_pow(10, -5));
	std::cout << y << std::endl;
	system("pause");
	return 0;
}
예제 #16
0
파일: sensors.c 프로젝트: Fyiyu/X4_Flyer
void sensor_read(float basic[9], unsigned int loop_count, float bmp085[2])
{
	short temp_mpu[6];
	short temp_acc[3] = {0};
	short temp_gyr[3] = {0};
	short temp_hmc[3];
	int i;
	unsigned char filter_cnt=0;
	unsigned char bmp085_state = loop_count % 10;
	mpu6050_read(temp_mpu);
	hmc5883l_read(temp_hmc);
	bmp085_read(bmp085_state,bmp085);
	
	ACC_X_BUF[filter_cnt] = temp_mpu[0];//更新滑动窗口数组
	ACC_Y_BUF[filter_cnt] = temp_mpu[1];
	ACC_Z_BUF[filter_cnt] = temp_mpu[2];	
	GYR_X_BUF[filter_cnt] = temp_mpu[3];
	GYR_Y_BUF[filter_cnt] = temp_mpu[4];
	GYR_Z_BUF[filter_cnt] = temp_mpu[5];
	if((filter_cnt++) == FILTER_NUM)	
	{
		filter_cnt=0;
		filter_full = 1;
	}

	if(filter_full == 1)
	{
		for(i=0;i<FILTER_NUM;i++)
		{
			temp_acc[0] += ACC_X_BUF[i];
			temp_acc[1] += ACC_Y_BUF[i];
			temp_acc[2] += ACC_Z_BUF[i];
			temp_gyr[0] += GYR_X_BUF[i];
			temp_gyr[1] += GYR_Y_BUF[i];
			temp_gyr[2] += GYR_Z_BUF[i];
		}
		for(i=0;i<3;i++)
		{
			temp_mpu[i] = temp_acc[i] / FILTER_NUM;
			temp_mpu[i+3] = temp_gyr[i] / FILTER_NUM;
		}
	}
	
	for(i=0;i<3;i++)
		basic[i] = (temp_mpu[i])*0.0001220703125;
	for(i=3;i<6;i++)
		basic[i] = (temp_mpu[i])*0.00762939453125 - mpu6050_OFFSET[i];
	for(i=6;i<9;i++)
		basic[i] = (temp_hmc[i-6])*1.0;
	
	if(my_abs(basic[5])<1)basic[5] = 0.0;
}
예제 #17
0
int my_putnbr_u(unsigned int nombre, int base) /* même fonction que put_nbr sauf que l'argument 1 est un unsigned number */
{
	char base16[16]={'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};



	if (nombre>=base)
	{

		my_putnbr(nombre /base,base);
	}

	my_putchar(base16[nombre%my_abs(base)]);
}
예제 #18
0
파일: page.cpp 프로젝트: ysyshtc/Reaper_SCL
int64 pollard_rho(int64 n, int64 c) {
	int64 x = rand() % (n - 1) + 1, y = x;
	for (int head = 1, tail = 2; true; ) {
		x = multiply_mod(x, x, n);
		if ((x += c) >= n)
			x -= n;
		if (x == y)
			return n;
		int64 d = gcd(my_abs(x - y), n);
		if (d > 1 && d < n)
			return d;
		if ((++head) == tail) {
			y = x;
			tail <<= 1;
		}
	}
}
예제 #19
0
int main ( int argc, char * argv[] )
{
    float interval = pi/500.0, x = -pi, y, z, r, d, sumd = 0.0;
    float max = -1.0, rmax = -1.0;
    int k;

#if 1
    for ( k=0; k<1000; ++k, x += interval )
    {
#if 1
        y = fast_sine(x);
        z = sin(x);
        d = my_abs(y-z);
        if ( d>max )
        {
            max = d;
        }
        r = d/z;
        if ( r>rmax )
        {
            rmax = r;
        }

        printf("fast_sine(%2.5f) = %2.5f\n",x,y);
        printf("sin      (%2.5f) = %2.5f\n",x,z);
        printf("abs_diff           = %2.5f\n",d);
        printf("rel_diff           = %2.5f\n\n",r);
        sumd += d;
#endif
    }
    y = sumd/1000.0;
    printf("Average difference = %f\n",y);
    printf("Max difference = %f\n",max);
    printf("Max rel diff   = %f\n",rmax);
#endif

    return 0;
}
예제 #20
0
int main()
{   
    /** Testovani souctu */ 

    // test 1 - celych cisel
    SHOULD_BE_EQUAL_FLOAT(122.0+105.0,sucet(122.0,105.0),"soucet_1");
    // test 2 - desetinnych cisel
    SHOULD_BE_EQUAL_FLOAT(36514.515+3652.525, sucet(36514.515,3652.525),"soucet_2");
    // test 3 - desetinnych cisel s vetsi presnosti
    SHOULD_BE_EQUAL_FLOAT(9.8+3.1, sucet(9.8,3.1),"soucet_3");
    // test 4 - zapornych cisel
    SHOULD_BE_EQUAL_FLOAT(-1.5811111+6.5252525, sucet(-1.5811111,6.5252525),"soucet_4");
    
    /** Testovani rozdilu  */

    // test 5 - celych cisel
    SHOULD_BE_EQUAL_FLOAT(55.0-20.0, rozdil(55.0,20.0), "rozdil_5");
    // test 6 - desetinnych cisel
    SHOULD_BE_EQUAL_FLOAT( 358.49-258.4, rozdil(358.49,258.4),"rozdil_6");
    // test 7 - desetinnych cisel s vetsi presnosti
    SHOULD_BE_EQUAL_FLOAT(256.12357-128.999999, rozdil(256.12357,128.999999),"rozdil_7");
    // test 8 - zapornych desetinnych cisel
    SHOULD_BE_EQUAL_FLOAT(-2.555555-(-3.595959), rozdil(-2.555555,-3.595959), "rozdil_8");
    
    
    /** Testovani nasobeni  */
    
    // test 9 - celych cisel
    SHOULD_BE_EQUAL_FLOAT(11.0*3.0, nasobeni(11.0,3.0),"nasobeni_9");
    // test 10 - desetinnych cisel
    SHOULD_BE_EQUAL_FLOAT(35.555*211.652, nasobeni(35.555,211.652),"nasobeni_10");
    // test 11 - nasobeni nulou
    SHOULD_BE_EQUAL_FLOAT(5.5*0.0, nasobeni(5.5,0.0),"nasobeni_11");
    // test 12 - nasobeni zapornym cislem
    SHOULD_BE_EQUAL_FLOAT(36.56*(-4.123), nasobeni(36.56,-4.123),"nasobeni_12");
    
    /** Testovani podilu */

    // test 13 - celych cisel
    SHOULD_BE_EQUAL_FLOAT( 8.0/4.0, podil(8.0,4.0),"podil_13");
    // test 14 - desetinnych cisel
    SHOULD_BE_EQUAL_FLOAT(64.5/28.244, podil(64.5,28.244),"podil_14");
    // test 15 - zapornych cisel
    SHOULD_BE_EQUAL_FLOAT(-96.2/16.5, podil(-96.2,16.5),"podil_15");
    // test 16 - podil nulou
    SHOULD_BE_EQUAL_INF(45.136/0.0,podil(45.136,0.0),"podil_16"); // using isnan() function
    
    /** Testovani mocniny */

    // test 17 - umocneni celeho cisla
    SHOULD_BE_EQUAL_FLOAT(pow(5.0,3.0), my_pow(5.0,3.0),"mocnina_17");
    // test 18 - umocneni desetinneho cisla
    SHOULD_BE_EQUAL_FLOAT(pow(25.684,6.0), my_pow(25.684,6),"mocnina_18");
    // test 19 - umocneni zapornym cislem
    SHOULD_BE_EQUAL_NAN(NAN, my_pow(11.6545,-8),"mocnina_19");
    // test 20 - umocneni nulou
    SHOULD_BE_EQUAL_FLOAT(pow(78.1111,0.0), my_pow(78.1111,0),"mocnina_20");
    
    /** Testovani druhe odmocniny  */
    
    // test 21 - odmocneni celeho cisla
    SHOULD_BE_EQUAL_FLOAT(pow(64.0,1/2.0), my_sqrt(64.0), "odmocnina_21");
    // test 22 - odmocneni desetinneho cisla
    SHOULD_BE_EQUAL_FLOAT(pow(235.154787,1/2.0), my_sqrt(235.154787),"odmocnina_22");
    // test 23 - odmocneni zaporneho cisla
    SHOULD_BE_EQUAL_NAN(pow(-81.154787,1/2.0),my_sqrt(-81.154787),"odmocnina_23");
    // test 24 - odmocneni nuly
    SHOULD_BE_EQUAL_FLOAT(pow(0,1/2.0),my_sqrt(0),"odmocnina_24");
    
    /** Testovani arcus sinu */

    // test 25 - krajnich hodnot Df
    SHOULD_BE_EQUAL_FLOAT(asin(1.0), my_asin(1.0),"arcus_sinus_25");
    // test 26 - krajnich hodnot Df
    SHOULD_BE_EQUAL_FLOAT(asin(-1.0), my_asin(-1.0),"arcus_sinus_26");
    // test 27 - hodnot z intervalu (-1;1)
    SHOULD_BE_EQUAL_FLOAT(asin(0.56), my_asin(0.56),"arcus_sinus_27");
    // test 28 - hodnot z intervalu (-1;-0.9) a (0.9;1)
    SHOULD_BE_EQUAL_FLOAT(asin(-0.96), my_asin(-0.96),"arcus_sinus_28");
    //test 29 - hodnot mimo definicni obor
    SHOULD_BE_EQUAL_NAN(NAN,my_asin(-2.56),"arcus_sinus_29");

    /** Testovani faktorialu */

    // test 30 - kladneho celeho cisla
    SHOULD_BE_EQUAL_FACT(120.0,factorial(5),"factorial_33");
    // test 31 - kladneho celeho cisla
    SHOULD_BE_EQUAL_FACT(40320.0,factorial(8),"factorial_34");
    //test 32 - zaporneho cisla
    SHOULD_BE_EQUAL_NAN(NAN,factorial(-6),"factorial_35");
    // test 33 - cisla s vysledkem nad limit hodnot promenne integer
    SHOULD_BE_EQUAL_NAN(NAN,factorial(100.0),"factorial_36");
    // test 34 - desetinneho cisla
    SHOULD_BE_EQUAL_NAN(NAN,factorial(29.99),"factorial_37");

    /** Testovani absolutni hodnoty */

    // test 37 - kladneho celeho cisla
    SHOULD_BE_EQUAL_FLOAT(fabs(11.0), my_abs(11.0),"my_abs_38");
    // test 38 - zaporneho cisla
    SHOULD_BE_EQUAL_FLOAT(fabs(-222.0), my_abs(-222.0),"my_abs_39");
    // test 39 - desetinneho cisla
    SHOULD_BE_EQUAL_FLOAT(fabs(-55.666), my_abs(-55.666),"my_abs_40");
    // test 40 - nuly
    SHOULD_BE_EQUAL_FLOAT(fabs(0), my_abs(0),"my_abs_41");
    

    printf("\nTest failed: %d\n", errors);
    printf("Test passed: %d\n",passed);
    return 0;
}
예제 #21
0
파일: orient.c 프로젝트: pikelang/Pike
void image_orient(INT32 args)
{
  struct object *o[5];
  struct image *img[5],*this,*img1;
  int n;
  rgb_group *d,*s1,*s2,*s3,*s0;
  double mag;
  int i, w, h;

  CHECK_INIT();

  this=THIS;

  if (args)
  {
    if (TYPEOF(sp[-args]) == T_INT)
      mag=sp[-args].u.integer;
    else if (TYPEOF(sp[-args]) == T_FLOAT)
      mag=sp[-args].u.float_number;
    else {
      SIMPLE_ARG_TYPE_ERROR("orient",1,"int|float");
      UNREACHABLE(mag=0.0);
    }
  }
  else mag=1.0;

  if (args==1)
    pop_n_elems(args);

  if (args>1)
  {
    if (TYPEOF(sp[1-args]) != T_ARRAY)
      SIMPLE_ARG_TYPE_ERROR("orient",2,"array");
    if (sp[1-args].u.array->size!=4)
      Pike_error("The array given as argument 2 to orient do not have size 4\n");
    for(i=0; i<4; i++)
      if ((TYPEOF(sp[1-args].u.array->item[i]) != T_OBJECT) ||
	  (!(sp[1-args].u.array->item[i].u.object)) ||
	  (sp[1-args].u.array->item[i].u.object->prog!=image_program))
	Pike_error("The array given as argument 2 to orient do not contain images\n");
    img1=(struct image*)sp[1-args].u.array->item[0].u.object->storage;

    w=this->xsize;
    h=this->ysize;

    for(i=0; i<4; i++)
    {
      img1=(struct image*)sp[1-args].u.array->item[i].u.object->storage;
      if ((img1->xsize!=w)||
	  (img1->ysize!=h))
	Pike_error("The images in the array given as argument 2 to orient have different sizes\n");
    }
    for(i=0; i<4; i++)
        img[i]=get_storage(sp[1-args].u.array->item[i].u.object,image_program);
    pop_n_elems(args);
    push_int(this->xsize);
    push_int(this->ysize);
    o[4]=clone_object(image_program,2);
    img[4]=get_storage(o[4],image_program);
    push_object(o[4]);
    w=1;
  }
  else
  {
    _image_orient(this,o,img);
    w=0;
  }
  s0=img[0]->img;
  s1=img[1]->img;
  s2=img[2]->img;
  s3=img[3]->img;
  d=img[4]->img;

THREADS_ALLOW();
CHRONO("begin hsv...");
  n=this->xsize*this->ysize;
  while (n--)
  {
     /* Första färg, sista mörkhet */
     double j=(s0->r+s0->g+s0->b-s2->r-s2->g-s2->b)/3.0;
                /* riktning - - riktning | */

     double h=(s1->r+s1->g+s1->b-s3->r-s3->g-s3->b)/3.0;
                /* riktning \ - riktning / */

     int z,w;

     if (my_abs((int)h) > my_abs((int)j))
	if (h) {
          z = -(int)(32*(j/h)+(h>0)*128+64);
          w = my_abs((int)h);
	}
	else z=0,w=0;
     else {
	if (j) {
          z = -(int)(-32*(h/j)+(j>0)*128+128);
          w = my_abs((int)j);
	}
	else z=0,w=0;
     }

     d->r=(COLORTYPE)z;
     d->g=255;
     d->b = MINIMUM((COLORTYPE)(w*mag), 255);

     d++;
     s0++;
     s1++;
     s2++;
     s3++;
  }
CHRONO("end hsv...");
THREADS_DISALLOW();

  if (!w)
  {
    add_ref(o[4]);
    pop_n_elems(5);
    push_object(o[4]);
  }
}
예제 #22
0
파일: util.c 프로젝트: kmurray/ECE1387_CAD
double my_pct_diff(double orig_val, double new_val) {
    double diff = my_abs(orig_val - new_val);

    return diff/orig_val*100;
}
int V4L2Camera::Init(int width, int height, int fps)
{
    LOGD("V4L2Camera::Init");

    /* Initialize the capture to the specified width and height */
    static const struct {
        int fmt;            /* PixelFormat */
        int bpp;            /* bytes per pixel */
        int isplanar;       /* If format is planar or not */
        int allowscrop;     /* If we support cropping with this pixel format */
    } pixFmtsOrder[] = {
        {V4L2_PIX_FMT_YUYV,     2,0,1},
        {V4L2_PIX_FMT_YVYU,     2,0,1},
        {V4L2_PIX_FMT_UYVY,     2,0,1},
        {V4L2_PIX_FMT_YYUV,     2,0,1},
        {V4L2_PIX_FMT_SPCA501,  2,0,0},
        {V4L2_PIX_FMT_SPCA505,  2,0,0},
        {V4L2_PIX_FMT_SPCA508,  2,0,0},
        {V4L2_PIX_FMT_YUV420,   0,1,0},
        {V4L2_PIX_FMT_YVU420,   0,1,0},
        {V4L2_PIX_FMT_NV12,     0,1,0},
        {V4L2_PIX_FMT_NV21,     0,1,0},
        {V4L2_PIX_FMT_NV16,     0,1,0},
        {V4L2_PIX_FMT_NV61,     0,1,0},
        {V4L2_PIX_FMT_Y41P,     0,0,0},
        {V4L2_PIX_FMT_SGBRG8,   0,0,0},
        {V4L2_PIX_FMT_SGRBG8,   0,0,0},
        {V4L2_PIX_FMT_SBGGR8,   0,0,0},
        {V4L2_PIX_FMT_SRGGB8,   0,0,0},
        {V4L2_PIX_FMT_BGR24,    3,0,1},
        {V4L2_PIX_FMT_RGB24,    3,0,1},
        {V4L2_PIX_FMT_MJPEG,    0,1,0},
        {V4L2_PIX_FMT_JPEG,     0,1,0},
        {V4L2_PIX_FMT_GREY,     1,0,1},
        {V4L2_PIX_FMT_Y16,      2,0,1},
    };

    int ret;

    // If no formats, break here
    if (m_AllFmts.isEmpty()) {
        LOGE("No video formats available");
        return -1;
    }

    // Try to get the closest match ...
    SurfaceDesc closest;
    int closestDArea = -1;
    int closestDFps = -1;
    unsigned int i;
    int area = width * height;
    for (i = 0; i < m_AllFmts.size(); i++) {
        SurfaceDesc sd = m_AllFmts[i];

        // Always choose a bigger or equal surface
        if (sd.getWidth() >= width &&
            sd.getHeight() >= height) {

            int difArea = sd.getArea() - area;
            int difFps = my_abs(sd.getFps() - fps);

            LOGD("Trying format: (%d x %d), Fps: %d [difArea:%d, difFps:%d, cDifArea:%d, cDifFps:%d]",sd.getWidth(),sd.getHeight(),sd.getFps(), difArea, difFps, closestDArea, closestDFps);
            if (closestDArea < 0 ||
                difArea < closestDArea ||
                (difArea == closestDArea && difFps < closestDFps)) {

                // Store approximation
                closestDArea = difArea;
                closestDFps = difFps;

                // And the new surface descriptor
                closest = sd;
            }
        }
    }

    if (closestDArea == -1) {
        LOGE("Size not available: (%d x %d)",width,height);
        return -1;
    }

    LOGD("Selected format: (%d x %d), Fps: %d",closest.getWidth(),closest.getHeight(),closest.getFps());

    // Check if we will have to crop the captured image
    bool crop = width != closest.getWidth() || height != closest.getHeight();

    // Iterate through pixel formats from best to worst
    ret = -1;
    for (i=0; i < (sizeof(pixFmtsOrder) / sizeof(pixFmtsOrder[0])); i++) {

        // If we will need to crop, make sure to only select formats we can crop...
        if (!crop || pixFmtsOrder[i].allowscrop) {

            memset(&videoIn->format,0,sizeof(videoIn->format));
            videoIn->format.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
            videoIn->format.fmt.pix.width = closest.getWidth();
            videoIn->format.fmt.pix.height = closest.getHeight();
            videoIn->format.fmt.pix.pixelformat = pixFmtsOrder[i].fmt;

            ret = ioctl(fd, VIDIOC_TRY_FMT, &videoIn->format);
            if (ret >= 0) {
                break;
            }
        }
    }
    if (ret < 0) {
        LOGE("Open: VIDIOC_TRY_FMT Failed: %s", strerror(errno));
        return ret;
    }

    /* Set the format */
    memset(&videoIn->format,0,sizeof(videoIn->format));
    videoIn->format.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
    videoIn->format.fmt.pix.width = closest.getWidth();
    videoIn->format.fmt.pix.height = closest.getHeight();
    videoIn->format.fmt.pix.pixelformat = pixFmtsOrder[i].fmt;
    ret = ioctl(fd, VIDIOC_S_FMT, &videoIn->format);
    if (ret < 0) {
        LOGE("Open: VIDIOC_S_FMT Failed: %s", strerror(errno));
        return ret;
    }


    /* Query for the effective video format used */
    memset(&videoIn->format,0,sizeof(videoIn->format));
    videoIn->format.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
    ret = ioctl(fd, VIDIOC_G_FMT, &videoIn->format);
    if (ret < 0) {
        LOGE("Open: VIDIOC_G_FMT Failed: %s", strerror(errno));
        return ret;
    }

    /* Note VIDIOC_S_FMT may change width and height. */

    /* Buggy driver paranoia. */
    unsigned int min = videoIn->format.fmt.pix.width * 2;
    if (videoIn->format.fmt.pix.bytesperline < min)
        videoIn->format.fmt.pix.bytesperline = min;
    min = videoIn->format.fmt.pix.bytesperline * videoIn->format.fmt.pix.height;
    if (videoIn->format.fmt.pix.sizeimage < min)
        videoIn->format.fmt.pix.sizeimage = min;

    /* Store the pixel formats we will use */
    videoIn->outWidth           = width;
    videoIn->outHeight          = height;
    videoIn->outFrameSize       = width * height << 1; // Calculate the expected output framesize in YUYV
    videoIn->capBytesPerPixel   = pixFmtsOrder[i].bpp;

    /* Now calculate cropping margins, if needed, rounding to even */
    int startX = ((closest.getWidth() - width) >> 1) & (-2);
    int startY = ((closest.getHeight() - height) >> 1) & (-2);

    /* Avoid crashing if the mode found is smaller than the requested */
    if (startX < 0) {
        videoIn->outWidth += startX;
        startX = 0;
    }
    if (startY < 0) {
        videoIn->outHeight += startY;
        startY = 0;
    }

    /* Calculate the starting offset into each captured frame */
    videoIn->capCropOffset = (startX * videoIn->capBytesPerPixel) +
            (videoIn->format.fmt.pix.bytesperline * startY);

    LOGI("Cropping from origin: %dx%d - size: %dx%d  (offset:%d)",
        startX,startY,
        videoIn->outWidth,videoIn->outHeight,
        videoIn->capCropOffset);

    /* sets video device frame rate */
    memset(&videoIn->params,0,sizeof(videoIn->params));
    videoIn->params.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
    videoIn->params.parm.capture.timeperframe.numerator = 1;
    videoIn->params.parm.capture.timeperframe.denominator = closest.getFps();

    /* Set the framerate. If it fails, it wont be fatal */
    if (ioctl(fd,VIDIOC_S_PARM,&videoIn->params) < 0) {
        LOGE("VIDIOC_S_PARM error: Unable to set %d fps", closest.getFps());
    }

    /* Gets video device defined frame rate (not real - consider it a maximum value) */
    if (ioctl(fd,VIDIOC_G_PARM,&videoIn->params) < 0) {
        LOGE("VIDIOC_G_PARM - Unable to get timeperframe");
    }

    LOGI("Actual format: (%d x %d), Fps: %d, pixfmt: '%c%c%c%c', bytesperline: %d",
        videoIn->format.fmt.pix.width,
        videoIn->format.fmt.pix.height,
        videoIn->params.parm.capture.timeperframe.denominator,
        videoIn->format.fmt.pix.pixelformat & 0xFF, (videoIn->format.fmt.pix.pixelformat >> 8) & 0xFF,
        (videoIn->format.fmt.pix.pixelformat >> 16) & 0xFF, (videoIn->format.fmt.pix.pixelformat >> 24) & 0xFF,
        videoIn->format.fmt.pix.bytesperline);

    /* Configure JPEG quality, if dealing with those formats */
    if (videoIn->format.fmt.pix.pixelformat == V4L2_PIX_FMT_JPEG ||
        videoIn->format.fmt.pix.pixelformat == V4L2_PIX_FMT_MJPEG) {

        /* Get the compression format */
        ioctl(fd,VIDIOC_G_JPEGCOMP, &videoIn->jpegcomp);

        /* Set to maximum */
        videoIn->jpegcomp.quality = 100;

        /* Try to set it */
        if(ioctl(fd,VIDIOC_S_JPEGCOMP, &videoIn->jpegcomp) >= 0)
        {
            LOGE("VIDIOC_S_COMP:");
            if(errno == EINVAL)
            {
                videoIn->jpegcomp.quality = -1; //not supported
                LOGE("   compression control not supported\n");
            }
        }

        /* gets video stream jpeg compression parameters */
        if(ioctl(fd,VIDIOC_G_JPEGCOMP, &videoIn->jpegcomp) >= 0) {
            LOGD("VIDIOC_G_COMP:\n");
            LOGD("    quality:      %i\n", videoIn->jpegcomp.quality);
            LOGD("    APPn:         %i\n", videoIn->jpegcomp.APPn);
            LOGD("    APP_len:      %i\n", videoIn->jpegcomp.APP_len);
            LOGD("    APP_data:     %s\n", videoIn->jpegcomp.APP_data);
            LOGD("    COM_len:      %i\n", videoIn->jpegcomp.COM_len);
            LOGD("    COM_data:     %s\n", videoIn->jpegcomp.COM_data);
            LOGD("    jpeg_markers: 0x%x\n", videoIn->jpegcomp.jpeg_markers);
        } else {
            LOGE("VIDIOC_G_COMP:");
            if(errno == EINVAL) {
                videoIn->jpegcomp.quality = -1; //not supported
                LOGE("   compression control not supported\n");
            }
        }
    }

    /* Check if camera can handle NB_BUFFER buffers */
    memset(&videoIn->rb,0,sizeof(videoIn->rb));
    videoIn->rb.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
    videoIn->rb.memory = V4L2_MEMORY_MMAP;
    videoIn->rb.count = NB_BUFFER;

    ret = ioctl(fd, VIDIOC_REQBUFS, &videoIn->rb);
    if (ret < 0) {
        LOGE("Init: VIDIOC_REQBUFS failed: %s", strerror(errno));
        return ret;
    }

    for (int i = 0; i < NB_BUFFER; i++) {

        memset (&videoIn->buf, 0, sizeof (struct v4l2_buffer));
        videoIn->buf.index = i;
        videoIn->buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
        videoIn->buf.memory = V4L2_MEMORY_MMAP;

        ret = ioctl (fd, VIDIOC_QUERYBUF, &videoIn->buf);
        if (ret < 0) {
            LOGE("Init: Unable to query buffer (%s)", strerror(errno));
            return ret;
        }

        videoIn->mem[i] = mmap (0,
                                videoIn->buf.length,
                                PROT_READ | PROT_WRITE,
                                MAP_SHARED,
                                fd,
                                videoIn->buf.m.offset);

        if (videoIn->mem[i] == MAP_FAILED) {
            LOGE("Init: Unable to map buffer (%s)", strerror(errno));
            return -1;
        }

        ret = ioctl(fd, VIDIOC_QBUF, &videoIn->buf);
        if (ret < 0) {
            LOGE("Init: VIDIOC_QBUF Failed");
            return -1;
        }

        nQueued++;
    }

    // Reserve temporary buffers, if they will be needed
    size_t tmpbuf_size=0;
    switch (videoIn->format.fmt.pix.pixelformat)
    {
        case V4L2_PIX_FMT_JPEG:
        case V4L2_PIX_FMT_MJPEG:
        case V4L2_PIX_FMT_UYVY:
        case V4L2_PIX_FMT_YVYU:
        case V4L2_PIX_FMT_YYUV:
        case V4L2_PIX_FMT_YUV420: // only needs 3/2 bytes per pixel but we alloc 2 bytes per pixel
        case V4L2_PIX_FMT_YVU420: // only needs 3/2 bytes per pixel but we alloc 2 bytes per pixel
        case V4L2_PIX_FMT_Y41P:   // only needs 3/2 bytes per pixel but we alloc 2 bytes per pixel
        case V4L2_PIX_FMT_NV12:
        case V4L2_PIX_FMT_NV21:
        case V4L2_PIX_FMT_NV16:
        case V4L2_PIX_FMT_NV61:
        case V4L2_PIX_FMT_SPCA501:
        case V4L2_PIX_FMT_SPCA505:
        case V4L2_PIX_FMT_SPCA508:
        case V4L2_PIX_FMT_GREY:
        case V4L2_PIX_FMT_Y16:

        case V4L2_PIX_FMT_YUYV:
            //  YUYV doesn't need a temp buffer but we will set it if/when
            //  video processing disable control is checked (bayer processing).
            //            (logitech cameras only)
            break;

        case V4L2_PIX_FMT_SGBRG8: //0
        case V4L2_PIX_FMT_SGRBG8: //1
        case V4L2_PIX_FMT_SBGGR8: //2
        case V4L2_PIX_FMT_SRGGB8: //3
            // Raw 8 bit bayer
            // when grabbing use:
            //    bayer_to_rgb24(bayer_data, RGB24_data, width, height, 0..3)
            //    rgb2yuyv(RGB24_data, pFrameBuffer, width, height)

            // alloc a temp buffer for converting to YUYV
            // rgb buffer for decoding bayer data
            tmpbuf_size = videoIn->format.fmt.pix.width * videoIn->format.fmt.pix.height * 3;
            if (videoIn->tmpBuffer)
                free(videoIn->tmpBuffer);
            videoIn->tmpBuffer = (uint8_t*)calloc(1, tmpbuf_size);
            if (!videoIn->tmpBuffer) {
                LOGE("couldn't calloc %lu bytes of memory for frame buffer\n",
                    (unsigned long) tmpbuf_size);
                return -ENOMEM;
            }


            break;

        case V4L2_PIX_FMT_RGB24: //rgb or bgr (8-8-8)
        case V4L2_PIX_FMT_BGR24:
            break;

        default:
            LOGE("Should never arrive (1)- exit fatal !!\n");
            return -1;
    }

    return 0;
}
예제 #24
0
파일: clock.c 프로젝트: LucidOne/Rovio
int
main(int argc, char *argv[])
{
    unsigned long mean=0, sum=0, maxerr=0;
    int i;

    CYG_TEST_INIT();

    CYG_TEST_INFO("Starting tests from testcase " __FILE__ " for C library "
                  "clock() function");

    // First disable the caches - they may affect the timing loops
    // below - causing the elapsed time during the clock() call to vary.
    {
        register CYG_INTERRUPT_STATE oldints;

        HAL_DISABLE_INTERRUPTS(oldints);
        HAL_DCACHE_SYNC();
        HAL_ICACHE_DISABLE();
        HAL_DCACHE_DISABLE();
        HAL_DCACHE_SYNC();
        HAL_ICACHE_INVALIDATE_ALL();
        HAL_DCACHE_INVALIDATE_ALL();
        HAL_RESTORE_INTERRUPTS(oldints);
    }

    // This waits for a clock tick, to ensure that we are at the
    // start of a clock period. Then sit in a tight loop to get
    // the clock period. Repeat this, and make sure that it the
    // two timed periods are acceptably close.

    clocks[0] = clock();
    
    if (clocks[0] == (clock_t)-1)  // unimplemented is potentially valid.
    {
#ifdef CYGSEM_LIBC_TIME_CLOCK_WORKING
        CYG_TEST_FAIL_FINISH( "clock() returns -1, meaning unimplemented");
#else
        CYG_TEST_PASS_FINISH( "clock() returns -1, meaning unimplemented");
#endif
    } // if

    // record clocks in a tight consistent loop to avoid random variations
    for (i=1; i<SAMPLES; i++) {
        ctrs[i] = clock_loop( MAX_TIMEOUT, clocks[i-1], &clocks[i] );
    }

    for (i=0;i<SAMPLES;i++) {
        // output what we got - useful for diagnostics of occasional
        // test failures
        diag_printf("clocks[%d] = %d, ctrs[%d] = %d\n", i, clocks[i],
                    i, ctrs[i]);

        // Now we work out the error etc.
        if (i>=SKIPPED_SAMPLES) {
            sum += ctrs[i];
        }
    }

    // deduce out the average
    mean = sum / (SAMPLES-SKIPPED_SAMPLES);

    // now go through valid results and compare against average
    for (i=SKIPPED_SAMPLES;i<SAMPLES;i++) {
        unsigned long err;

        err = (100 * my_abs(ctrs[i]-mean)) / mean;
        if (err > TOLERANCE) {
            diag_printf("mean=%d, ctrs[%d]=%d, err=%d\n", mean, i, ctrs[i],
                        err);
            CYG_TEST_FAIL_FINISH("clock() within tolerance");
        }
        if (err > maxerr)
            maxerr=err;
    }

    diag_printf("mean=%d, maxerr=%d\n", mean, maxerr);
    CYG_TEST_PASS_FINISH("clock() stable");

} // main()
int main()
{
    f();
    return my_abs(max(f(),g(0)) - max2(f(),g(1)));
}