|
| 1 | +"""PSNR calculation utilities.""" |
| 2 | + |
| 3 | +import logging |
| 4 | +import math |
| 5 | +import wave |
| 6 | +import numpy as np |
| 7 | +import scipy.io.wavfile as wavfile |
| 8 | +import librosa |
| 9 | + |
| 10 | + |
| 11 | +def calc_per_channel_psnr_pcm( |
| 12 | + ref_signal: np.ndarray, signal: np.ndarray, sampwidth_bytes: int |
| 13 | +): |
| 14 | + """Calculates the PSNR between two signals. |
| 15 | +
|
| 16 | + Args: |
| 17 | + ref_signal: The reference signal as a numpy array. |
| 18 | + signal: The signal to compare as a numpy array. |
| 19 | + sampwidth_bytes: The sample width in bytes (e.g. 2 for 16-bit, 3 for |
| 20 | + 24-bit). |
| 21 | +
|
| 22 | + Returns: |
| 23 | + The per channel PSNR in dB. |
| 24 | + """ |
| 25 | + assert ( |
| 26 | + sampwidth_bytes > 1 |
| 27 | + ), "Supports sample format: [pcm_s16le, pcm_s24le, pcm_s32le]" |
| 28 | + max_value = pow(2, sampwidth_bytes * 8) - 1 |
| 29 | + |
| 30 | + # To prevent overflow |
| 31 | + ref_signal = ref_signal.astype("int64") |
| 32 | + signal = signal.astype("int64") |
| 33 | + |
| 34 | + mse = np.mean((ref_signal - signal) ** 2, axis=0, dtype="float64") |
| 35 | + |
| 36 | + psnr_list = list() |
| 37 | + |
| 38 | + # To support mono signal |
| 39 | + num_channels = 1 if ref_signal.shape[1:] == () else ref_signal.shape[1] |
| 40 | + for i in range(num_channels): |
| 41 | + mse_value = mse[i] if num_channels > 1 else mse |
| 42 | + if mse_value == 0: |
| 43 | + psnr_list.append(np.inf) |
| 44 | + logging.debug("ch#%d PSNR: inf", i) |
| 45 | + else: |
| 46 | + psnr_value = 10 * math.log10(max_value**2 / mse_value) |
| 47 | + psnr_list.append(psnr_value) |
| 48 | + logging.debug("ch#%d PSNR: %f dB", i, psnr_value) |
| 49 | + |
| 50 | + return psnr_list |
| 51 | + |
| 52 | + |
| 53 | +def calc_per_channel_lsd_pcm(ref_signal: np.ndarray, |
| 54 | + signal: np.ndarray, |
| 55 | + sampling_rate: int): |
| 56 | + """Calculates the log spectral distance using Mel bins between two signals. |
| 57 | +
|
| 58 | + Args: |
| 59 | + ref_signal: The reference signal as a numpy array. |
| 60 | + signal: The signal to compare as a numpy array. |
| 61 | + sampling rate: The sampling rate of the signals in Hz. |
| 62 | +
|
| 63 | + Returns: |
| 64 | + The per channel log spectral distance in dB. |
| 65 | + """ |
| 66 | + eps = 1e-4 |
| 67 | + |
| 68 | + # Convert to float |
| 69 | + ref_signal = ref_signal / np.iinfo(ref_signal.dtype).max |
| 70 | + signal = signal / np.iinfo(signal.dtype).max |
| 71 | + |
| 72 | + lsd_list = list() |
| 73 | + |
| 74 | + # To support mono channel |
| 75 | + num_channels = 1 if ref_signal.shape[1:] == () else ref_signal.shape[1] |
| 76 | + for i in range(num_channels): |
| 77 | + ref_channel = ref_signal[:, i] if num_channels > 1 else ref_signal |
| 78 | + signal_channel = signal[:, i] if num_channels > 1 else signal |
| 79 | + |
| 80 | + lsd_frames = list() |
| 81 | + |
| 82 | + # Compute mel spectrogram |
| 83 | + mel_ref = librosa.feature.melspectrogram(y=ref_channel, sr=sampling_rate) |
| 84 | + mel_signal = librosa.feature.melspectrogram(y=signal_channel, |
| 85 | + sr=sampling_rate) |
| 86 | + |
| 87 | + log_mel_ref = 10 * np.log10(mel_ref + eps) |
| 88 | + log_mel_signal = 10 * np.log10(mel_signal + eps) |
| 89 | + |
| 90 | + diff_squared = (log_mel_ref - log_mel_signal) ** 2 |
| 91 | + |
| 92 | + # Average across mel bins, which is the 0th dimension |
| 93 | + lsd_per_frame = np.sqrt(np.mean(diff_squared, axis=0)) |
| 94 | + |
| 95 | + # shape: (1, num_frames) -> (num_frames,) |
| 96 | + lsd_per_frame = np.squeeze(lsd_per_frame) |
| 97 | + |
| 98 | + lsd_value = np.mean(lsd_per_frame) |
| 99 | + lsd_list.append(lsd_value) |
| 100 | + logging.debug('ch#d LSD: %f dB', i, lsd_value) |
| 101 | + |
| 102 | + return lsd_list |
| 103 | + |
| 104 | + |
| 105 | +def calc_score_wav(ref_filepath: str, target_filepath: str, metric: str): |
| 106 | + """Calculates the score between two WAV files. |
| 107 | +
|
| 108 | + Args: |
| 109 | + ref_filepath: Path to the reference WAV file. |
| 110 | + target_filepath: Path to the target WAV file to compare. |
| 111 | + metric: one of 'PSNR' or 'SNR'. |
| 112 | +
|
| 113 | + Returns: |
| 114 | + The score in dB, averaged over all channels. |
| 115 | +
|
| 116 | + Raises: |
| 117 | + Exception: If the wav files have different samplerate, channels, bit-depth |
| 118 | + or number of samples. |
| 119 | + """ |
| 120 | + ref_wav = wave.open(ref_filepath, "rb") |
| 121 | + target_wav = wave.open(target_filepath, "rb") |
| 122 | + |
| 123 | + # Check sampling rate |
| 124 | + if ref_wav.getframerate() != target_wav.getframerate(): |
| 125 | + raise ValueError( |
| 126 | + "Sampling rate of reference file and comparison file are different:" |
| 127 | + f" {ref_filepath} vs {target_filepath}" |
| 128 | + ) |
| 129 | + |
| 130 | + # Check number of channels |
| 131 | + if ref_wav.getnchannels() != target_wav.getnchannels(): |
| 132 | + raise ValueError( |
| 133 | + "Number of channels of reference file and comparison file are" |
| 134 | + f" different: {ref_filepath} vs {target_filepath}" |
| 135 | + ) |
| 136 | + |
| 137 | + # Check number of samples |
| 138 | + if ref_wav.getnframes() != target_wav.getnframes(): |
| 139 | + raise ValueError( |
| 140 | + "Number of samples of reference file and comparison file are different:" |
| 141 | + f" {ref_filepath} vs {target_filepath}" |
| 142 | + ) |
| 143 | + |
| 144 | + # Check bit depth |
| 145 | + if ref_wav.getsampwidth() != target_wav.getsampwidth(): |
| 146 | + raise ValueError( |
| 147 | + "Bit depth of reference file and comparison file are different:" |
| 148 | + f" {ref_filepath} vs {target_filepath}" |
| 149 | + ) |
| 150 | + |
| 151 | + # Open wav as a np array |
| 152 | + _, ref_data = wavfile.read(ref_filepath) |
| 153 | + _, target_data = wavfile.read(target_filepath) |
| 154 | + |
| 155 | + if metric == 'PSNR': |
| 156 | + scores_list = calc_per_channel_psnr_pcm( |
| 157 | + ref_data, target_data, ref_wav.getsampwidth() |
| 158 | + ) |
| 159 | + elif metric == 'LSD': |
| 160 | + scores_list = calc_per_channel_lsd_pcm(ref_data, target_data, |
| 161 | + ref_wav.getframerate()) |
| 162 | + else: |
| 163 | + return None |
| 164 | + |
| 165 | + return np.mean(scores_list) |
0 commit comments