public override void OnRequestPermissionsResult(int requestCode, string[] permissions, Android.Content.PM.Permission[] grantResults) { if (requestCode == FINGERPRINT_PERMISSION_REQUEST_CODE && grantResults[0] == Android.Content.PM.Permission.Granted) { if (!mKeyguardManager.IsKeyguardSecure) { IsFingerPrintReady = false; // Show a message that the user hasn't set up a fingerprint or lock screen. Toast.MakeText(this, "Secure lock screen hasn't set up.\n" + "Go to 'Settings -> Security -> Fingerprint' to set up a fingerprint", ToastLength.Long).Show(); return; } mFingerprintManager = (FingerprintManager)GetSystemService(Context.FingerprintService); if (!mFingerprintManager.HasEnrolledFingerprints) { IsFingerPrintReady = false; // This happens when no fingerprints are registered. Toast.MakeText(this, "Go to 'Settings -> Security -> Fingerprint' " + "and register at least one fingerprint", ToastLength.Long).Show(); return; } CreateKey(); IsFingerPrintReady = true; } }
static void Process(Files.File file) { var audio = new Files.AudioFile { ID = file.ID, ContentType = file.ContentType, Name = file.Name, Size = file.Size, Url = file.Url, FullPath = file.FullPath }; audio.AlterPath = file.FullPath.ToLower().Replace("mp3", "wav"); var proxy = new BassProxy(); if (!File.Exists(audio.AlterPath)) proxy.RecodeTheFile(file.FullPath, audio.AlterPath, 5512); FingerprintManager manager = new FingerprintManager(); manager.FingerprintLength = Length; manager.TopWavelets = 150; manager.MaxFrequency = 2048; manager.MinFrequency = 512; //float[][] spec = manager.CreateSpectrogram(proxy, audio.AlterPath, 0, 0); var StaticStride = new StaticStride(0); audio.Finger = manager.CreateFingerprints(proxy, audio.AlterPath, StaticStride).ToArray(); FileProvider.Save(audio); }
public async Task GenerateFingerprintTest() { var apiKey = Environment.GetEnvironmentVariable("baelor-test-apikey"); var fingerprints = await FingerprintManager.GenerateFingerprint(apiKey); Assert.True(fingerprints.Count() == FingerprintManager.FingerprintCount); }
/// <summary> /// Each repository should have storage for permutations and for tracks/fingerprints /// </summary> /// <param name = "storage">Track/Signatures storage</param> /// <param name = "permutations">Permutations storage</param> public Repository(IStorage storage, IPermutations permutations) { _permutations = permutations; _storage = storage; _manager = new FingerprintManager(); _hasher = new MinHash(_permutations); }
public MarshmallowBiometricsImpl() { this.scanner = (FingerprintManager)Application.Context.GetSystemService(Context.FingerprintService); if (Build.VERSION.SdkInt < BuildVersionCodes.M) { this.available = false; } else if (!this.scanner.IsHardwareDetected) { this.available = false; } else if (Application.Context.CheckCallingOrSelfPermission(Manifest.Permission.UseFingerprint) != Permission.Granted) { this.available = false; } else if (!this.scanner.HasEnrolledFingerprints) { this.available = false; } else { this.available = true; } }
public override void OnRequestPermissionsResult(int requestCode, string[] permissions, Android.Content.PM.Permission[] grantResults) { if (requestCode == FINGERPRINT_PERMISSION_REQUEST_CODE && grantResults[0] == Android.Content.PM.Permission.Granted) { SetContentView(Resource.Layout.activity_main); var purchaseButton = FindViewById <Button> (Resource.Id.purchase_button); if (!mKeyguardManager.IsKeyguardSecure) { purchaseButton.Enabled = false; // Show a message that the user hasn't set up a fingerprint or lock screen. Toast.MakeText(this, "Secure lock screen hasn't set up.\n" + "Go to 'Settings -> Security -> Fingerprint' to set up a fingerprint", ToastLength.Long).Show(); return; } mFingerprintManager = (FingerprintManager)GetSystemService(Context.FingerprintService); if (!mFingerprintManager.HasEnrolledFingerprints) { purchaseButton.Enabled = false; // This happens when no fingerprints are registered. Toast.MakeText(this, "Go to 'Settings -> Security -> Fingerprint' " + "and register at least one fingerprint", ToastLength.Long).Show(); return; } CreateKey(); purchaseButton.Enabled = true; purchaseButton.Click += (sender, e) => { // Show the fingerprint dialog. The user has the option to use the fingerprint with // crypto, or you can fall back to using a server-side verified password. FindViewById(Resource.Id.confirmation_message).Visibility = ViewStates.Gone; FindViewById(Resource.Id.encrypted_message).Visibility = ViewStates.Gone; mFragment = new FingerprintAuthenticationDialogFragment(); mSharedPreferences = this.GetPreferences(FileCreationMode.Private); if (InitCipher()) { mFragment.SetCryptoObject(new FingerprintManager.CryptoObject(mCipher)); var useFingerprintPreference = mSharedPreferences.GetBoolean(GetString(Resource.String.use_fingerprint_to_authenticate_key), true); if (useFingerprintPreference) { mFragment.SetStage(FingerprintAuthenticationDialogFragment.Stage.Fingerprint); } else { mFragment.SetStage(FingerprintAuthenticationDialogFragment.Stage.Password); } mFragment.Show(FragmentManager, DIALOG_FRAGMENT_TAG); } else { mFragment.SetCryptoObject(new FingerprintManager.CryptoObject(mCipher)); mFragment.SetStage(FingerprintAuthenticationDialogFragment.Stage.NewFingerprintEnrolled); mFragment.Show(FragmentManager, DIALOG_FRAGMENT_TAG); } }; } }
protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); Xamarin.Essentials.Platform.Init(this, savedInstanceState); SetContentView(Resource.Layout.activity_main); fingerprintManager = CreateFingerprintManager(); InitiateViews(); }
/// <summary> /// Constructor for {@link FingerprintUiHelper}. This method is expected to be called from /// only the {@link FingerprintUiHelperBuilder} class. /// </summary> /// <param name="fingerprintManager">Fingerprint manager.</param> /// <param name="icon">Icon.</param> /// <param name="errorTextView">Error text view.</param> /// <param name="callback">Callback.</param> FingerprintUiHelper (FingerprintManager fingerprintManager, ImageView icon, TextView errorTextView, Callback callback) { mFingerprintManager = fingerprintManager; mIcon = icon; mErrorTextView = errorTextView; mCallback = callback; }
/// <summary> /// Constructor for {@link FingerprintUiHelper}. This method is expected to be called from /// only the {@link FingerprintUiHelperBuilder} class. /// </summary> /// <param name="fingerprintManager">Fingerprint manager.</param> /// <param name="icon">Icon.</param> /// <param name="errorTextView">Error text view.</param> /// <param name="callback">Callback.</param> FingerprintUiHelper(FingerprintManager fingerprintManager, ImageView icon, TextView errorTextView, Callback callback) { mFingerprintManager = fingerprintManager; mIcon = icon; mErrorTextView = errorTextView; mCallback = callback; }
public FingerprintCrypt(FingerprintModule fingerprint, string keyId) { _keyId = keyId; _cipher = fingerprint.Cipher; _keystore = fingerprint.Keystore; _fingerprintManager = fingerprint.FingerprintManager; }
public static bool SupportsFingerScan() { FingerprintManager manager = Application.Context.GetSystemService(Context.FingerprintService) as FingerprintManager; var isHardware = manager.IsHardwareDetected; var hasEnrolledPrints = manager.HasEnrolledFingerprints; var hasLockScreen = HasLockScreen(); return(isHardware && hasEnrolledPrints && hasLockScreen); }
internal void StartAuthentication(FingerprintManager fingerprintManager, FingerprintManager.CryptoObject cryptoObject) { CancellationSignal cancellationSignal = new CancellationSignal(); if (ActivityCompat.CheckSelfPermission(mainActivity, Manifest.Permission.UseFingerprint) != (int)Android.Content.PM.Permission.Granted) { return; } fingerprintManager.Authenticate(cryptoObject, cancellationSignal, 0, this, null); }
public void StartListening (FingerprintManager.CryptoObject cryptoObject) { if (!IsFingerprintAuthAvailable) return; mCancellationSignal = new CancellationSignal (); mSelfCancelled = false; mFingerprintManager.Authenticate (cryptoObject, mCancellationSignal, 0 /* flags */, this, null); mIcon.SetImageResource (Resource.Drawable.ic_fp_40px); }
public FingerprintCrypt(FingerprintModule fingerprint, string keyId) { Kp2aLog.Log("FP: Create " + this.GetType().Name); _keyId = keyId; _cipher = fingerprint.Cipher; _keystore = fingerprint.Keystore; _fingerprintManager = fingerprint.FingerprintManager; }
internal void _startAutentificare(FingerprintManager amp, FingerprintManager.CryptoObject criptat) { CancellationSignal _semnal = new CancellationSignal(); if (Android.Support.V4.Content.ContextCompat.CheckSelfPermission(_amprenta, Manifest.Permission.UseFingerprint) != (int)Android.Content.PM.Permission.Granted) { return; } amp.Authenticate(criptat, _semnal, 0, this, null); }
public static bool IsFingerprintSet() { FingerprintManager myFM = (FingerprintManager)Application.Context.GetSystemService(Context.FingerprintService); if (myFM.IsHardwareDetected == false) { return(false); } return(myFM.HasEnrolledFingerprints); }
public async Task TestIvGeneration() { var apiKey = Environment.GetEnvironmentVariable("baelor-test-apikey"); var fingerprints = await FingerprintManager.GenerateFingerprint(apiKey); var cryptoManagaer = new CryptographyManager(new FingerprintManager(fingerprints)); var ivA = cryptoManagaer.GenerateNewIv(); var ivB = cryptoManagaer.GenerateNewIv(); Assert.False(ivA == ivB); Assert.True(ivA.Length * 8 == CryptographyManager.BlockBitSize); Assert.True(ivB.Length * 8 == CryptographyManager.BlockBitSize); }
protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); // Set our view from the "main" layout resource SetContentView(Resource.Layout.Main); Button logInButton = FindViewById <Button>(Resource.Id.logInButton); logInButton.Click += (s, e) => { Intent intent = new Intent(this, typeof(HomeActivity)); this.StartActivity(intent); }; KeyguardManager keyguardManager = (KeyguardManager)GetSystemService(KeyguardService); FingerprintManager fingerprintManager = (FingerprintManager)GetSystemService(FingerprintService); if (ActivityCompat.CheckSelfPermission(this, Manifest.Permission.UseFingerprint) != (int)Android.Content.PM.Permission.Granted) { return; } if (!fingerprintManager.IsHardwareDetected) { Toast.MakeText(this, "FingerPrint authentication permission not enable", ToastLength.Short).Show(); } else { if (!fingerprintManager.HasEnrolledFingerprints) { Toast.MakeText(this, "Register at least one fingerprint in Settings", ToastLength.Short).Show(); } else { if (!keyguardManager.IsKeyguardSecure) { Toast.MakeText(this, "Lock screen security not enable in Settings", ToastLength.Short).Show(); } else { GenKey(); } if (CipherInit()) { FingerprintManager.CryptoObject cryptoObject = new FingerprintManager.CryptoObject(cipher); FingerprintHandler handler = new FingerprintHandler(this); handler.StartAuthentication(fingerprintManager, cryptoObject); } } } }
protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); SetContentView(Resource.Layout.biometric_activity); if (this.Intent.Extras != null) { transactionObject = JsonConvert.DeserializeObject <TransactionObject>(Intent.GetStringExtra("transactionObject")); user = JsonConvert.DeserializeObject <User>(Intent.GetStringExtra("users")); } KeyguardManager keyguardManager = (KeyguardManager)GetSystemService(KeyguardService); FingerprintManager fingerprintManager = (FingerprintManager)GetSystemService(FingerprintService); if (ActivityCompat.CheckSelfPermission(this, Manifest.Permission.UseFingerprint) != (int)Android.Content.PM.Permission.Granted) { return; } if (!fingerprintManager.IsHardwareDetected) { Toast.MakeText(this, "FingerPrint authentication permission not enable", ToastLength.Short).Show(); } else { if (!fingerprintManager.HasEnrolledFingerprints) { Toast.MakeText(this, "Register at least one fingerprint in Settings", ToastLength.Short).Show(); } else { if (!keyguardManager.IsKeyguardSecure) { Toast.MakeText(this, "Lock screen security not enable in Settings", ToastLength.Short).Show(); } else { GenKey(); } if (CipherInit()) { FingerprintManager.CryptoObject cryptoObject = new FingerprintManager.CryptoObject(cipher); FingerprintHandler handler = new FingerprintHandler(this, transactionObject, user); handler.StartAuthentication(fingerprintManager, cryptoObject); } } } }
private void _autentificareAmprenta(object ob, EventArgs ev) { KeyguardManager _manager = (KeyguardManager)GetSystemService(KeyguardService); FingerprintManager _amprente = (FingerprintManager)GetSystemService(FingerprintService); if (Android.Support.V4.Content.ContextCompat.CheckSelfPermission(this, _permisiune) != (int)Android.Content.PM.Permission.Granted) { return; } if (!_amprente.IsHardwareDetected) { Toast.MakeText(this, "The use of fingertip authentication is disabled", ToastLength.Short).Show(); } else { if (!_amprente.HasEnrolledFingerprints) { Toast.MakeText(this, "No fingertips registered in our app", ToastLength.Short).Show(); } else { if (!_manager.IsKeyguardSecure) { Toast.MakeText(this, "Please enable lock screen security!", ToastLength.Short).Show(); } else { _algoritmCriptare(); } if (_genereazaCifru()) { FingerprintManager.CryptoObject _criptat = new FingerprintManager.CryptoObject(_cifru); CreatorAmprenta _creator = new CreatorAmprenta(this); _creator._startAutentificare(_amprente, _criptat); gotoCriptare.Visibility = ViewStates.Visible; gotoGPS.Visibility = ViewStates.Visible; gotoContinut.Visibility = ViewStates.Visible; ftipTV.Text = "Now you can use any of the options below"; gotoCriptare.Click += _accesCriptarePosibil; gotoGPS.Click += _accesGPSPosibil; gotoContinut.Click += _accesContinutPosibil; } } } }
private void Authenticate() { FingerprintManager fingerprint = this.GetSystemService(FingerprintService) as FingerprintManager; KeyguardManager keyGuard = GetSystemService(KeyguardService) as KeyguardManager; Android.Content.PM.Permission permission = CheckSelfPermission(Android.Manifest.Permission.UseFingerprint); if (fingerprint.IsHardwareDetected && keyGuard.IsKeyguardSecure && fingerprint.HasEnrolledFingerprints && permission == Android.Content.PM.Permission.Granted) { const int flags = 0; CryptoObjectFactory cryptoObject = new CryptoObjectFactory(); CancellationSignal cancellationSignal = new CancellationSignal(); FingerprintManager.AuthenticationCallback authCallback = new AuthCallback(this); fingerprint.Authenticate(cryptoObject.BuildCryptoObject(), cancellationSignal, flags, authCallback, null); } }
protected override void OnCreate(Bundle bundle) { base.OnCreate(bundle); SetContentView(Resource.Layout.Main); KeyguardManager keyguardManager = (KeyguardManager)GetSystemService(KeyguardService); FingerprintManager fingerprintManager = (FingerprintManager)GetSystemService(FingerprintService); if (ActivityCompat.CheckSelfPermission(this, Manifest.Permission.UseFingerprint) != (int)Android.Content.PM.Permission.Granted) { return; } if (!fingerprintManager.IsHardwareDetected) { Toast.MakeText(this, "Fingerprint authentication permission not enalbe", ToastLength.Long).Show(); } else { if (!fingerprintManager.HasEnrolledFingerprints) { Toast.MakeText(this, "Register at least one fingerprint in Settings", ToastLength.Long).Show(); } else { if (!keyguardManager.IsKeyguardSecure) { Toast.MakeText(this, "Lock screen security not enable in Settings", ToastLength.Long).Show(); } else { GenKey(); } if (CipherInit()) { FingerprintManager.CryptoObject cryptoObject = new FingerprintManager.CryptoObject(cipher); FingerprintHandler helper = new FingerprintHandler(this); helper.StartAuthentication(fingerprintManager, cryptoObject); } } } }
public void Main(string[] args) { var fingerprintManager = new FingerprintManager("fingerprints.json"); var cryptoManager = new CryptographyManager(fingerprintManager); var key = cryptoManager.GenerateNewKey(); var iv = cryptoManager.GenerateNewIv(); System.Console.Write("Enter Text to be encrypted: "); var input = System.Console.ReadLine(); var encryptedFingerprintData = cryptoManager.Encrypt(Encoding.ASCII.GetBytes(input), key, iv); var output = ""; foreach (var fingerprint in encryptedFingerprintData) { output += fingerprint.Lyric + "\n"; } output = output.TrimEnd('\n'); var decryptedOutput = cryptoManager.Decrypt(output, key, iv); System.Console.WriteLine(); System.Console.WriteLine("=== ENCRYPTED DATA ==="); System.Console.WriteLine(output); System.Console.WriteLine("======================"); System.Console.WriteLine(); System.Console.WriteLine("=== DECRYPTED DATA ==="); System.Console.WriteLine(Encoding.ASCII.GetString(decryptedOutput)); System.Console.WriteLine("====================="); System.Console.WriteLine(); System.Console.WriteLine("=== METADATA ==="); System.Console.WriteLine("Crypto Key: {0}", BitConverter.ToString(key, 0, key.Length).Replace("-", "")); System.Console.WriteLine("Crypto Iv: {0}", BitConverter.ToString(iv, 0, iv.Length).Replace("-", "")); System.Console.WriteLine("================"); System.Console.ReadLine(); }
public void Authenticate() { KeyguardManager keyguardManager = (KeyguardManager)Forms.Context.GetSystemService("keyguard"); FingerprintManager fingerprintManager = (FingerprintManager)Forms.Context.GetSystemService("fingerprint"); if (ActivityCompat.CheckSelfPermission(Forms.Context, Manifest.Permission.UseFingerprint) != (int)Android.Content.PM.Permission.Granted) { return; } if (!fingerprintManager.IsHardwareDetected) { Toast.MakeText(Forms.Context, "FingerPrint authentication permission not enable", ToastLength.Short).Show(); } else { if (!fingerprintManager.HasEnrolledFingerprints) { Toast.MakeText(Forms.Context, "Register at least one fingerprint in Settings", ToastLength.Short).Show(); } else { if (!keyguardManager.IsKeyguardSecure) { Toast.MakeText(Forms.Context, "Lock screen security not enable in Settings", ToastLength.Short).Show(); } else { GenKey(); } if (CipherInit()) { FingerprintManager.CryptoObject cryptoObject = new FingerprintManager.CryptoObject(cipher); StartAuthentication(fingerprintManager, cryptoObject); } } } }
public async Task TestEncryptionAndDecryption(string data) { var apiKey = Environment.GetEnvironmentVariable("baelor-test-apikey"); var fingerprints = await FingerprintManager.GenerateFingerprint(apiKey); var cryptoManagaer = new CryptographyManager(new FingerprintManager(fingerprints)); var key = cryptoManagaer.GenerateNewKey(); var iv = cryptoManagaer.GenerateNewIv(); var encryptedDataFingerprints = cryptoManagaer.Encrypt(Encoding.ASCII.GetBytes(data), key, iv); var formattedEncryptedFingerprints = ""; foreach (var fingerprint in encryptedDataFingerprints) { formattedEncryptedFingerprints += fingerprint.Lyric + "\n"; } formattedEncryptedFingerprints = formattedEncryptedFingerprints.TrimEnd('\n'); var decryptedData = cryptoManagaer.Decrypt(formattedEncryptedFingerprints, key, iv); var decryptedPlainText = Encoding.ASCII.GetString(decryptedData); Assert.True(data == decryptedPlainText); }
protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); Xamarin.Essentials.Platform.Init(this, savedInstanceState); SetContentView(Resource.Layout.activity_main); KeyguardManager keyguardManager = (KeyguardManager)GetSystemService(KeyguardService); FingerprintManager fingerprintManager = (FingerprintManager)GetSystemService(FingerprintService); if (ActivityCompat.CheckSelfPermission(this, Manifest.Permission.UseFingerprint) != (int)Android.Content.PM.Permission.Granted) { return; } if (!fingerprintManager.IsHardwareDetected) { Toast.MakeText(this, GetString(Resource.String.fingerPrintPermissionDisabled), ToastLength.Short).Show(); return; } if (!fingerprintManager.HasEnrolledFingerprints) { Toast.MakeText(this, GetString(Resource.String.fingerPrintNotRegister), ToastLength.Short).Show(); return; } if (!keyguardManager.IsKeyguardSecure) { Toast.MakeText(this, GetString(Resource.String.lockscreenDisabled), ToastLength.Short).Show(); return; } GetKey(); if (CipherInit()) { FingerprintManager.CryptoObject cryptoObject = new FingerprintManager.CryptoObject(cipher); FingerPrintHandler helper = new FingerPrintHandler(this); helper.StartAuthentication(fingerprintManager, cryptoObject); } }
public void Main(string[] args) { var fingerprintManager = new FingerprintManager("fingerprints.json"); var cryptoManager = new CryptographyManager(fingerprintManager); var key = cryptoManager.GenerateNewKey(); var iv = cryptoManager.GenerateNewIv(); System.Console.Write("Enter Text to be encrypted: "); var input = System.Console.ReadLine(); var encryptedFingerprintData = cryptoManager.Encrypt(Encoding.ASCII.GetBytes(input), key, iv); var output = ""; foreach (var fingerprint in encryptedFingerprintData) output += fingerprint.Lyric + "\n"; output = output.TrimEnd('\n'); var decryptedOutput = cryptoManager.Decrypt(output, key, iv); System.Console.WriteLine(); System.Console.WriteLine("=== ENCRYPTED DATA ==="); System.Console.WriteLine(output); System.Console.WriteLine("======================"); System.Console.WriteLine(); System.Console.WriteLine("=== DECRYPTED DATA ==="); System.Console.WriteLine(Encoding.ASCII.GetString(decryptedOutput)); System.Console.WriteLine("====================="); System.Console.WriteLine(); System.Console.WriteLine("=== METADATA ==="); System.Console.WriteLine("Crypto Key: {0}", BitConverter.ToString(key, 0, key.Length).Replace("-", "")); System.Console.WriteLine("Crypto Iv: {0}", BitConverter.ToString(iv, 0, iv.Length).Replace("-", "")); System.Console.WriteLine("================"); System.Console.ReadLine(); }
protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); SetContentView(Resource.Layout.FingerPrintAuth); String nombreArchivo = "app-bco_security.sqlite"; String rutaCarpeta = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal); String ruta = System.IO.Path.Combine(rutaCarpeta, nombreArchivo); var key = new Contenido() { Password = KEY_NAME }; DatabaseHelper.Insertar(ref key, ruta); KeyguardManager keyguardManager = (KeyguardManager)GetSystemService(KeyguardService); FingerprintManager fingerprintManager = (FingerprintManager)GetSystemService(FingerprintService); if (ActivityCompat.CheckSelfPermission(this, Manifest.Permission.UseFingerprint) != (int)Android.Content.PM.Permission.Granted) { return; } if (!fingerprintManager.IsHardwareDetected) { Toast.MakeText(ApplicationContext, "Lector de huella no habilitado en tu dispositivo", ToastLength.Long).Show(); } else { if (!fingerprintManager.HasEnrolledFingerprints) { Toast.MakeText(ApplicationContext, "Debes enrolar tu huella del dispositivo", ToastLength.Long).Show(); } else { if (!keyguardManager.IsKeyguardSecure) { Toast.MakeText(ApplicationContext, "No tienes habilitada la configuracion del scaner dactilar", ToastLength.Long).Show(); } else { GenKey(); } if (CipherInit()) { FingerprintManager.CryptoObject cryptoObject = new FingerprintManager.CryptoObject(cipher); FingerprintHandler helper = new FingerprintHandler(this); helper.StartAuthentication(fingerprintManager, cryptoObject); } } } lblTituloAsociaHuella = FindViewById <TextView>(Resource.Id.lblTituloAsociaHuella); lblTextoIndicacionAsociacion1 = FindViewById <TextView>(Resource.Id.lblTextoIndicacionAsociacion1); lblTextoIndicacionAsociacion2 = FindViewById <TextView>(Resource.Id.lblTextoIndicacionAsociacion2); lblTextoIndicacionAsociacion3 = FindViewById <TextView>(Resource.Id.lblTextoIndicacionAsociacion3); lblTextoIndicacionAsociacion4 = FindViewById <TextView>(Resource.Id.lblTextoIndicacionAsociacion4); lblTextoIndicacionAsociacion5 = FindViewById <TextView>(Resource.Id.lblTextoIndicacionAsociacion5); btnOmitirEnrolado = FindViewById <ImageView>(Resource.Id.btnOmitirEnrolado); btnOmitirEnrolado.Click += BtnOmitirEnrolado_Click; var fontRegular = Typeface.CreateFromAsset(Assets, rutaFuenteTitiliumRegular); var fontSemiBold = Typeface.CreateFromAsset(Assets, rutaFuenteTitiliumSemiBold); lblTituloAsociaHuella.Typeface = fontSemiBold; lblTextoIndicacionAsociacion1.Typeface = fontRegular; lblTextoIndicacionAsociacion2.Typeface = fontSemiBold; lblTextoIndicacionAsociacion3.Typeface = fontRegular; lblTextoIndicacionAsociacion4.Typeface = fontRegular; lblTextoIndicacionAsociacion5.Typeface = fontRegular; }
public MarshmallowBiometricsImpl() { this.scanner = (FingerprintManager)Application.Context.GetSystemService(Context.FingerprintService); }
static void Process(string path) { Console.WriteLine(path); var proxy = new BassProxy(); proxy.RecodeTheFile(path + ".mp3", path + ".wav", 5512); var data = File.CreateText(path + ".txt"); FingerprintManager manager = new FingerprintManager(); manager.FingerprintLength = Length; manager.TopWavelets = 150; manager.MaxFrequency = 2048; manager.MinFrequency = 512; float[][] spec = manager.CreateSpectrogram(proxy, path + ".wav", 0, 0); var StaticStride = ( path == "7" ) ? new StaticStride(Milliseconds) : new StaticStride(0); var fingerprint = manager.CreateFingerprints(proxy, path + ".wav", StaticStride); if (path == "4") { sfinger = fingerprint; } foreach (var finger in fingerprint) { int[] bits = finger.Select(f => f ? 1 : 0).ToArray(); data.WriteLine(string.Join(";", bits)); } data.Close(); if(File.Exists( path + ".jpg") ) File.Delete(path + ".jpg"); if (spec.Length > 0) { Bitmap image = Imaging.GetSpectrogramImage(spec, 800, 600); image.Save(path + ".jpg", ImageFormat.Jpeg); } if (path == "7") { var hasMin = new MinHash(new LocalPermutations("2.txt", ";")); var result = File.CreateText("r.txt"); Dictionary<int, int> count = new Dictionary<int, int>(); foreach (var finger in sfinger) { //var t = fingerprint.Select(p => MinHash.CalculateSimilarity(finger, p)).OrderByDescending(p => p).ToArray(); //var t = fingerprint.Select(p => MinHash.CalculateHammingDistance (finger, p)).OrderByDescending(p => p).ToArray(); //var t = sfinger.Select(p => MinHash.CalculateSimilarity(finger, p)).OrderByDescending(p => p).ToArray(); for (int i = 0; i < fingerprint.Count; i++) { var similarity = MinHash.CalculateSimilarity(finger, fingerprint[i]); if (similarity > 0.5f) { if (!count.ContainsKey(i)) count.Add(i, 0); count[i]++; result.Write("{1}:{0};", similarity.ToString("#.000"), i, i * 11.6f * Block, (i + 1) * 11.6f * Block); } } result.WriteLine(); } foreach (var c in count.OrderByDescending(p => p.Value)) result.Write("{0}:{1};", c.Key, c.Value); result.WriteLine("-------------------"); foreach (var c in count.OrderBy(p => p.Key)) result.WriteLine("{0}:{1} Time: {2} ms;", c.Key, c.Value, c.Key * 11.6f * Block); result.Close(); } }
/// <summary> /// Dump information into file /// </summary> private void BtnDumpInfoClick(object sender, EventArgs e) { if (String.IsNullOrEmpty(_tbPathToFile.Text)) { MessageBox.Show(Resources.ErrorNoFileToAnalyze, Resources.SelectFile, MessageBoxButtons.OK, MessageBoxIcon.Information); return; } if (String.IsNullOrEmpty(_tbOutputPath.Text)) { MessageBox.Show(Resources.SelectPathToDump, Resources.SelectFile, MessageBoxButtons.OK, MessageBoxIcon.Information); return; } if (!File.Exists(Path.GetFullPath(_tbPathToFile.Text))) { MessageBox.Show(Resources.NoSuchFile, Resources.NoSuchFile, MessageBoxButtons.OK, MessageBoxIcon.Information); return; } if (_chbCompare.Checked) { if (String.IsNullOrEmpty(_tbSongToCompare.Text)) { MessageBox.Show(Resources.ErrorNoFileToAnalyze, Resources.SelectFile, MessageBoxButtons.OK, MessageBoxIcon.Information); return; } } Action action = () => { using (BassProxy proxy = new BassProxy()) { FadeControls(false); int minFreq = (int) _nudFreq.Value; int topWavelets = (int) _nudTopWavelets.Value; int stride = (int) _nudStride.Value; IStride objStride = (_chbStride.Checked) ? (IStride) new RandomStride(0, stride) : new StaticStride(stride); FingerprintManager manager = new FingerprintManager {MinFrequency = minFreq, TopWavelets = topWavelets}; DumpResults resultObj = new DumpResults(); string pathToInput = _tbPathToFile.Text; string pathToOutput = _tbOutputPath.Text; int hashTables = (int) _nudTables.Value; int hashKeys = (int) _nudKeys.Value; stride = (int) _nudQueryStride.Value; int numFingerprints = (int) _nudNumberOfSubsequent.Value; IStride queryStride = (_chbQueryStride.Checked) ? (IStride) new RandomStride(0, stride) : new StaticStride(stride); queryStride = new StaticStride(5115, 5115/2); GetFingerprintSimilarity(manager, objStride, queryStride, numFingerprints, proxy, pathToInput, resultObj); GetHashSimilarity(manager, objStride, queryStride, numFingerprints, hashTables, hashKeys, proxy, pathToInput, resultObj); if (_chbCompare.Checked) { string pathToDifferent = _tbSongToCompare.Text; GetFingerprintSimilarity(manager, objStride, proxy, pathToInput, pathToDifferent, resultObj); } resultObj.Info.MinFrequency = minFreq; resultObj.Info.TopWavelets = topWavelets; resultObj.Info.StrideSize = stride; resultObj.Info.RandomStride = _chbStride.Checked; resultObj.Info.Filename = pathToInput; resultObj.ComparisonDone = _chbCompare.Checked; XmlSerializer serializer = new XmlSerializer(typeof (DumpResults)); TextWriter writer = new StreamWriter(pathToOutput); serializer.Serialize(writer, resultObj); writer.Close(); } }; action.BeginInvoke( (result) => { action.EndInvoke(result); FadeControls(true); }, null); }
/// <summary> /// Get fingerprint similarity between 2 different songs. /// </summary> /// <param name = "manager">Fingerprint manager used in file decomposition</param> /// <param name = "stride">Stride object parameter</param> /// <param name = "proxy">Proxy to the audio object</param> /// <param name = "path">Path to first file</param> /// <param name = "differentPath">Path to different file</param> /// <param name = "results">Results object to be filled with the corresponding data</param> private static void GetFingerprintSimilarity(FingerprintManager manager, IStride stride, IAudio proxy, string path, string differentPath, DumpResults results) { int startindex = 0; int count = 0; double sum = 0; List<bool[]> imglista = manager.CreateFingerprints(proxy, path, stride); List<bool[]> imglistb = manager.CreateFingerprints(proxy, differentPath, stride); count = imglista.Count > imglistb.Count ? imglistb.Count : imglista.Count; double max = double.MinValue; for (int i = 0; i < count; i++) { int j = i; double value = MinHash.CalculateSimilarity(imglista[i], imglistb[j]); if (value > max) max = value; sum += value; } results.SumJaqFingerprintSimilarityBetweenDiffertSongs = sum; results.AverageJaqFingerprintsSimilarityBetweenDifferentSongs = sum/count; results.MaxJaqFingerprintsSimilarityBetweenDifferentSongs = max; }
public static void Main(string[] args) { /* int nFFT = 1024; int samplerate = 44100; int length = samplerate * 10; // 10 sec double freq1, freq2; int i1, i2; for (int i = 0; i < nFFT + 1; i++) { freq1 = MathUtils.Index2Freq(i, samplerate, nFFT); freq2 = MathUtils.IndexToFreq(i, samplerate, nFFT); i1 = MathUtils.Freq2Index(freq1, samplerate, nFFT); i2 = MathUtils.FreqToIndex((float)freq2, samplerate, nFFT); } */ // http://www.music.mcgill.ca/~gary/307/week5/additive.html //SaveColorPaletteBar("c:\\rew-colorbar-generated.png", "c:\\rew-colorbar-generated.csv", ColorPaletteType.REWColorPalette); /* List<Color> rew_hsb_gradients = ColorUtils.GetHSBColorGradients(256, ColorUtils.ColorPaletteType.REW); ColorUtils.SaveColorGradients("c:\\rew-hsb-gradients.png", rew_hsb_gradients, 40); List<Color> rew_hsl_gradients = ColorUtils.GetHSLColorGradients(256, ColorUtils.ColorPaletteType.REW); ColorUtils.SaveColorGradients("c:\\rew-hsl-gradients.png", rew_hsl_gradients, 40); List<Color> sox_hsb_gradients = ColorUtils.GetHSBColorGradients(256, ColorUtils.ColorPaletteType.SOX); ColorUtils.SaveColorGradients("c:\\sox-hsb-gradients.png", sox_hsb_gradients, 40); List<Color> sox_hsl_gradients = ColorUtils.GetHSLColorGradients(256, ColorUtils.ColorPaletteType.SOX); ColorUtils.SaveColorGradients("c:\\sox-hsl-gradients.png", sox_hsl_gradients, 40); List<Color> photosounder_hsb_gradients = ColorUtils.GetHSBColorGradients(256, ColorUtils.ColorPaletteType.PHOTOSOUNDER); ColorUtils.SaveColorGradients("c:\\photosounder_hsb_gradients.png", photosounder_hsb_gradients, 40); List<Color> photosounder_hsl_gradients = ColorUtils.GetHSLColorGradients(256, ColorUtils.ColorPaletteType.PHOTOSOUNDER); ColorUtils.SaveColorGradients("c:\\photosounder_hsl_gradients.png", photosounder_hsl_gradients, 40); List<Color> photosounder_rgb_gradients = ColorUtils.GetRGBColorGradients(255, ColorUtils.ColorPaletteType.PHOTOSOUNDER); ColorUtils.SaveColorGradients("c:\\photosounder_rgb_gradients.png", photosounder_rgb_gradients, 40); List<Color> grey_hsb_gradients = ColorUtils.GetHSBColorGradients(256, ColorUtils.ColorPaletteType.BLACK_AND_WHITE); ColorUtils.SaveColorGradients("c:\\grey-hsb-gradients.png", grey_hsb_gradients, 40); */ /* ReadColorPaletteBar(@"C:\Users\perivar.nerseth\SkyDrive\Temp\sox_colorbar.png", "c:\\sox_colorbar.csv"); ReadColorPaletteBar(@"C:\Users\perivar.nerseth\SkyDrive\Temp\soundforge_colorbar.png", "c:\\soundforge_colorbar.csv"); ReadColorPaletteBar(@"C:\Users\perivar.nerseth\SkyDrive\Temp\rew_colorbar.png", "c:\\rew_colorbar.csv"); ReadColorPaletteBar(@"C:\Users\perivar.nerseth\SkyDrive\Temp\sox_colorbar.png", "c:\\sox_colorbar.csv"); ReadColorPaletteBar(@"C:\Users\perivar.nerseth\SkyDrive\Temp\thermal_colorbar.png", "c:\\thermal_colorbar.csv"); ReadColorPaletteBar(@"C:\rew-gradients.png", "c:\\rew-gradients.csv"); */ //String fileName = @"C:\Users\perivar.nerseth\Music\Sleep Away.mp3"; //String fileName = @"C:\Users\perivar.nerseth\Music\Sleep Away32f.wav"; String fileName = @"C:\Users\perivar.nerseth\Music\Sleep Away16.wav"; //String fileName = @"C:\Users\perivar.nerseth\Music\Maid with the Flaxen Hair.mp3"; //String fileName = @"G:\Cubase and Nuendo Projects\Music To Copy Learn\Britney Spears - Hold It Against Me\02 Hold It Against Me (Instrumental) 1.mp3"; Console.WriteLine("Analyzer starting ..."); RepositoryGateway repositoryGateway = new RepositoryGateway(); FingerprintManager manager = new FingerprintManager(); // VB6 FFT double sampleRate = 44100;// 44100, default 5512 int fftWindowsSize = 16384; //32768 16384 8192 4096 2048, default 256*8 (2048) to 256*128 (32768), reccomended: 256*64 = 16384 int secondsToSample = 25; //25, 15; int fftOverlap = (int) (sampleRate * secondsToSample / 1280); // 32768:990, 16384:990, 8192:990, 4096:990 //float fftOverlapPercentage = 94.0f; // 99.0f number between 0 and 100 //float[] wavDataVB6 = repositoryGateway._proxy.ReadMonoFromFile(fileName, (int) sampleRate, secondsToSample*1000, 20*1000 ); //float[] wavDataVB6 = repositoryGateway._proxy.ReadMonoFromFile(fileName, (int) sampleRate, secondsToSample*1000, 0); //MathUtils.NormalizeInPlace(wavDataVB6); //Export.exportCSV(@"c:\bass.csv", wavDataVB6); float[] wavDataNaudio = AudioUtilsNAudio.ReadMonoFromFile(fileName, (int) sampleRate, secondsToSample*1000, 0); //float[] wavDataNaudio = AudioUtilsNAudio.ReadMonoFromFile(fileName, (int) sampleRate, 0, 0); /* float[] wavDataNaudio = new float[(int) (sampleRate*secondsToSample)]; BasicOscillatorProvider basic = new BasicOscillatorProvider(); int length = (int)(sampleRate*3); int offset = 0; basic.Amplitude = MathUtils.DecibelToAmplitude(-80); basic.SetFrequency(220); basic.SetOscWaveshape(BasicOscillatorProvider.WAVESHAPE.SINE); offset += basic.Read(wavDataNaudio, offset, length); basic.Amplitude = MathUtils.DecibelToAmplitude(-60); basic.SetFrequency(440); basic.SetOscWaveshape(BasicOscillatorProvider.WAVESHAPE.SQUARE); offset += basic.Read(wavDataNaudio, offset, length); basic.Amplitude = MathUtils.DecibelToAmplitude(-40); basic.SetFrequency(880); basic.SetOscWaveshape(BasicOscillatorProvider.WAVESHAPE.TRIANGLE); offset += basic.Read(wavDataNaudio, offset, length); basic.Amplitude = MathUtils.DecibelToAmplitude(-20); basic.SetFrequency(1760); basic.SetOscWaveshape(BasicOscillatorProvider.WAVESHAPE.SAW); offset += basic.Read(wavDataNaudio, offset, length); basic.Amplitude = MathUtils.DecibelToAmplitude(-10); basic.SetFrequency(3520); basic.SetOscWaveshape(BasicOscillatorProvider.WAVESHAPE.SINE); offset += basic.Read(wavDataNaudio, offset, length); basic.Amplitude = MathUtils.DecibelToAmplitude(0); basic.SetFrequency(1760); basic.SetOscWaveshape(BasicOscillatorProvider.WAVESHAPE.SAW); offset += basic.Read(wavDataNaudio, offset, length); AudioUtilsNAudio.WriteIEEE32WaveFileMono(@"c:\sines.wav", 44100, wavDataNaudio); */ //MathUtils.NormalizeInPlace(wavDataNaudio); //Export.exportCSV(@"c:\naudio.csv", wavDataNaudio); //VB6Spectrogram vb6Spect = new VB6Spectrogram(); //vb6Spect.ComputeColorPalette(); //float[][] vb6Spectrogram = vb6Spect.Compute(wavDataVB6, sampleRate, fftWindowsSize, fftOverlapPercentage); //Export.exportCSV (@"c:\VB6Spectrogram-full.csv", vb6Spectrogram); // Exocortex.DSP FFT /* int numberOfSamples = wavDataNaudio.Length; fftOverlapPercentage = fftOverlapPercentage / 100; long ColSampleWidth = (long)(fftWindowsSize * (1 - fftOverlapPercentage)); double fftOverlapSamples = fftWindowsSize * fftOverlapPercentage; long NumCols = numberOfSamples / ColSampleWidth; int fftOverlap = (int)((numberOfSamples - fftWindowsSize) / NumCols); int numberOfSegments = (numberOfSamples - fftWindowsSize)/fftOverlap; */ //System.Console.Out.WriteLine(String.Format("EXO: fftWindowsSize: {0}, Overlap samples: {1:n2}.", fftWindowsSize, fftOverlap )); //VIPSLib.Audio.WAVFile wavefile = new VIPSLib.Audio.WAVFile(); //wavefile.ReadFromFileToDouble(fileName.Substring(0, fileName.LastIndexOf(".")) + ".wav"); //RiffRead riff = new RiffRead(fileName.Substring(0, fileName.LastIndexOf(".")) + ".wav"); //riff.Process(); /* VIPSLib.Audio.MFCC mfcclib = new VIPSLib.Audio.MFCC((float)sampleRate); double[][] data = riff.SoundData; double min; double max; MathUtils.ComputeMinAndMax(data, out min, out max); double[][] mfcc = mfcclib.Process(MathUtils.FloatToDouble(wavDataVB6)); float fmin; float fmax; MathUtils.ComputeMinAndMax(wavDataVB6, out fmin, out fmax); */ //double[][] mfcc = mfcclib.Process(riff.SoundData[0]); //float[][] mfccFloats = MathUtils.DoubleToFloat(mfcc); // GENERATE SPECTROGRAM //Bitmap spectro = AudioAnalyzer.GetSpectrogramImage(wavDataNaudio, 1200, 600, sampleRate, fftWindowsSize, fftOverlap, ColorUtils.ColorPaletteType.PHOTOSOUNDER, true); //spectro.Save(@"c:\spectrogram-rew.png"); // The following lines replicate the BtnDrawSpectrumClick method // from Soundfingerprinting.SoundTools.DrawningTool fileName = @"C:\Users\perivar.nerseth\Music\Maid with the Flaxen Hair.mp3"; float[] wavDataBass = AudioUtilsBass.ReadMonoFromFile(fileName, 5512, 0, 0 ); float[][] data = AudioAnalyzer.CreateSpectrogramLomont(wavDataBass, 2048, 64); Bitmap image = AudioAnalyzer.GetSpectrogramImage(data, 1000, 800); image.Save(@"C:\Users\perivar.nerseth\Music\Maid with the Flaxen Hair_spectrum_2.jpg", ImageFormat.Jpeg); //float[][] logSpectrogram = manager.CreateLogSpectrogram(repositoryGateway._proxy, fileName, secondsToSample*1000, 0); //Bitmap logspectro = AudioAnalyzer.GetSpectrogramImage(logSpectrogram, 1200, 600, secondsToSample*1000, sampleRate, ColorUtils.ColorPaletteType.REW); //logspectro.Save(@"c:\spectrogram-log.png"); //Bitmap waveform = AudioAnalyzer.DrawWaveform(wavDataVB6, new Size (1200, 600), 0, 1, 0, sampleRate); //waveform.Save(@"c:\waveform.png"); //Bitmap waveform = AudioAnalyzer.DrawWaveform(wavDataNaudio, 1200, 600); //waveform.Save(@"c:\waveform.png"); Console.Write("Press any key to continue . . . "); Console.ReadKey(true); }
/// <summary> /// Sets the crypto object to be passed in when authenticating with fingerprint. /// </summary> /// <param name="cryptoObject">Crypto object.</param> public void SetCryptoObject (FingerprintManager.CryptoObject cryptoObject) { mCryptoObject = cryptoObject; }
/// <summary> /// Draw the fingerprints of an audio file /// </summary> private void BtnDrawFingerprintsClick(object sender, EventArgs e) { if (String.IsNullOrEmpty(_tbPathToFile.Text)) { MessageBox.Show(Resources.SelectAPathToBeDrawn, Resources.SelectFile, MessageBoxButtons.OK, MessageBoxIcon.Information); return; } if (!File.Exists(Path.GetFullPath(_tbPathToFile.Text))) { MessageBox.Show(Resources.NoSuchFile, Resources.NoSuchFile, MessageBoxButtons.OK, MessageBoxIcon.Information); return; } if (_lbImageTypes.SelectedIndex == 0) { string fileName = Path.GetFileNameWithoutExtension(_tbPathToFile.Text); SaveFileDialog sfd = new SaveFileDialog { FileName = fileName + "_fingerprints_" + ".jpg", Filter = Resources.FileFilterJPeg }; if (sfd.ShowDialog() == DialogResult.OK) { string path = Path.GetFullPath(sfd.FileName); FadeControls(false); Action action = () => { using (IAudio proxy = new BassProxy()) { FingerprintManager manager = new FingerprintManager(); StaticStride stride = new StaticStride((int) _nudStride.Value); int totalFingerprints = 0; List<bool[]> fingerprints = manager.CreateFingerprints(proxy, Path.GetFullPath(_tbPathToFile.Text), stride); int width = manager.FingerprintLength; int height = manager.LogBins; Bitmap image = Imaging.GetFingerprintsImage(fingerprints, width, height); image.Save(path); image.Dispose(); } }; action.BeginInvoke((result) => { FadeControls(true); MessageBox.Show(Resources.ImageIsDrawn, Resources.Finished, MessageBoxButtons.OK, MessageBoxIcon.Information); action.EndInvoke(result); }, action); } } else if (_lbImageTypes.SelectedIndex == 1) { FolderBrowserDialog fbd = new FolderBrowserDialog(); if (fbd.ShowDialog() == DialogResult.OK) { string path = fbd.SelectedPath; string fileName = Path.GetFileName(_tbPathToFile.Text); FadeControls(false); Action action = () => { using (IAudio proxy = new BassProxy()) { FingerprintManager manager = new FingerprintManager(); StaticStride stride = new StaticStride((int) _nudStride.Value); List<bool[]> result = manager.CreateFingerprints(proxy, Path.GetFullPath(_tbPathToFile.Text), stride); int i = -1; int width = manager.FingerprintLength; int height = manager.LogBins; foreach (bool[] item in result) { Image image = Imaging.GetFingerprintImage(item, width, height); image.Save(path + "\\" + fileName + i++ + ".jpg", ImageFormat.Jpeg); } } }; action.BeginInvoke((result) => { FadeControls(true); MessageBox.Show(Resources.ImageIsDrawn, Resources.Finished, MessageBoxButtons.OK, MessageBoxIcon.Information); action.EndInvoke(result); } , action); } } }
public FingerprintUiHelperBuilder(FingerprintManager fingerprintManager) { mFingerPrintManager = fingerprintManager; }
/// <summary> /// Draw wavelets /// </summary> private void BtnDrawWaveletsClick(object sender, EventArgs e) { if (String.IsNullOrEmpty(_tbPathToFile.Text)) { MessageBox.Show(Resources.SelectAPathToBeDrawn, Resources.SelectFile, MessageBoxButtons.OK, MessageBoxIcon.Information); return; } if (!File.Exists(Path.GetFullPath(_tbPathToFile.Text))) { MessageBox.Show(Resources.NoSuchFile, Resources.NoSuchFile, MessageBoxButtons.OK, MessageBoxIcon.Information); return; } string fileName = Path.GetFileNameWithoutExtension(_tbPathToFile.Text); SaveFileDialog sfd = new SaveFileDialog { FileName = fileName + ".jpg", Filter = Resources.FileFilterJPeg }; if (sfd.ShowDialog() == DialogResult.OK) { string path = Path.GetFullPath(sfd.FileName); FadeControls(false); Action action = () => { using (IAudio proxy = new BassProxy()) { FingerprintManager manager = new FingerprintManager(); StaticStride stride = new StaticStride((int) _nudStride.Value); Image image = Imaging.GetWaveletSpectralImage(Path.GetFullPath(_tbPathToFile.Text), stride, proxy, manager); image.Save(path); image.Dispose(); } }; action.BeginInvoke((result) => { FadeControls(true); MessageBox.Show(Resources.ImageIsDrawn, Resources.Finished, MessageBoxButtons.OK, MessageBoxIcon.Information); action.EndInvoke(result); }, action); } }
/// <summary> /// Draw the spectrogram of the audio file /// </summary> private void BtnDrawSpectrumClick(object sender, EventArgs e) { if (String.IsNullOrEmpty(_tbPathToFile.Text)) { MessageBox.Show(Resources.SelectAPathToBeDrawn, Resources.SelectFile, MessageBoxButtons.OK, MessageBoxIcon.Information); return; } if (!File.Exists(Path.GetFullPath(_tbPathToFile.Text))) { MessageBox.Show(Resources.NoSuchFile, Resources.NoSuchFile, MessageBoxButtons.OK, MessageBoxIcon.Information); return; } SaveFileDialog sfd = new SaveFileDialog { Filter = Resources.FileFilterJPeg, FileName = Path.GetFileNameWithoutExtension(_tbPathToFile.Text) + "_spectrum_" + ".jpg" }; if (sfd.ShowDialog() == DialogResult.OK) { FadeControls(false); Action action = () => { using (BassProxy proxy = new BassProxy()) { FingerprintManager manager = new FingerprintManager(); float[][] data = manager.CreateSpectrogram(proxy, Path.GetFullPath(_tbPathToFile.Text), 0, 0); double duration = proxy.GetTagInfoFromFile(Path.GetFullPath(_tbPathToFile.Text)).duration; Bitmap image = Imaging.GetSpectrogramImage(data, (int) _nudWidth.Value, (int) _nudHeight.Value); image.Save(sfd.FileName, ImageFormat.Jpeg); image.Dispose(); } }; action.BeginInvoke(((result) => { FadeControls(true); action.EndInvoke(result); MessageBox.Show(Resources.ImageIsDrawn, Resources.Finished, MessageBoxButtons.OK, MessageBoxIcon.Information); }), null); } }
/// <summary> /// Draw the signal of the audio file /// </summary> private void BtnDrawSignalClick(object sender, EventArgs e) { if (String.IsNullOrEmpty(_tbPathToFile.Text)) { MessageBox.Show(Resources.SelectAPathToBeDrawn, Resources.SelectFile, MessageBoxButtons.OK, MessageBoxIcon.Information); return; } if (!File.Exists(Path.GetFullPath(_tbPathToFile.Text))) { MessageBox.Show(Resources.NoSuchFile, Resources.NoSuchFile, MessageBoxButtons.OK, MessageBoxIcon.Information); return; } SaveFileDialog sfd = new SaveFileDialog { Filter = Resources.FileFilterJPeg, FileName = Path.GetFileNameWithoutExtension(_tbPathToFile.Text) + "_signal_" + ".jpg" }; if (sfd.ShowDialog() == DialogResult.OK) { string fullpath = Path.GetFullPath(_tbPathToFile.Text); FadeControls(false); Action action = () => { #pragma warning disable 612,618 using (IAudio proxy = new BassProxy()) #pragma warning restore 612,618 { FingerprintManager manager = new FingerprintManager(); float[] data = proxy.ReadMonoFromFile(fullpath, manager.SampleRate, 0, 0); Bitmap image = Imaging.GetSignalImage(data, (int) _nudWidth.Value, (int) _nudHeight.Value); image.Save(sfd.FileName, ImageFormat.Jpeg); image.Dispose(); } }; action.BeginInvoke(((result) => { FadeControls(true); action.EndInvoke(result); MessageBox.Show(Resources.ImageIsDrawn, Resources.Finished, MessageBoxButtons.OK, MessageBoxIcon.Information); }), null); } }
// https://developer.android.com/reference/android/hardware/fingerprint/FingerprintManager.AuthenticationCallback.html public override void OnAuthenticationSucceeded(FingerprintManager.AuthenticationResult res) { base.OnAuthenticationSucceeded(res); var result = new FingerprintAuthenticationResult { Status = FingerprintAuthenticationResultStatus.Succeeded }; SetResultSafe(result); }
/// <summary> /// On window form loading event /// </summary> private void WinMiscLoad(object sender, EventArgs e) { FingerprintManager manager = new FingerprintManager(); _nudFreq.Value = manager.MinFrequency; _nudTopWavelets.Value = manager.TopWavelets; }
protected override void OnCreate(Bundle savedInstanceState) { ServicePointManager.ServerCertificateValidationCallback += new RemoteCertificateValidationCallback(ValidateServerCertificate); base.OnCreate(savedInstanceState); SetContentView(Resource.Layout.LoginConocido); nombreConocido = MainActivity.returnNombreConsultaEnrolado(); nombreDesdeConfirmacion = ConfirmacionEnroladoActivity.returnNombreConsultaEnroladoConocido(); nombreTitulo = nombreConocido; if (string.IsNullOrEmpty(nombreTitulo)) { nombreTitulo = nombreDesdeConfirmacion; } string nombreLogin = nombreTitulo; nombreUsuario = nombreLogin.Split(' '); primerNombreUsuario = nombreUsuario[0].ToLower(); segundoNombreUsuario = nombreUsuario[1].ToLower(); parametriaLogUtil = new ParametriaLogUtil(); string primeraLetraPrimerNombre = primerNombreUsuario.Substring(0, 1).ToUpper(); string restoPrimernombreFormateado = primerNombreUsuario.Substring(1, primerNombreUsuario.Length - 1); primerNombreFormateado = primeraLetraPrimerNombre + restoPrimernombreFormateado; if (!string.IsNullOrEmpty(segundoNombreUsuario)) { string primeraLetraSegundoNombre = segundoNombreUsuario.Substring(0, 1).ToUpper(); string restoSegundonombreFormateado = segundoNombreUsuario.Substring(1, segundoNombreUsuario.Length - 1); segundoNombreFormateado = primeraLetraSegundoNombre + restoSegundonombreFormateado; } string nombreUserFormateado = primerNombreFormateado + " " + segundoNombreFormateado; rutConocido = MainActivity.returnRutConsultaEnrolado(); rutDesdeConfirmacion = ConfirmacionEnroladoActivity.returnRutConsultaEnroladoConocido(); rutDefinitivo = rutConocido; if (string.IsNullOrEmpty(rutDefinitivo)) { rutDefinitivo = rutDesdeConfirmacion; } String nombreArchivo = "app-bco_security.sqlite"; String rutaCarpeta = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal); String ruta = System.IO.Path.Combine(rutaCarpeta, nombreArchivo); KEY_NAME = DatabaseHelper.pass(ruta); KeyguardManager keyguardManager = (KeyguardManager)GetSystemService(KeyguardService); FingerprintManager fingerprintManager = (FingerprintManager)GetSystemService(FingerprintService); if (ActivityCompat.CheckSelfPermission(this, Manifest.Permission.UseFingerprint) != (int)Android.Content.PM.Permission.Granted) { return; } if (!fingerprintManager.IsHardwareDetected) { //Toast.MakeText(ApplicationContext, "Lector de huella no habilitado", ToastLength.Long).Show(); } else { if (!fingerprintManager.HasEnrolledFingerprints) { //Toast.MakeText(ApplicationContext, "Debes enrolar tu huella a la app", ToastLength.Long).Show(); } else { if (!keyguardManager.IsKeyguardSecure) { Toast.MakeText(ApplicationContext, "No tienes habilitada la configuracion del scaner dactilar", ToastLength.Short).Show(); } else { GenKey(); } if (CipherInit()) { FingerprintManager.CryptoObject cryptoObject = new FingerprintManager.CryptoObject(cipher); FingerprintHandlerLogin helperLogin = new FingerprintHandlerLogin(this); helperLogin.StartAuthentication(fingerprintManager, cryptoObject); } } } txtUsernameConocido = FindViewById <TextView>(Resource.Id.txtUsernameConocido); txtUsernameConocido.Text = "Hola, " + nombreUserFormateado; txtClaveConocido = FindViewById <EditText>(Resource.Id.txtClaveConocido); lblMensajeConocido = FindViewById <TextView>(Resource.Id.lblMensajeConocido); txtInputClaveConocido = FindViewById <TextInputLayout>(Resource.Id.txtInputClaveConocido); btnIniciaSesionConocido = FindViewById <Button>(Resource.Id.btnIniciaSesionConocido); btnIniciaSesionConocido.Click += BtnIniciaSesionConocido_ClickAsync; btnProblemasClaveConocido = FindViewById <ImageView>(Resource.Id.btnProblemasClaveConocido); btnProblemasClaveConocido.Click += BtnProblemasClaveConocido_Click; txtClaveConocido.TextChanged += TxtClaveConocido_TextChanged; btnAyudaLoginConocido = FindViewById <ImageView>(Resource.Id.btnAyudaLoginConocido); var fontRegular = Typeface.CreateFromAsset(Assets, rutaFuenteTitiliumRegular); var fontSemiBold = Typeface.CreateFromAsset(Assets, rutaFuenteTitiliumSemiBold); txtUsernameConocido.Typeface = fontRegular; btnIniciaSesionConocido.Typeface = fontSemiBold; txtClaveConocido.Typeface = fontRegular; txtInputClaveConocido.Typeface = fontRegular; lblMensajeConocido.Typeface = fontRegular; lineTxtClaveConocido = FindViewById <View>(Resource.Id.lineTxtClaveConocido); dialogoLoadingBcoSecurityActivity = new DialogoLoadingBcoSecurityActivity(this); }
/// <summary> /// Get fingerprint similarity of one song /// </summary> /// <param name = "manager">Fingerprint manager used in file decomposition</param> /// <param name = "dbstride">Database creation stride</param> /// <param name = "queryStride">Query stride</param> /// <param name = "numberOfItemsToCompare">Number of subsequent elements to compare with</param> /// <param name = "proxy">Proxy</param> /// <param name = "path">Path to first file</param> /// <param name = "results">Results object to be filled with the corresponding data</param> private static void GetFingerprintSimilarity(FingerprintManager manager, IStride dbstride, IStride queryStride, int numberOfItemsToCompare, IAudio proxy, string path, DumpResults results) { int startindex = 0; int count = 0; double sum = 0; List<bool[]> list = manager.CreateFingerprints(proxy, path, dbstride); List<bool[]> listToCompare = manager.CreateFingerprints(proxy, path, queryStride); count = list.Count; int toCompare = listToCompare.Count; double max = double.MinValue; for (int i = 0; i < count; i++) { for (int j = 0; j < toCompare; j++) { double value = MinHash.CalculateSimilarity(list[i], listToCompare[j]); if (value > max) max = value; sum += value; } } results.Results.SumJaqFingerprintsSimilarity = sum; results.Results.AverageJaqFingerprintSimilarity = sum/(count*toCompare); results.Results.MaxJaqFingerprintSimilarity = max; }
/// <summary> /// Protected constructor of WinQueryResults class /// </summary> /// <param name = "connectionString">Connection string used for the underlying data source</param> /// <param name = "secondsToAnalyze">Number of consequent fingerprints to analyze</param> /// <param name = "startSecond">Starting seconds</param> /// <param name = "stride">Stride used in the query</param> /// <param name = "topWavelets">Number of top wavelets to analyze</param> /// <param name = "fileList">List of all files to be recognized</param> protected WinQueryResults(string connectionString, int secondsToAnalyze, int startSecond, IStride stride, int topWavelets, List<string> fileList) { InitializeComponent(); /*Initialize Designer Components*/ Icon = Resources.Sound; _connectionString = connectionString; _topWavelets = topWavelets; _dalManager = new DaoGateway(ConfigurationManager.ConnectionStrings["FingerprintConnectionString"].ConnectionString); _permStorage = new DbPermutations(ConfigurationManager.ConnectionStrings["FingerprintConnectionString"].ConnectionString); _manager = new FingerprintManager {TopWavelets = topWavelets}; _dalManager.SetConnectionString(_connectionString); /*Set connection string for DAL manager*/ _secondsToAnalyze = secondsToAnalyze; /*Number of fingerprints to analyze from each song*/ _startSecond = startSecond; _fileList = fileList; /*List of files to analyze*/ _dgvResults.Columns.Add(COL_SONG_NAME, "Initial Song"); _dgvResults.Columns[COL_SONG_NAME].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; _dgvResults.Columns.Add(COL_RESULT_NAME, "Result Song"); _dgvResults.Columns[COL_RESULT_NAME].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; _dgvResults.Columns.Add(COL_POSITION, "Position"); _dgvResults.Columns[COL_POSITION].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; _dgvResults.Columns.Add(COL_RESULT, "Result"); _dgvResults.Columns[COL_RESULT].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; _dgvResults.Columns.Add(COL_HAMMING_AVG, "Hamming Avg."); _dgvResults.Columns[COL_HAMMING_AVG].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; _queryStride = stride; }
public override void OnRequestPermissionsResult(int requestCode, string[] permissions, Android.Content.PM.Permission[] grantResults) { if (requestCode == FINGERPRINT_PERMISSION_REQUEST_CODE && grantResults[0] == Android.Content.PM.Permission.Granted) { SetContentView (Resource.Layout.activity_main); var purchaseButton = FindViewById<Button> (Resource.Id.purchase_button); if (!mKeyguardManager.IsKeyguardSecure) { purchaseButton.Enabled = false; // Show a message that the user hasn't set up a fingerprint or lock screen. Toast.MakeText (this, "Secure lock screen hasn't set up.\n" + "Go to 'Settings -> Security -> Fingerprint' to set up a fingerprint", ToastLength.Long).Show (); return; } mFingerprintManager = (FingerprintManager)GetSystemService (Context.FingerprintService); if (!mFingerprintManager.HasEnrolledFingerprints) { purchaseButton.Enabled = false; // This happens when no fingerprints are registered. Toast.MakeText (this, "Go to 'Settings -> Security -> Fingerprint' " + "and register at least one fingerprint", ToastLength.Long).Show (); return; } CreateKey (); purchaseButton.Enabled = true; purchaseButton.Click += (sender, e) => { // Show the fingerprint dialog. The user has the option to use the fingerprint with // crypto, or you can fall back to using a server-side verified password. FindViewById (Resource.Id.confirmation_message).Visibility = ViewStates.Gone; FindViewById (Resource.Id.encrypted_message).Visibility = ViewStates.Gone; mFragment = new FingerprintAuthenticationDialogFragment (); mSharedPreferences = this.GetPreferences (FileCreationMode.Private); if (InitCipher ()) { mFragment.SetCryptoObject (new FingerprintManager.CryptoObject (mCipher)); var useFingerprintPreference = mSharedPreferences.GetBoolean (GetString (Resource.String.use_fingerprint_to_authenticate_key), true); if (useFingerprintPreference) { mFragment.SetStage (FingerprintAuthenticationDialogFragment.Stage.Fingerprint); } else { mFragment.SetStage (FingerprintAuthenticationDialogFragment.Stage.Password); } mFragment.Show (FragmentManager, DIALOG_FRAGMENT_TAG); } else { mFragment.SetCryptoObject (new FingerprintManager.CryptoObject (mCipher)); mFragment.SetStage (FingerprintAuthenticationDialogFragment.Stage.NewFingerprintEnrolled); mFragment.Show (FragmentManager, DIALOG_FRAGMENT_TAG); } }; } }
/// <summary> /// Start inserting into the database /// </summary> private void BtnStartClick(object sender, EventArgs e) { string connectionString = _cmbDBFillerConnectionString.SelectedItem.ToString(); //Set Connection String try { _dalManager.SetConnectionString(connectionString); //Try Connection String } catch (Exception ex) { MessageBox.Show(ex.Message, Resources.Error, MessageBoxButtons.OK, MessageBoxIcon.Error); FadeAllControls(false); return; } if (!String.IsNullOrEmpty(_tbRootFolder.Text) || !String.IsNullOrEmpty(_tbSingleFile.Text) && _fileList == null) { _fileList = new List<string>(); if (!String.IsNullOrEmpty(_tbRootFolder.Text)) TbRootFolderTextChanged(this, null); if (!String.IsNullOrEmpty(_tbSingleFile.Text)) TbSingleFileTextChanged(this, null); } if (_fileList == null || _fileList.Count == 0) { MessageBox.Show(Resources.FileListEmpty, Resources.FileListEmptyCaption, MessageBoxButtons.OK, MessageBoxIcon.Information); return; } FadeAllControls(true); //Fade all controls int rest = _fileList.Count%THREADS; int filesPerThread = _fileList.Count/THREADS; _listOfAllAlbums = _dalManager.ReadAlbums(); //Get all albums _unknownAlbum = _dalManager.ReadUnknownAlbum(); //Read unknown album int topWavelets = (int) _nudTopWav.Value; _fingerManager = new FingerprintManager {TopWavelets = topWavelets}; switch (_hashAlgorithm) { case HashAlgorithm.LSH: _hashTables = (int) _nudHashTables.Value; //If LSH is used # of Hash tables _hashKeys = (int) _nudHashKeys.Value; //If LSH is used # of keys per table break; case HashAlgorithm.NeuralHasher: if (String.IsNullOrEmpty(_tbPathToEnsemble.Text)) //Check if the path to ensemble is specified { MessageBox.Show(Resources.SpecifyPathToNetworkEnsemble, Resources.Error, MessageBoxButtons.OK, MessageBoxIcon.Exclamation); FadeAllControls(false); return; } try { _ensemble = NNEnsemble.Load(_tbPathToEnsemble.Text); //Load the ensemble } catch (Exception ex) { MessageBox.Show(ex.Message); FadeAllControls(false); return; } break; case HashAlgorithm.None: break; } BeginInvoke(new Action(() => { }), null); ResetControls(); int runningThreads = THREADS; for (int i = 0; i < THREADS; i++) //Start asynchronous operation { int start = i*filesPerThread; //Define start and end indexes int end = (i == THREADS - 1) ? i*filesPerThread + filesPerThread + rest : i*filesPerThread + filesPerThread; Action<int, int> action = InsertInDatabase; action.BeginInvoke(start, end, (result) => { //End Asynchronous operation Action<int, int> item = (Action<int, int>) result.AsyncState; item.EndInvoke(result); Interlocked.Decrement(ref runningThreads); if (runningThreads == 0) { /********* END OF INSERTION PROCESS HERE!********/ Invoke(new Action(() => { _pbTotalSongs.Visible = false; FadeAllControls(false); _tbRootFolder.Text = null; _tbSingleFile.Text = null; })); MessageBox.Show(Resources.InsertionEnded, Resources.End, MessageBoxButtons.OK, MessageBoxIcon.Information); } }, action); } }
/// <summary> /// Gets the spectrum of the wavelet decomposition before extracting top wavelets and binary transformation /// </summary> /// <param name = "pathToFile">Path to file to be drawn</param> /// <param name = "stride">Stride within the fingerprint creation</param> /// <param name = "proxy">Proxy manager</param> /// <param name = "manager">Fingerprint manager</param> /// <returns>Image to be saved</returns> public static Image GetWaveletSpectralImage(string pathToFile, IStride stride, IAudio proxy, FingerprintManager manager) { List<float[][]> wavelets = new List<float[][]>(); float[][] spectrum = manager.CreateLogSpectrogram(proxy, pathToFile, 0, 0); int specLen = spectrum.GetLength(0); int start = stride.GetFirstStride()/manager.Overlap; int logbins = manager.LogBins; int fingerprintLength = manager.FingerprintLength; int overlap = manager.Overlap; while (start + fingerprintLength < specLen) { float[][] frames = new float[fingerprintLength][]; for (int i = 0; i < fingerprintLength; i++) { frames[i] = new float[logbins]; Array.Copy(spectrum[start + i], frames[i], logbins); } start += fingerprintLength + stride.GetStride()/overlap; wavelets.Add(frames); } const int imagesPerRow = 5; /*5 bitmap images per line*/ const int spaceBetweenImages = 10; /*10 pixel space between images*/ int width = wavelets[0].GetLength(0); int height = wavelets[0][0].Length; int fingersCount = wavelets.Count; int rowCount = (int) Math.Ceiling((float) fingersCount/imagesPerRow); int imageWidth = imagesPerRow*(width + spaceBetweenImages) + spaceBetweenImages; int imageHeight = rowCount*(height + spaceBetweenImages) + spaceBetweenImages; Bitmap image = new Bitmap(imageWidth, imageHeight, PixelFormat.Format16bppRgb565); /*Change the background of the bitmap*/ for (int i = 0; i < imageWidth; i++) for (int j = 0; j < imageHeight; j++) image.SetPixel(i, j, Color.White); double maxValue = wavelets.Max((wavelet) => (wavelet.Max((column) => column.Max()))); int verticalOffset = spaceBetweenImages; int horizontalOffset = spaceBetweenImages; int count = 0; double max = wavelets.Max(wav => wav.Max(w => w.Max(v => Math.Abs(v)))); foreach (float[][] wavelet in wavelets) { for (int i = 0; i < width /*128*/; i++) { for (int j = 0; j < height /*32*/; j++) { Color color = ValueToBlackWhiteColor(wavelet[i][j], max/4); image.SetPixel(i + horizontalOffset, j + verticalOffset, color); } } count++; if (count%imagesPerRow == 0) { verticalOffset += height + spaceBetweenImages; horizontalOffset = spaceBetweenImages; } else horizontalOffset += width + spaceBetweenImages; } return image; }
public override void OnAuthenticationSucceeded (FingerprintManager.AuthenticationResult result) { mErrorTextView.RemoveCallbacks (ResetErrorTextRunnable); mIcon.SetImageResource (Resource.Drawable.ic_fingerprint_success); mErrorTextView.SetTextColor (mErrorTextView.Resources.GetColor (Resource.Color.success_color, null)); mErrorTextView.Text = mErrorTextView.Resources.GetString (Resource.String.fingerprint_success); mIcon.PostDelayed (() => { mCallback.OnAuthenticated (); }, SUCCESS_DELAY_MILLIS); }
public FingerprintUiHelperBuilder (FingerprintManager fingerprintManager) { mFingerPrintManager = fingerprintManager; }
public static void Main(string[] args) { /* * int nFFT = 1024; * int samplerate = 44100; * int length = samplerate * 10; // 10 sec * * double freq1, freq2; * int i1, i2; * for (int i = 0; i < nFFT + 1; i++) { * freq1 = MathUtils.Index2Freq(i, samplerate, nFFT); * freq2 = MathUtils.IndexToFreq(i, samplerate, nFFT); * i1 = MathUtils.Freq2Index(freq1, samplerate, nFFT); * i2 = MathUtils.FreqToIndex((float)freq2, samplerate, nFFT); * } */ // http://www.music.mcgill.ca/~gary/307/week5/additive.html //SaveColorPaletteBar("c:\\rew-colorbar-generated.png", "c:\\rew-colorbar-generated.csv", ColorPaletteType.REWColorPalette); /* * List<Color> rew_hsb_gradients = ColorUtils.GetHSBColorGradients(256, ColorUtils.ColorPaletteType.REW); * ColorUtils.SaveColorGradients("c:\\rew-hsb-gradients.png", rew_hsb_gradients, 40); * List<Color> rew_hsl_gradients = ColorUtils.GetHSLColorGradients(256, ColorUtils.ColorPaletteType.REW); * ColorUtils.SaveColorGradients("c:\\rew-hsl-gradients.png", rew_hsl_gradients, 40); * * List<Color> sox_hsb_gradients = ColorUtils.GetHSBColorGradients(256, ColorUtils.ColorPaletteType.SOX); * ColorUtils.SaveColorGradients("c:\\sox-hsb-gradients.png", sox_hsb_gradients, 40); * List<Color> sox_hsl_gradients = ColorUtils.GetHSLColorGradients(256, ColorUtils.ColorPaletteType.SOX); * ColorUtils.SaveColorGradients("c:\\sox-hsl-gradients.png", sox_hsl_gradients, 40); * * List<Color> photosounder_hsb_gradients = ColorUtils.GetHSBColorGradients(256, ColorUtils.ColorPaletteType.PHOTOSOUNDER); * ColorUtils.SaveColorGradients("c:\\photosounder_hsb_gradients.png", photosounder_hsb_gradients, 40); * List<Color> photosounder_hsl_gradients = ColorUtils.GetHSLColorGradients(256, ColorUtils.ColorPaletteType.PHOTOSOUNDER); * ColorUtils.SaveColorGradients("c:\\photosounder_hsl_gradients.png", photosounder_hsl_gradients, 40); * List<Color> photosounder_rgb_gradients = ColorUtils.GetRGBColorGradients(255, ColorUtils.ColorPaletteType.PHOTOSOUNDER); * ColorUtils.SaveColorGradients("c:\\photosounder_rgb_gradients.png", photosounder_rgb_gradients, 40); * * List<Color> grey_hsb_gradients = ColorUtils.GetHSBColorGradients(256, ColorUtils.ColorPaletteType.BLACK_AND_WHITE); * ColorUtils.SaveColorGradients("c:\\grey-hsb-gradients.png", grey_hsb_gradients, 40); */ /* * ReadColorPaletteBar(@"C:\Users\perivar.nerseth\SkyDrive\Temp\sox_colorbar.png", "c:\\sox_colorbar.csv"); * ReadColorPaletteBar(@"C:\Users\perivar.nerseth\SkyDrive\Temp\soundforge_colorbar.png", "c:\\soundforge_colorbar.csv"); * ReadColorPaletteBar(@"C:\Users\perivar.nerseth\SkyDrive\Temp\rew_colorbar.png", "c:\\rew_colorbar.csv"); * ReadColorPaletteBar(@"C:\Users\perivar.nerseth\SkyDrive\Temp\sox_colorbar.png", "c:\\sox_colorbar.csv"); * ReadColorPaletteBar(@"C:\Users\perivar.nerseth\SkyDrive\Temp\thermal_colorbar.png", "c:\\thermal_colorbar.csv"); * ReadColorPaletteBar(@"C:\rew-gradients.png", "c:\\rew-gradients.csv"); */ //String fileName = @"C:\Users\perivar.nerseth\Music\Sleep Away.mp3"; //String fileName = @"C:\Users\perivar.nerseth\Music\Sleep Away32f.wav"; String fileName = @"C:\Users\perivar.nerseth\Music\Sleep Away16.wav"; //String fileName = @"C:\Users\perivar.nerseth\Music\Maid with the Flaxen Hair.mp3"; //String fileName = @"G:\Cubase and Nuendo Projects\Music To Copy Learn\Britney Spears - Hold It Against Me\02 Hold It Against Me (Instrumental) 1.mp3"; Console.WriteLine("Analyzer starting ..."); RepositoryGateway repositoryGateway = new RepositoryGateway(); FingerprintManager manager = new FingerprintManager(); // VB6 FFT double sampleRate = 44100; // 44100, default 5512 int fftWindowsSize = 16384; //32768 16384 8192 4096 2048, default 256*8 (2048) to 256*128 (32768), reccomended: 256*64 = 16384 int secondsToSample = 25; //25, 15; int fftOverlap = (int)(sampleRate * secondsToSample / 1280); // 32768:990, 16384:990, 8192:990, 4096:990 //float fftOverlapPercentage = 94.0f; // 99.0f number between 0 and 100 //float[] wavDataVB6 = repositoryGateway._proxy.ReadMonoFromFile(fileName, (int) sampleRate, secondsToSample*1000, 20*1000 ); //float[] wavDataVB6 = repositoryGateway._proxy.ReadMonoFromFile(fileName, (int) sampleRate, secondsToSample*1000, 0); //MathUtils.NormalizeInPlace(wavDataVB6); //Export.exportCSV(@"c:\bass.csv", wavDataVB6); float[] wavDataNaudio = AudioUtilsNAudio.ReadMonoFromFile(fileName, (int)sampleRate, secondsToSample * 1000, 0); //float[] wavDataNaudio = AudioUtilsNAudio.ReadMonoFromFile(fileName, (int) sampleRate, 0, 0); /* * float[] wavDataNaudio = new float[(int) (sampleRate*secondsToSample)]; * BasicOscillatorProvider basic = new BasicOscillatorProvider(); * * int length = (int)(sampleRate*3); * int offset = 0; * * basic.Amplitude = MathUtils.DecibelToAmplitude(-80); * basic.SetFrequency(220); * basic.SetOscWaveshape(BasicOscillatorProvider.WAVESHAPE.SINE); * offset += basic.Read(wavDataNaudio, offset, length); * * basic.Amplitude = MathUtils.DecibelToAmplitude(-60); * basic.SetFrequency(440); * basic.SetOscWaveshape(BasicOscillatorProvider.WAVESHAPE.SQUARE); * offset += basic.Read(wavDataNaudio, offset, length); * * basic.Amplitude = MathUtils.DecibelToAmplitude(-40); * basic.SetFrequency(880); * basic.SetOscWaveshape(BasicOscillatorProvider.WAVESHAPE.TRIANGLE); * offset += basic.Read(wavDataNaudio, offset, length); * * basic.Amplitude = MathUtils.DecibelToAmplitude(-20); * basic.SetFrequency(1760); * basic.SetOscWaveshape(BasicOscillatorProvider.WAVESHAPE.SAW); * offset += basic.Read(wavDataNaudio, offset, length); * * basic.Amplitude = MathUtils.DecibelToAmplitude(-10); * basic.SetFrequency(3520); * basic.SetOscWaveshape(BasicOscillatorProvider.WAVESHAPE.SINE); * offset += basic.Read(wavDataNaudio, offset, length); * * basic.Amplitude = MathUtils.DecibelToAmplitude(0); * basic.SetFrequency(1760); * basic.SetOscWaveshape(BasicOscillatorProvider.WAVESHAPE.SAW); * offset += basic.Read(wavDataNaudio, offset, length); * * AudioUtilsNAudio.WriteIEEE32WaveFileMono(@"c:\sines.wav", 44100, wavDataNaudio); */ //MathUtils.NormalizeInPlace(wavDataNaudio); //Export.exportCSV(@"c:\naudio.csv", wavDataNaudio); //VB6Spectrogram vb6Spect = new VB6Spectrogram(); //vb6Spect.ComputeColorPalette(); //float[][] vb6Spectrogram = vb6Spect.Compute(wavDataVB6, sampleRate, fftWindowsSize, fftOverlapPercentage); //Export.exportCSV (@"c:\VB6Spectrogram-full.csv", vb6Spectrogram); // Exocortex.DSP FFT /* * int numberOfSamples = wavDataNaudio.Length; * fftOverlapPercentage = fftOverlapPercentage / 100; * long ColSampleWidth = (long)(fftWindowsSize * (1 - fftOverlapPercentage)); * double fftOverlapSamples = fftWindowsSize * fftOverlapPercentage; * long NumCols = numberOfSamples / ColSampleWidth; * * int fftOverlap = (int)((numberOfSamples - fftWindowsSize) / NumCols); * int numberOfSegments = (numberOfSamples - fftWindowsSize)/fftOverlap; */ //System.Console.Out.WriteLine(String.Format("EXO: fftWindowsSize: {0}, Overlap samples: {1:n2}.", fftWindowsSize, fftOverlap )); //VIPSLib.Audio.WAVFile wavefile = new VIPSLib.Audio.WAVFile(); //wavefile.ReadFromFileToDouble(fileName.Substring(0, fileName.LastIndexOf(".")) + ".wav"); //RiffRead riff = new RiffRead(fileName.Substring(0, fileName.LastIndexOf(".")) + ".wav"); //riff.Process(); /* * VIPSLib.Audio.MFCC mfcclib = new VIPSLib.Audio.MFCC((float)sampleRate); * double[][] data = riff.SoundData; * double min; * double max; * MathUtils.ComputeMinAndMax(data, out min, out max); * double[][] mfcc = mfcclib.Process(MathUtils.FloatToDouble(wavDataVB6)); * * float fmin; * float fmax; * MathUtils.ComputeMinAndMax(wavDataVB6, out fmin, out fmax); */ //double[][] mfcc = mfcclib.Process(riff.SoundData[0]); //float[][] mfccFloats = MathUtils.DoubleToFloat(mfcc); // GENERATE SPECTROGRAM //Bitmap spectro = AudioAnalyzer.GetSpectrogramImage(wavDataNaudio, 1200, 600, sampleRate, fftWindowsSize, fftOverlap, ColorUtils.ColorPaletteType.PHOTOSOUNDER, true); //spectro.Save(@"c:\spectrogram-rew.png"); // The following lines replicate the BtnDrawSpectrumClick method // from Soundfingerprinting.SoundTools.DrawningTool fileName = @"C:\Users\perivar.nerseth\Music\Maid with the Flaxen Hair.mp3"; float[] wavDataBass = AudioUtilsBass.ReadMonoFromFile(fileName, 5512, 0, 0); float[][] data = AudioAnalyzer.CreateSpectrogramLomont(wavDataBass, 2048, 64); Bitmap image = AudioAnalyzer.GetSpectrogramImage(data, 1000, 800); image.Save(@"C:\Users\perivar.nerseth\Music\Maid with the Flaxen Hair_spectrum_2.jpg", ImageFormat.Jpeg); //float[][] logSpectrogram = manager.CreateLogSpectrogram(repositoryGateway._proxy, fileName, secondsToSample*1000, 0); //Bitmap logspectro = AudioAnalyzer.GetSpectrogramImage(logSpectrogram, 1200, 600, secondsToSample*1000, sampleRate, ColorUtils.ColorPaletteType.REW); //logspectro.Save(@"c:\spectrogram-log.png"); //Bitmap waveform = AudioAnalyzer.DrawWaveform(wavDataVB6, new Size (1200, 600), 0, 1, 0, sampleRate); //waveform.Save(@"c:\waveform.png"); //Bitmap waveform = AudioAnalyzer.DrawWaveform(wavDataNaudio, 1200, 600); //waveform.Save(@"c:\waveform.png"); Console.Write("Press any key to continue . . . "); Console.ReadKey(true); }
/// <summary> /// Get hash similarity of one song /// </summary> /// <param name = "manager">Fingerprint manager</param> /// <param name = "dbstride">Database stride between fingerprints</param> /// <param name = "queryStride">Query stride between fingerprints</param> /// <param name = "numberOfFingerprintsToAnalyze">Number of fingerprints to analyze</param> /// <param name = "hashTables">Number of hash tables in the LSH transformation</param> /// <param name = "hashKeys">Number of hash keys per table in the LSH transformation</param> /// <param name = "proxy">Audio proxy</param> /// <param name = "path">Path to analyzed file</param> /// <param name = "results">Results object to be filled with the appropriate data</param> private static void GetHashSimilarity(FingerprintManager manager, IStride dbstride, IStride queryStride, int numberOfFingerprintsToAnalyze, int hashTables, int hashKeys, IAudio proxy, string path, DumpResults results) { double sum = 0; int hashesCount = 0; int startindex = 0; List<bool[]> listDb = manager.CreateFingerprints(proxy, path, dbstride); List<bool[]> listQuery = manager.CreateFingerprints(proxy, path, queryStride); IPermutations perms = new DbPermutations(ConfigurationManager.ConnectionStrings["FingerprintConnectionString"].ConnectionString); MinHash minHash = new MinHash(perms); List<int[]> minHashDb = listDb.Select(minHash.ComputeMinHashSignature).ToList(); List<int[]> minHashQuery = listQuery.Select(minHash.ComputeMinHashSignature).ToList(); /*Calculate Min Hash signature similarity by comparing 2 consecutive signatures*/ int countDb = minHashDb.Count; int countQuery = minHashQuery.Count; int minHashSignatureLen = minHashDb[0].Length; int similarMinHashValues = 0; for (int i = 0; i < countDb; i++) { for (int j = 0; j < countQuery; j++) { for (int k = 0; k < minHashSignatureLen; k++) if (minHashDb[i][k] == minHashQuery[j][k]) similarMinHashValues++; } } results.Results.SumIdenticalMinHash = similarMinHashValues; results.Results.AverageIdenticalMinHash = (double) similarMinHashValues/(countDb*countQuery*minHashSignatureLen); /*Group min hash signatures into LSH Buckets*/ List<Dictionary<int, long>> lshBucketsDb = minHashDb.Select(item => minHash.GroupMinHashToLSHBuckets(item, hashTables, hashKeys)).ToList(); List<Dictionary<int, long>> lshBucketsQuery = minHashQuery.Select(item => minHash.GroupMinHashToLSHBuckets(item, hashTables, hashKeys)).ToList(); int countSignatures = lshBucketsDb.Count; sum = 0; foreach (Dictionary<int, long> a in lshBucketsDb) { Dictionary<int, long>.ValueCollection aValues = a.Values; foreach (Dictionary<int, long> b in lshBucketsQuery) { Dictionary<int, long>.ValueCollection bValues = b.Values; hashesCount += aValues.Intersect(bValues).Count(); } } results.Results.SumJaqLSHBucketSimilarity = -1; results.Results.AverageJaqLSHBucketSimilarity = -1; results.Results.TotalIdenticalLSHBuckets = hashesCount; }