#!/usr/bin/python

# ----------------------------------------------------------------------------
#
#  Copyright (C) 2008-2022 Fons Adriaensen <fons@linuxaudio.org>
#    
#  This program is free software; you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation; either version 3 of the License, or
#  (at your option) any later version.
#
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
#  along with this program.  If not, see <http:#www.gnu.org/licenses/>.
#
# ----------------------------------------------------------------------------


import numpy as np
import matplotlib.pyplot as plt
from math import *
from time import sleep
from zita_jacktools.jacksignal import JackSignal


# ------- Frequency response measurement using impulse and FFT  ---------
#
# Make sure jnoisemeter is running, using
# input 1, and select the A, C or ITU filter.

# Create a JackSignal object and connect.
#
J = JackSignal("JackSignal")
if J.get_state() < 0:
    print ("Failed to create JackSignal -- is Jack running ?")
    exit(1)
J.create_input (0, "in")
J.create_input (1, "trig")

J.silence()

# Get Jack info.
#
name, fsamp, period = J.get_jack_info ()

# Parameters
#
SIZE = 512
LFFT = 8 * 1024
NBIN = LFFT // 2 + 1

Ain = np.zeros ((SIZE,), dtype = np.float32)
Fax = np.linspace (0, fsamp / 2, NBIN, endpoint = True)

# Run the test
#
J.silence ()
while True:
    J.set_input_data (0, Ain)
    J.trigger (1)
    J.wait ()
    
    # Process the result  
    # 
    Spec = np.fft.rfft (Ain, LFFT)
    print (Spec.shape, NBIN)
    
    # Display impulse and magnitude response.
    #
    fig = plt.figure (figsize=(8,6), facecolor='white')
    ax1 = fig.add_axes ([0.07, 0.04, 0.90, 0.44])
    ax1.set_ylim (-1.5, 1.5)
    ax1.plot (Ain, color='b', lw=1)
    ax1.grid ()
    ax2 = fig.add_axes ([0.07, 0.53, 0.90, 0.44])
    ax2.set_xlim (20, 20e3)
    ax2.set_ylim (-40, 40)
    ax2.set_xscale ('log')
    ax2.plot (Fax, 20 * np.log10 (np.abs (Spec) + 1e-10), color='b', lw=1)
    ax2.grid ()
    plt.show()
