Link to home
Start Free TrialLog in
Avatar of dervisakyuz
dervisakyuz

asked on

c++ to java

Hello All;

I have a working c++ source code about echo cancellation, and i have to convert it into the java code.But it is diffucult to do.I am a student and it is my final year project.It is very important for me.Please help me.
Best regards;

Dervis.

Code:



/***************** A.1 APPENDIX aec.h *****************/

/* aec.h
 *

 */

#ifndef _AEC_H                  /* include only once */

// use double if your CPU does software-emulation of float
typedef float REAL;       

/* dB Values */
const REAL M0dB = 1.0f;
const REAL M3dB = 0.71f;
const REAL M6dB = 0.50f;
const REAL M9dB = 0.35f;
const REAL M12dB = 0.25f;
const REAL M18dB = 0.125f;
const REAL M24dB = 0.063f;

/* dB values for 16bit PCM */
/* MxdB_PCM = 32767 * 10 ^(x / 20) */
const REAL M10dB_PCM = 10362.0f;
const REAL M20dB_PCM = 3277.0f;
const REAL M25dB_PCM = 1843.0f;
const REAL M30dB_PCM = 1026.0f;
const REAL M35dB_PCM = 583.0f;
const REAL M40dB_PCM = 328.0f;
const REAL M45dB_PCM = 184.0f;
const REAL M50dB_PCM = 104.0f;
const REAL M55dB_PCM = 58.0f;
const REAL M60dB_PCM = 33.0f;
const REAL M65dB_PCM = 18.0f;
const REAL M70dB_PCM = 10.0f;
const REAL M75dB_PCM = 6.0f;
const REAL M80dB_PCM = 3.0f;
const REAL M85dB_PCM = 2.0f;
const REAL M90dB_PCM = 1.0f;

const REAL MAXPCM = 32767.0f;

/* Design constants (Change to fine tune the algorithms */

/* The following values are for hardware AEC and studio quality
 * microphone */

/* maximum NLMS filter length in taps. A longer filter length gives
 * better Echo Cancellation, but slower convergence speed and
 * needs more CPU power (Order of NLMS is linear) */
#define NLMS_LEN  (80*8)

/* convergence speed. Range: >0 to <1 (0.2 to 0.7). Larger values give
 * more AEC in lower frequencies, but less AEC in higher frequencies. */
const REAL Stepsize = 0.7f;

/* minimum energy in xf. Range: M70dB_PCM to M50dB_PCM. Should be equal
 * to microphone ambient Noise level */
const REAL Min_xf = M75dB_PCM;

/* Double Talk Detector Speaker/Microphone Threshold. Range <=1
 * Large value (M0dB) is good for Single-Talk Echo cancellation,
 * small value (M12dB) is good for Doulbe-Talk AEC */
const REAL GeigelThreshold = M6dB;

/* Double Talk Detector hangover in taps. Not relevant for Single-Talk
 * AEC */
const int Thold = 30 * 8;

/* for Non Linear Processor. Range >0 to 1. Large value (M0dB) is good
 * for Double-Talk, small value (M12dB) is good for Single-Talk */
const REAL NLPAttenuation = M12dB;

/* Below this line there are no more design constants */


/* Exponential Smoothing or IIR Infinite Impulse Response Filter */
class IIR_HP {
  REAL x;

public:
   IIR_HP() { x = 0.0f; };
  REAL highpass(REAL in) {
    const REAL a0 = 0.01f;   /* controls Transfer Frequency */
    /* Highpass = Signal - Lowpass. Lowpass = Exponential Smoothing */
    x += a0 * (in - x);
    return in - x;
  };
};


/* 13 taps FIR Finite Impulse Response filter
 * Coefficients calculated with
 * www.dsptutor.freeuk.com/KaiserFilterDesign/KaiserFilterDesign.html
 */
class FIR_HP13 {
  REAL z[14];
 
public:
   FIR_HP13() { memset(this, 0, sizeof(FIR_HP13)); };
  REAL highpass(REAL in) {
    const REAL a[14] = {
      // Kaiser Window FIR Filter, Filter type: High pass
      // Passband: 300.0 - 4000.0 Hz, Order: 12
      // Transition band: 100.0 Hz, Stopband attenuation: 10.0 dB
      -0.043183226f, -0.046636667f, -0.049576525f, -0.051936015f,
      -0.053661242f, -0.054712527f, 0.82598513f, -0.054712527f,
      -0.053661242f, -0.051936015f, -0.049576525f, -0.046636667f,
      -0.043183226f, 0.0f
    };
    memmove(z+1, z, 13*sizeof(REAL));
    z[0] = in;
    REAL sum0 = 0.0, sum1 = 0.0;
    int j;

    for (j = 0; j < 14; j+= 2) {
      // optimize: partial loop unrolling
      sum0 += a[j] * z[j];
      sum1 += a[j+1] * z[j+1];
    }
    return sum0+sum1;
  }
};


