peak limiting/audio compression formula needed
Two problems here: how to get a reliable estimate of the level, and how to compress the data.


Use robust statistics on the original (not peak-limited) data like median or quantiles instead of a running average to make your "typical level" detection robust to outliers.
$k \times \tanh(\frac{x}{k})$ works nice as a $C^\infty$ compression formula and it is actually what is happening in some audio circuits (using OTAs). To get adaptive compression that preserves the dynamics of the original signal and just remove transients, make k track the smoothed "average" level.





Blue: original signal
Green: 2 x median of the absolute value over a sliding window as a "typical level" detection
Red: tanh compression (formula given above with k equal to the level plotted in green)