diff --git a/Code_v1.0.6/CMakeLists.txt b/Code_v1.0.6/CMakeLists.txt new file mode 100644 index 0000000..65e89db --- /dev/null +++ b/Code_v1.0.6/CMakeLists.txt @@ -0,0 +1,16 @@ +cmake_minimum_required( VERSION 3.10 ) +set(CMAKE_BUILD_TYPE Release) +project (ssl CXX) + +find_package(PkgConfig) +pkg_check_modules(ALSA alsa REQUIRED) + + +add_executable (Localisation_exe Localisation.cpp) +target_link_libraries (Localisation_exe ${ALSA_LIBRARIES}) +target_compile_options(Localisation_exe PUBLIC ${ALSA_CFLAGS_OTHER}) +target_include_directories(Localisation_exe PUBLIC ${ALSA_INCLUDE_DIRS}) + +install(PROGRAMS ${CMAKE_CURRENT_BINARY_DIR}/Localisation_exe + DESTINATION bin + RENAME ${CMAKE_PROJECT_NAME}-Localisation_exe) diff --git a/Code_v1.0.6/Localisation_v1.0.6.cpp b/Code_v1.0.6/Localisation_v1.0.6.cpp new file mode 100644 index 0000000..970455d --- /dev/null +++ b/Code_v1.0.6/Localisation_v1.0.6.cpp @@ -0,0 +1,243 @@ +#include +using namespace std; + +#include +#include +#include +#include +#include +#include "/usr/include/alsa/asoundlib.h" + +//#define SAMPLE_TYPE float +//#define SAMPLE_TYPE_ALSA SND_PCM_FORMAT_FLOAT_LE + +#define SAMPLE_TYPE short //sample type = type d'echantillon +#define SAMPLE_TYPE_ALSA SND_PCM_FORMAT_S16_LE + +/** + * classe permettant de calculer la moyenne glissante du signal + */ +class MoyenneGlissante { + int _nbDeValeursPrMoy; + int _nbDeValeurs; + float _mean; + +public: + MoyenneGlissante(int nbDeValeursPrMoy) { + _nbDeValeursPrMoy = nbDeValeursPrMoy; + _mean = 0; + _nbDeValeurs = 0; + } + + void nvelleValeur(SAMPLE_TYPE v) { + if (_nbDeValeurs < _nbDeValeursPrMoy) + _nbDeValeurs++; + _mean = ((_mean * (_nbDeValeurs - 1)) + v) / (float)_nbDeValeurs; + } + + SAMPLE_TYPE getMean() { + return (SAMPLE_TYPE) _mean; + } +}; + +/** + * Cette classe calcule la direction du son entendu + * + * + * Elle utilise 2 microphones et calcule la différence de temps d'arrivée des sons entre eux pour + * estimer la localisation de la source sonore. + */ +class Localisation { + + /** + * Décalage maximum entre le micro droit et gauche en nombre d'échantillons. + * Cela dépend généralement de la fréquence d'échantillonnage et de la distance entre + * microphones + */ + static const int _nbEchantillonsDiffMax = 13; //difference max du nombre d'echantillons + + /** + * Taille du tampon sur laquelle nous allons essayer de localiser le son. + * Ceci est un certain nombre d'échantillons, et dépend de la fréquence d'échantillonnage et de la vitesse de + * changement de loc son que nous voulons détecter. Des valeurs plus faibles signifient le calcul du son + * se fait plus souvent, mais la précision est assez faible car nous calculons sur une très petite tranche de + * du son. + */ + static const int _TailleTampon = 4096; + + /** + * Prenez un point pour la localisation du son est Niveau> 105% du Niveau moyen. Cela permet de calculer la + * localisation du son uniquement pour les sons "significatifs", pas le bruit de fond. + */ + static constexpr float _NiveauSonMin = 1.1f; //f de 1.05f signifie :float constant with value of 1.05 + + /** + * sound speed in meters per seconds + */ + static constexpr float _Vson = 344; + + /** + * sound sampling rate in Hz + */ + unsigned int _TauxEchantillonnageSon; + + /** + * Distance between microphones in meters + */ + static constexpr float _DistanceMic = 0.05f;//5 cm de distance entre les deux microphones + + /** An utility to compute the running average of sound power */ + MoyenneGlissante* _MoyNivSonore; + + /** ALSA sound input handle */ + snd_pcm_t* _capture_handle; + + /** sound samples input buffer */ + SAMPLE_TYPE _TamponDroit[_TailleTampon]; + SAMPLE_TYPE _TamponGauche[_TailleTampon]; + +public: + Localisation() { + _MoyNivSonore = new MoyenneGlissante(50); + _TauxEchantillonnageSon = 44100; + + // sampling: 2 chanels, 44 KHz, 16 bits. + int err; + snd_pcm_hw_params_t* hw_params; + + // ideally use "hw:0,0" for embedded, to limit processing. But check if card support our needs... + const char* CarteSon = "plughw:0,0"; + if ((err = snd_pcm_open(&_capture_handle, CarteSon, SND_PCM_STREAM_CAPTURE, 0)) < 0) { + fprintf(stderr, "Impossible d'ouvrir le peripherique audio %s (%s)\n", CarteSon,snd_strerror(err)); + exit(1); + } + + if ((err = snd_pcm_hw_params_malloc(&hw_params)) < 0) { + fprintf(stderr, "Impossible d'allouer la structure des paramètres matériels (%s)\n",snd_strerror(err)); + exit(1); + } + + if ((err = snd_pcm_hw_params_any(_capture_handle, hw_params)) < 0) { + fprintf(stderr,"Impossible d'initialiser la structure des paramètres matériels (%s)\n",snd_strerror(err)); + exit(1); + } + + if ((err = snd_pcm_hw_params_set_access(_capture_handle, hw_params,SND_PCM_ACCESS_RW_NONINTERLEAVED)) < 0) { + fprintf(stderr, "Impossible de definir le type d'acces (%s)\n", snd_strerror(err)); + exit(1); + } + + if ((err = snd_pcm_hw_params_set_format(_capture_handle, hw_params,SAMPLE_TYPE_ALSA)) < 0) { + fprintf(stderr, "Impossible de definir le format d'echantillonnage (%s)\n",snd_strerror(err)); + exit(1); + } + + if ((err = snd_pcm_hw_params_set_rate_near(_capture_handle, hw_params,&_TauxEchantillonnageSon, 0)) < 0) { + fprintf(stderr, "Impossible de definir le taux d'echantillonnage (%s)\n", snd_strerror(err)); + exit(1); + } + + if ((err = snd_pcm_hw_params_set_channels(_capture_handle, hw_params, 2))< 0) { + fprintf(stderr, "Impossible de definir le nombre de canaux (%s)\n", snd_strerror(err)); + exit(1); + } + + if ((err = snd_pcm_hw_params(_capture_handle, hw_params)) < 0) { + fprintf(stderr, "Impossible de definir les parametres (%s)\n", snd_strerror(err)); + exit(1); + } + + snd_pcm_hw_params_free(hw_params); + + if ((err = snd_pcm_prepare(_capture_handle)) < 0) { + fprintf(stderr, "Impossible de preparer l'interface audio pour utilisation (%s)\n",snd_strerror(err)); + exit(1); + } + } + + /** Clean exit */ + ~Localisation() { + snd_pcm_close(_capture_handle); + delete _MoyNivSonore; + } + + /** + * Boucle principale: lit un tampon, calcule la localisation de la source sonore, fait une itération. + */ + void run() { + while (true) { + TraitementSonsSuivants(); + } + } + +private: + /** + * C'est le cœur de la localisation de la source sonore: il prend les sons échantillonnés + * Droit / Gauche, et calcule leurs différences tout en retardant de plus en plus un canal.
+ * => le retard pour lequel la différence est minime est le vrai retard + * entre les sons Droit / Gauche, dont on peut déduire la source sonore + * localisation + */ + void TraitementSonsSuivants() { + SAMPLE_TYPE* bufs[2]; + bufs[0] = _TamponDroit; + bufs[1] = _TamponGauche; + int err; + if ((err = snd_pcm_readn(_capture_handle, (void**) bufs, _TailleTampon))!= _TailleTampon) { + fprintf(stderr, "Echec de la lecture de l'interface audio (%s)\n",snd_strerror(err)); + exit(1); + } + + // compute the sound level (i.e. "loudness" of the sound): + SAMPLE_TYPE Niveau = CalculNiv(_TamponDroit, _TamponGauche); + // update the average sound level with this new measure: + _MoyNivSonore->nvelleValeur(Niveau); + // relative sound level of this sample compared to average: + float NivRelatif = (float) Niveau / (float) _MoyNivSonore->getMean(); + //cout << "level " << level << ", relative " << NivRelatif << endl; + + int minDiff = INT_MAX; + int minDiffTime = -1; + // glisse sur l'axe du temps pour trouver la différence sonore minimum entre les microphones Droit et Gauche + for (int t = -_nbEchantillonsDiffMax; t < _nbEchantillonsDiffMax; t++) { + // calcule la somme des différences pour simuler une mesure de corrélation croisée: + int diff = 0; + for (int i = _nbEchantillonsDiffMax; i < _TailleTampon - _nbEchantillonsDiffMax - 1; i++) { + diff += abs(_TamponGauche[i] - _TamponDroit[i + t]); + } + if (diff < minDiff) { + minDiff = diff; + minDiffTime = t; + } + } + + // Si le son est assez fort et pas extrême (= ce qui entraine généralement de fausses + // mesures), alors on le dessine: + if ((NivRelatif > _NiveauSonMin) && (minDiffTime > -_nbEchantillonsDiffMax) && (minDiffTime < _nbEchantillonsDiffMax)) { + // computation of angle depending on diff time, sampling rates, + // and geometry + float angle = -(float) asin((minDiffTime * _Vson) / (_TauxEchantillonnageSon* _DistanceMic)); + cout << angle << ";" << NivRelatif << endl; + } + } + + /** + * Calcule du niveau sonore moyen (la puissance) pour les canaux gauche et droit. + */ + SAMPLE_TYPE CalculNiv(SAMPLE_TYPE Droit[], SAMPLE_TYPE Gauche[]) { + float Niveau = 0; + for (int i = 0; i < _TailleTampon; i++) { + float s = (Gauche[i] + Droit[i]) / 2; + Niveau += (s * s); + } + Niveau /= _TailleTampon; + Niveau = sqrt(Niveau); + return (SAMPLE_TYPE) Niveau; + } +}; + +int main(int argc, char *argv[]) { + Localisation soundLoc; + soundLoc.run(); + exit(0); +} diff --git a/Code_v1.0.6/SoundSourceDraw.java b/Code_v1.0.6/SoundSourceDraw.java new file mode 100644 index 0000000..ec64557 --- /dev/null +++ b/Code_v1.0.6/SoundSourceDraw.java @@ -0,0 +1,104 @@ +//package soundsourceloc; + +import java.awt.BasicStroke; +import java.awt.BorderLayout; +import java.awt.Dimension; +import java.awt.Graphics; +import java.awt.Graphics2D; +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; + +import javax.swing.JFrame; +import javax.swing.JPanel; + +/** + * This class draws the direction of the source of the sound it hears. + * + * It gets its from a C++ program (see companion project 'sound-source-loc') + * + * @author Frederic Pesquet (fpesquet at gmail dot com) + */ +public class SoundSourceDraw extends JFrame { + private static final long serialVersionUID = 1L; + + /** the panel that draw the last sound localization as an arc */ + private final SoundLocDraw _soundLocDraw; + + public SoundSourceDraw() throws Exception { + super("Sound Source Localization"); + + _soundLocDraw = new SoundLocDraw(); + getContentPane().add(_soundLocDraw, BorderLayout.CENTER); + } + + /** + * Main loop: launch C++ listener, get its output, draw, and loop + * @throws IOException + */ + public void run() throws IOException { + ProcessBuilder pb = new ProcessBuilder("/home/quentin/Documents/Projet_localisation/Documentation/Code/code_v1.0.5/sound-source-loc"); + pb = pb.redirectErrorStream(true); + Process p = pb.start(); + InputStream is = p.getInputStream(); + InputStreamReader isr = new InputStreamReader(is); + BufferedReader br = new BufferedReader(isr); + String line; + while (( line = br.readLine()) != null) { + int sep=line.indexOf(';'); + float angle=Float.parseFloat(line.substring(0,sep)); + float relativePower=Float.parseFloat(line.substring(sep+1)); + //System.out.println("received sound loc: "+line); + _soundLocDraw.setSound(angle,relativePower); + } + } + + /** + * A simple panel that draws the sound source localization angle, with a + * thickness depending on the sound level. + */ + @SuppressWarnings("serial") + static private class SoundLocDraw extends JPanel { + // sound angle, between -PI/2...+PI/2 + private float _angle; + + // relative power with respect to mean power (1.0=mean power) + private float _relativePower; + + public void setSound(float angle, float relativePower) { + _angle = angle; + _relativePower = relativePower; + repaint(); + } + + @Override + protected void paintComponent(Graphics g) { + super.paintComponent(g); + Graphics2D g2d = (Graphics2D) g; + Dimension d = getSize(); + int radius = Math.min(d.height, d.width / 2); + int cx = d.width / 2; + int cy = 0; + int tx = cx + (int) (Math.cos(_angle + Math.PI / 2) * radius); + int ty = cy + (int) (Math.sin(_angle + Math.PI / 2) * radius); + g2d.drawOval(cx - radius, cy - radius, radius * 2, radius * 2); + // use larger strokes for louder sounds: + g2d.setStroke(new BasicStroke(1 + (int) ((Math.max(_relativePower, + 1) - 1.0) * 10))); + g2d.drawLine(cx, cy, tx, ty); + } + } + + /** + * Entry point: create the frame, and start listening to sound until closed. + */ + public static void main(String[] args) throws Exception { + SoundSourceDraw snd = new SoundSourceDraw(); + snd.setSize(800, 400); + snd.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + snd.setLocationRelativeTo(null); + snd.setVisible(true); + snd.run(); + } +}