/* Recursive single pole IIR Infinite Impulse response filter
 * Coefficients calculated with
 * http://www.dsptutor.freeuk.com/IIRFilterDesign/IIRFiltDes102.html
 */
class IIR1 {
  REAL x, y;

public:
   IIR1() { memset(this, 0, sizeof(IIR1)); };
  REAL highpass(REAL in) {
    // Chebyshev IIR filter, Filter type: HP
    // Passband: 3700 - 4000.0 Hz
    // Passband ripple: 1.5 dB, Order: 1
    const REAL a0 = 0.105831884f;
    const REAL a1 = -0.105831884;
    const REAL b1 = 0.78833646f;
    REAL out = a0 * in + a1 * x + b1 * y;
    x = in;
    y = out;
    return out;
  }
};

/* Recursive two pole IIR Infinite Impulse Response filter
 * Coefficients calculated with
 * http://www.dsptutor.freeuk.com/IIRFilterDesign/IIRFiltDes102.html
 */
class IIR2 {
  REAL x[2], y[2];

public:
   IIR2() { memset(this, 0, sizeof(IIR2)); };
  REAL highpass(REAL in) {
    // Butterworth IIR filter, Filter type: HP
    // Passband: 2000 - 4000.0 Hz, Order: 2
    const REAL a[] = { 0.29289323f, -0.58578646f, 0.29289323f };
    const REAL b[] = { 1.3007072E-16f, 0.17157288f };
    REAL out =
      a[0] * in +
      a[1] * x[0] +
      a[2] * x[1] -
      b[0] * y[0] -
      b[1] * y[1];

    x[1] = x[0];
    x[0] = in;
    y[1] = y[0];
    y[0] = out;
    return out;
  }
};

// Extention in taps to reduce mem copies
#define NLMS_EXT  (10*8)  

// block size in taps to optimize DTD calculation
#define DTD_LEN   16      


class AEC {
  // Time domain Filters
  IIR_HP hp00, hp1;             // DC-level remove Highpass)
  FIR_HP13 hp0;                 // 300Hz cut-off Highpass
  IIR1 Fx, Fe;                  // pre-whitening Highpass for x, e

  // Geigel DTD (Double Talk Detector)
  REAL max_max_x;               // max(|x[0]|, .. |x[L-1]|)
  int hangover;
  // optimize: less calculations for max()
  REAL max_x[NLMS_LEN / DTD_LEN];  
  int dtdCnt;
  int dtdNdx;

  // NLMS-pw
  REAL x[NLMS_LEN + NLMS_EXT];  // tap delayed loudspeaker signal
  REAL xf[NLMS_LEN + NLMS_EXT]; // pre-whitening tap delayed signal
  REAL w[NLMS_LEN];             // tap weights
  int j;                        // optimize: less memory copies
  int lastupdate;               // optimize: iterative dotp(x,x)
  double dotp_xf_xf;            // double to avoid loss of precision
  double Min_dotp_xf_xf;
  REAL s0avg;

public:
   AEC();

/* Geigel Double-Talk Detector
 *
 * in d: microphone sample (PCM as REALing point value)
 * in x: loudspeaker sample (PCM as REALing point value)
 * return: 0 for no talking, 1 for talking
 */
  int dtd(REAL d, REAL x);

/* Normalized Least Mean Square Algorithm pre-whitening (NLMS-pw)
 * The LMS algorithm was developed by Bernard Widrow
 * book: Widrow/Stearns, Adaptive Signal Processing, Prentice-Hall, 1985
 *
 * in mic: microphone sample (PCM as REALing point value)
 * in spk: loudspeaker sample (PCM as REALing point value)
 * in update: 0 for convolve only, 1 for convolve and update
 * return: echo cancelled microphone sample
 */
  REAL nlms_pw(REAL mic, REAL spk, int update);

/* Acoustic Echo Cancellation and Suppression of one sample
 * in   d:  microphone signal with echo
 * in   x:  loudspeaker signal
 * return:  echo cancelled microphone signal
 */
  int AEC::doAEC(int d, int x);

