;nyquist plug-in
;version 1
;type process
;name "Target Fade..."
;action "Applying (possibly unreasonable) fade..."
;info "By Steve Daulton\nApplies a linear fade from the specified initial to levels.\n THIS PLUG-IN IS FOR DEMONSTRATION PURPOSES ONLY."

;; TargetFadeDemo.ny by Steve Daulton. Sept 2012
;; Released under terms of the GNU General Public License version 2:
;; http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
;; version 1.0 May 2011
;; This plug-in demonstrates that fading from/to a target level is not
;; a practical proposition.


;control ipeak "Initial peak level (dB)" real "" 0.0 -100 0
;control fpeak "Final peak level (dB)" real "" -6.0 -100 0

(setq ipeak (db-to-linear ipeak))
(setq fpeak (db-to-linear fpeak))

(defun target-fade (sig)
  (let ((ival (abs (snd-fetch (snd-copy sig))))
        (fval (abs 
          (abs-env 
            (sref (snd-copy sig) (/ (1- len) *sound-srate*))))))
    (cond 
      ((= ival 0)
        "Error.\nInitial level is zero and cannot be faded.")
      ((= fval 0)
        "Error.\nFinal level is zero and cannot be faded.")
      (T (mult sig
           (control-srate-abs *sound-srate*
             (pwlv (/ ipeak ival) 1 (/ fpeak fval))))))))

(multichan-expand #'target-fade s)