
#############################################################################################################
#############################################################################################################
## function to find the window in a .wav file with lowest variability in amplitude
#############################################################################################################
#############################################################################################################
###########################################################################################
## created by Marcus Klaus, Swedish University of Agricultural Sciences (SLU), Umeå, Sweden
## contact: marcus.klaus@slu.se
## last update: 2026/04/30
###########################################################################################

## River flow is approximately stationary over short intervals, while impacts/handling noise are transient nonstationary events.
## This function selects the window with the lowest deviation from stationary noise.

## INPUTS:
# wav_file... wave file
# window_sec... length of window segments (s)
# hop_sec... step length (s) between each window
# frame_ms... length of chunks each window is split into (ms)
# channel... stereo wave-file channel (Left="L", Right="R")
# buffertime... time that wave file is cropped at start and end to avoid recording handling noise

## OUTPUTS:
# start_sec.. start time of best window (with minimal transient nonstationary events)
# end_sec.. end time of best window 
# score... SD/mean RMS value for best window
# waveform... wave of best window
# sample_rate... sampling rate (Hz)
# all_scores... dataframe with start_sec and score for all candidate windows
###########################################################################################


selectMostStationaryWindow <- function(
    wav_file,
    window_sec = 5,
    hop_sec = 0.5,
    frame_ms = 50,
    channel = "L",
    buffertime = 2
) {
  
  library(tuneR)
  
  wav <- readWave(wav_file)
  
  # Extract channel
  if (wav@stereo) {
    signal <- if (channel == "L") wav@left else wav@right
  } else {
    signal <- wav@left
  }
  
  signal <- as.numeric(signal)
  
  # Normalize signal
  signal <- signal / max(abs(signal))
  
  fs <- wav@samp.rate
  
  # Window sizes
  win_n <- round(window_sec * fs)
  hop_n <- round(hop_sec * fs)
  
  frame_n <- round(frame_ms / 1000 * fs)
  
  buffer_sec <- buffertime
  
  buffer_n <- round(buffer_sec * fs)
  
  starts <- seq(
    1 + buffer_n,
    length(signal) - win_n - buffer_n,
    by = hop_n
  )
  
  scores <- numeric(length(starts))
  
  rms <- function(x) sqrt(mean(x^2))
  
  for (i in seq_along(starts)) {
    
    idx <- starts[i]:(starts[i] + win_n - 1)
    x <- signal[idx]
    
    # Short-term RMS
    frame_starts <- seq(1, length(x) - frame_n, by = frame_n)
    
    frame_rms <- sapply(frame_starts, function(s) {
      rms(x[s:(s + frame_n - 1)])
    })
    
    # Coefficient of variation (dimensionless)
    score <- sd(frame_rms) / mean(frame_rms)
    
    scores[i] <- score
  }
  
  best_i <- which.min(scores)
  
  best_start <- starts[best_i]
  best_end <- best_start + win_n - 1
  
  best_signal <- signal[best_start:best_end]
  
  start_sec <- best_start / fs
  end_sec <- best_end / fs
  
  
  return(list(
    start_sec = start_sec,
    end_sec = end_sec,
    score = scores[best_i],
    waveform = best_signal,
    sample_rate = fs,
    all_scores = data.frame(
      start_sec = starts / fs,
      score = scores
    )
  ))
}