  float AEC::getambient() {
    return s0avg;
  };
  void AEC::setambient(float Min_xf) {
    dotp_xf_xf = Min_dotp_xf_xf = NLMS_LEN * Min_xf * Min_xf;
  };
};

#define _AEC_H
#endif


/***************** A.2 APPENDIX aec.cpp *****************/

/* aec.cpp
 *
 * Copyright (C) DFS Deutsche Flugsicherung (2004). All Rights Reserved.
 *
 * Acoustic Echo Cancellation NLMS-pw algorithm
 *
 * Version 1.3 filter created with www.dsptutor.freeuk.com
 */

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
#include "aec.h"


/* Vector Dot Product */
REAL dotp(REAL a[], REAL b[]) {
  REAL sum0 = 0.0, sum1 = 0.0;
  int j;
 
  for (j = 0; j < NLMS_LEN; j+= 2) {
    // optimize: partial loop unrolling
    sum0 += a[j] * b[j];
    sum1 += a[j+1] * b[j+1];
  }
  return sum0+sum1;
}


AEC::AEC()
{
  max_max_x = 0.0f;
  hangover = 0;
  memset(max_x, 0, sizeof(max_x));
  dtdCnt = dtdNdx = 0;
 
  memset(x, 0, sizeof(x));
  memset(xf, 0, sizeof(xf));
  memset(w, 0, sizeof(w));
  j = NLMS_EXT;
  lastupdate = 0;
  s0avg = M80dB_PCM;
  setambient(Min_xf);
}

REAL AEC::nlms_pw(REAL mic, REAL spk, int update)
{
  REAL d = mic;                    // desired signal
  x[j] = spk;
  xf[j] = Fx.highpass(spk);     // pre-whitening of x
 
  // calculate error value
  // (mic signal - estimated mic signal from spk signal)
  REAL e = d - dotp(w, x + j);
  REAL ef = Fe.highpass(e);    // pre-whitening of e
  // optimize: iterative dotp(xf, xf)
  dotp_xf_xf += (xf[j]*xf[j] - xf[j+NLMS_LEN-1]*xf[j+NLMS_LEN-1]);
  if (update) {
    // calculate variable step size
    REAL mikro_ef = Stepsize * ef / dotp_xf_xf;

    // update tap weights (filter learning)
    int i;
    for (i = 0; i < NLMS_LEN; i += 2) {
      // optimize: partial loop unrolling
      w[i] += mikro_ef*xf[i+j];
      w[i+1] += mikro_ef*xf[i+j+1];
    }
  }

  if (--j < 0) {
    // optimize: decrease number of memory copies
    j = NLMS_EXT;
    memmove(x+j+1, x, (NLMS_LEN-1)*sizeof(REAL));    
    memmove(xf+j+1, xf, (NLMS_LEN-1)*sizeof(REAL));    
  }

  return e;
}


int AEC::dtd(REAL d, REAL x)
{
  // optimized implementation of max(|x[0]|, |x[1]|, .., |x[L-1]|):
  // calculate max of block (DTD_LEN values)
  x = fabsf(x);
  if (x > max_x[dtdNdx]) {
    max_x[dtdNdx] = x;
    if (x > max_max_x) {
      max_max_x = x;
    }
  }
  if (++dtdCnt >= DTD_LEN) {
    dtdCnt = 0;
    // calculate max of max
    max_max_x = 0.0f;
    for (int i = 0; i < NLMS_LEN/DTD_LEN; ++i) {
      if (max_x[i] > max_max_x) {
        max_max_x = max_x[i];
      }
    }
    // rotate Ndx
    if (++dtdNdx >= NLMS_LEN/DTD_LEN) dtdNdx = 0;
    max_x[dtdNdx] = 0.0f;
  }

  // The Geigel DTD algorithm with Hangover timer Thold
  if (fabsf(d) >= GeigelThreshold * max_max_x) {
    hangover = Thold;
  }
   
  if (hangover) --hangover;
 
  return (hangover > 0);
}


