Stabilizing value changes, thresholding for both value and time

I am trying to ignore spikes in a control value: that is, changes that don’t last long and are not small fluctuations.

I’m sure there must be a simpler way… but I can’t find it. And since this function is using LocalIn/Out, I don’t want to make it a Pseudo-UGen. So, before I go on and make a proper UGen, can anyone suggest a better way to go?


    // test signals
    // var in =,20000) 
    // *,1.midiratio);
    // var in = 100 * Env.perc(0.01,0.5).range(1,100).kr(;
    var in =,20000)
    * Env.perc(0.1,0.1).range(1,2).kr(;

    // a relative value thr
    var thr=(1.midiratio);
    var timeThr = 0.1;
    var local =;
    var stable = local[0], testStable = local[1];

    // a valid change needs to be both outside the stable range and inside the test range for long enough
    // check ranges	
    var inStableRange = in / stable, thr.reciprocal, thr);
    var inTestRange = in / testStable, thr.reciprocal, thr);
    // check durations
    var outsideLongEnough = > timeThr
    * (1 - inStableRange);
    var insideTestLongEnough = > timeThr
    * inTestRange;
    var validChange = outsideLongEnough * insideTestLongEnough;
    var out;

    // update testStable when exiting the testRange
    testStable =, 1 - inTestRange);
    stable =, validChange); [stable, testStable] );
    // allow fluctuations within stable range
    out =, inStableRange);

    [in, out].poll