;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; simple demo of FFTW
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

(libload "fftw/fftw")
(libload "audio/simple-audio")


;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

(de build-cmap (&optional (gain 0.1))
  (let* ((cmap (int-matrix 64))
	 (bump (lambda (x a b) 
		 (if (or (> x b) (< x a)) 
		     0 (* 0.5 (- 1 (cos (* (/ 6.2832 (- b a)) (- x a))))))))
	 (fb (lambda (x) (bump x 0 48)))
	 (fg (lambda (x) (bump x 16 64)))
	 (fr (lambda (x) (bump x 24 88))))
    (for (i 0 63) 
	 ;; (print (fr i) (fg i) (fb i))
	 (cmap i (alloccolor (fr i) (fg i) (fb i))))
    cmap))

(de show-cmap (x y cm z)
  (let ((m (matrix 64 1)))
    (for (i 0 63) (m i 0 i))
    (color-draw-matrix x y m 0 63 z z cm)))

;; this is a demo of the code
;; call (demo-spectrum "ronde3-susato.ogg")
;; To read MP3, you must have a version of sox that supports MP3.
(de demo-spectrum (f &optional (maxv 500) (fr 10000))
  (let* ((m (read-sound f fr))
	 (s (spectrogram m 512 256)))
    (when (not window) (new-window 0 0 800 550 "Spectrogram"))
    (when (not cmap) (setq cmap (build-cmap)))
    ;; (gray-draw-matrix 0 0 (transpose s) 0 maxv 1 1)
    (color-draw-matrix 0 0 (transpose s) 0 maxv 1 1 cmap)
    s))
