########################################################################################################################################
########################################################################################################################################
## function to Smooth sound pressure level spectrum with 1/N-octave median filter
########################################################################################################################################
###########################################################################################
## created by Marcus Klaus, Swedish University of Agricultural Sciences (SLU), Umeå, Sweden
## contact: marcus.klaus@slu.se
## last update: 2026/04/30
###########################################################################################

## 1/N octave smoother of wave-frequency spectrum
## median filter with window size increasing with frequency
## wind size is 1/N octaves
## this function removes noise increasing at high frequency

## INPUTS: 
# ms...seewave::meanspec() output (sound spectrum with freq=frequency (Hz) and spec=amplitude or power)
# N...fractional-octave smoothing bandwidth (1/N octaves)
# k_min...minimum smoothing window size (number of frequency bins)

## OUTPUTS:
# freq...frequency (Hz)
# smooth...smoothed spectrum (original unit of spec)
######################################################################################

## load helper function to extract relative bandwidth for 1/N-octave (IEC-style)
rel_bw_from_N <- function(N) {
  2^(1/(2*N)) - 2^(-1/(2*N))
}


## load smoother function
smoothSpectrum <- function(ms, N = 3, k_min = 3) {
  stopifnot(ncol(ms) >= 2)
  freq <- as.numeric(ms[,1])   # Hz
  spec <- as.numeric(ms[,2])   # amplitude or power
  n    <- length(spec)
  
  df <- median(diff(freq))     # frequency resolution
  rel_bw <- rel_bw_from_N(N)  # exact fractional-octave relative bandwidth
  
  smoothed <- numeric(n)
  
  # make sure k_min is odd and at least 3
  if (k_min %% 2 == 0) k_min <- k_min + 1
  k_min <- max(3, k_min)
  
  for (k in seq_len(n)) {
    f <- max(freq[k], df)              # avoid zero at DC
    w <- 2 * floor((rel_bw * f) / df) + 1  # window length in bins
    w <- max(w, k_min)
    half <- w %/% 2
    i0 <- max(1, k - half)
    i1 <- min(n, k + half)
    smoothed[k] <- median(spec[i0:i1])
  }
  
  cbind(freq = freq, smooth = smoothed)
}
######################################################################################