int AEC::doAEC(int d, int x)
{
  REAL s0 = (REAL)d;
  REAL s1 = (REAL)x;
 
  // Mic Highpass Filter - to remove DC
  s0 = hp00.highpass(s0);
 
  // Mic Highpass Filter - telephone users are used to 300Hz cut-off
  s0 = hp0.highpass(s0);

  // ambient mic level estimation
  s0avg += 1e-4f*(fabsf(s0) - s0avg);
 
  // Spk Highpass Filter - to remove DC
  s1 = hp1.highpass(s1);

  // Double Talk Detector
  int update = !dtd(s0, s1);

  // Acoustic Echo Cancellation
  s0 = nlms_pw(s0, s1, update);

  // Acoustic Echo Suppression
  if (update) {
    // Non Linear Processor (NLP): attenuate low volumes
    s0 *= NLPAttenuation;
  }
 
  // Saturation
  if (s0 > MAXPCM) {
    return (int)MAXPCM;
  } else if (s0 < -MAXPCM) {
    return (int)-MAXPCM;
  } else {
    return (int)roundf(s0);
  }
}


/***************** A.3 APPENDIX aec_test.cpp *****************/

/* aec_test.cpp
 *
 * Copyright (C) DFS Deutsche Flugsicherung (2004). All Rights Reserved.
 *
 * Test stub for Acoustic Echo Cancellation NLMS-pw algorithm
 * Author: Andre Adrian, DFS Deutsche Flugsicherung
 * <Andre.Adrian@dfs.de>
 *
 * compile
c++ -O2 -o aec_test aec_test.cpp aec.cpp -lm
 *
 * Version 1.3 set/get ambient in dB
 */

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>

#include "aec.h"

#define TAPS        (80*8)

typedef signed short MONO;

typedef struct {
  signed short l;
  signed short r;
} STEREO;

float dB2q(float dB)
{
  /* Dezibel to Ratio */
  return powf(10.0f, dB / 20.0f);
}

float q2dB(float q)
{
  /* Ratio to Dezibel */
  return 20.0f * log10f(q);
}

/* Read a raw audio file (8KHz sample frequency, 16bit PCM, stereo)
 * from stdin, echo cancel it and write it to stdout
 */
int main(int argc, char *argv[])
{
  STEREO inbuf[TAPS], outbuf[TAPS];

  fprintf(stderr, "usage: aec_test [ambient in dB] <in.raw >out.raw\n");

  AEC aec;

  if (argc >= 2) {
    aec.setambient(MAXPCM*dB2q(atof(argv[1])));    
  }

  int taps;
  while (taps = fread(inbuf, sizeof(STEREO), TAPS, stdin)) {
    int i;
    for (i = 0; i < taps; ++i) {
      int s0 = inbuf[i].l;      /* left channel microphone */
      int s1 = inbuf[i].r;      /* right channel speaker */

      /* and do NLMS */
      s0 = aec.doAEC(s0, s1);

      /* copy back */
      outbuf[i].l = 0;          /* left channel silence */
      outbuf[i].r = s0;         /* right channel echo cancelled mic */
    }

    fwrite(outbuf, sizeof(STEREO), taps, stdout);
  }

  float ambient = aec.getambient();
  float ambientdB = q2dB(ambient / 32767.0f);
  fprintf(stderr, "Ambient = %2.0f dB\n", ambientdB);
  fflush(NULL);
  return 0;
}
Avatar of Manikandan Thiagarajan
Manikandan Thiagarajan
Flag of India image

first you have to study


how to create class , method ,variable in java


this link could be helpful to you
Avatar of dervisakyuz
dervisakyuz

ASKER

where is the link? and for example how can i write  "sizeof()(class name)" in java

if u convert this i will do others by looking oyur code.

best regards

dervis.

class IIR1 {
  REAL x, y;

public:
   IIR1() { memset(this, 0, sizeof(IIR1)); };
  REAL highpass(REAL in) {
    // Chebyshev IIR filter, Filter type: HP
    // Passband: 3700 - 4000.0 Hz
    // Passband ripple: 1.5 dB, Order: 1
    const REAL a0 = 0.105831884f;
    const REAL a1 = -0.105831884;
    const REAL b1 = 0.78833646f;
    REAL out = a0 * in + a1 * x + b1 * y;
    x = in;
    y = out;
    return out;
  }
};
Hi dervisakyuz,

I suggest you tu use the last Java version (1.5.0) because you'll have less conversion work to do as this version support template classes, and other C++ like features.

see http://java.sun.com/j2se/1.5.0/docs/guide/
1) In Java, all are classes, so you need something like :


public class MyApp // -> MyApp.java : same name as class name
{
    ...
    // C++: int main(int argc, char *argv[])
    // ->
    public static void main(String[] args) // args=argv (except argv[0]),  args.length = number of arguments
    {
        ...
    }
}
2)
const REAL M0dB = 1.0f;
const REAL M3dB = 0.71f;
const REAL M6dB = 0.50f;
const REAL M9dB = 0.35f;
const REAL M12dB = 0.25f;
const REAL M18dB = 0.125f;
const REAL M24dB = 0.063f;

->
public class MyApp // -> MyApp.java : same name as class name
{
    ...
    public static final float
        M0dB = 1.0f,
        M3dB = 0.71f,
        M6dB = 0.50f,
        M9dB = 0.35f,
        M12dB = 0.25f,
        M18dB = 0.125f,
        M24dB = 0.063f,
         ...   ;

}
ASKER CERTIFIED SOLUTION
Avatar of Webstorm
Webstorm

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
>> };
should be:
}

Avatar of Mayank S
You don't have sizeof in Java. So you cannot get the exact size of the object (maybe that Java 5 has some API support for that, but not sure). The best you can do is obtain its serialized size using ByteArrayOutputStream.
>> where is the link? and

To start with: http://java.sun.com/docs/books/tutorial/
public IIR1() { /* memset useless */ };

so i cant convert this code into java isnt it? because there are lots of memset(...sizeof(...)); some examples

memset(x, 0, sizeof(x));
  memset(xf, 0, sizeof(xf));
  memset(w, 0, sizeof(w));

i think there must be sth but i cant find.and i have to convert this code.

best regards

dervis
In java, you don't need to initialize to 0 : already done.

for example:
   int[] ints=new int[8];
all 8 integer values are initialized to 0.
But for reusing array next time, you can do :

    java.util.Arrays.fill(ints,0);
java.util.Arrays.fill is only for array of int,char,double,  but not for objects
because In Java you cannot directly access system memory.

In the class constructor, memset is useless because all object members are initialized to 0 by default :

Each time "new" is used, it allocate an object/array filled with 0.
(0 for int/short/byte/long, 0.0 for double/float, false for boolean, \0 for char, null for object types ).
hi again;

how can i combine .h files and cpp files into java pls help
i mean that if any h file is given how can i code in java ? do i have to create a class or sth else?
you combine .h and .cpp files in one .java file :
    - function prototype : skip (prototypes are not needed)
    - constants (#define) : in the class -> static final <type> <constname> = <value> ;
    - ...
memmove is another problem? how can i do   memmove(z+1, z, 13*sizeof(REAL));



hello again  what is "::" how can i use in java

thanks.

int AEC::doAEC(int d, int x);

  float AEC::getambient() {
    return s0avg;
You cannot define a method outside a class in Java, it has to be defined inside the class.
>> memmove is another problem? how can i do   memmove(z+1, z, 13*sizeof(REAL));

REAL -> double

You have to use a double array
    double[] z=new double[ ...array_size_here... ];
then
    System.arraycopy(z,0,z,1,13); // moving 13 elements from z[0] to z[1]

>> what is "::" how can i use in java

In C++ :           <class>::<static_member>


In Java :

   public class <class>
   {
           static <type> <static_member>;
or:
           static <type> <static_member>(...){}
   }

    <class>.<static_member>=
or:
    <class>.<static_member>(...)
these are perfect answers .thank you.

another problem is mine is getambient()

setambient(), what must i do ?

i am sorry but i confuse  does  the <static_member> is a static method or our writen method;

and does getambient  is a static method?

i cant do this, could  you write in java pls?
int AEC::doAEC(int d, int x);

  float AEC::getambient() {
    return s0avg;
  };
  void AEC::setambient(float Min_xf) {
    dotp_xf_xf = Min_dotp_xf_xf = NLMS_LEN * Min_xf * Min_xf;
  };
};


:: in my previous comment was for accessing static members of class
:: is also used in C++ to define methods in .cpp file, outside of class block

In Java, all must be declared within the class block, so <class>:: is useless :

>> int AEC::doAEC(int d, int x);
prototype, just don't translate this line


  float AEC::getambient() {
    return s0avg;
  };
  void AEC::setambient(float Min_xf) {
    dotp_xf_xf = Min_dotp_xf_xf = NLMS_LEN * Min_xf * Min_xf;
  };
->

  float getambient(){
    return s0avg;
  }
  void setambient(float Min_xf) {
    dotp_xf_xf = Min_dotp_xf_xf = NLMS_LEN * Min_xf * Min_xf;
  }
hi expert;

Now i am going to read wav files and apply this files to my code  and as an output write another wav file.how can i do it?

thanks.
i mean that; first of all, i want to read wav file as an input.reading wav file from my computer??.
That should be asked in another question because it is entirely different.
ok