#!/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 sys
import numpy as np
from time import sleep
from math import *
from zita_jacktools.jacksignal import JackSignal
from zita_audiotools.audiofile import write_audio
sys.path.append ('..')
from utils.logsweep import genlogsweep


# ------- Impulse response measurement using log sweep  ---------
#
# Make sure zita-rev1 is running, output full wet.


# 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_output (0, "out")
J.create_input (0, "in.L")
J.create_input (1, "in.R")
J.silence()
J.connect_output (0, "zita-rev1:in.L")
J.connect_output (0, "zita-rev1:in.R")
J.connect_input (0, "zita-rev1:out.L")
J.connect_input (1, "zita-rev1:out.R")


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

# Parameters.
#
fmin = 20.0
fmax = 23e3
amp = 0.1
tfade1 = 0.01
tsweep = 1.0
tfade2 = 0.01
timpulse = 3.0

# Generate sweep.
#
Afwd, Ainv, pcorr = genlogsweep (amp, fmin, fmax, fsamp, tfade1, tsweep, tfade2)

# Create input buffer.
#
k = int (fsamp * timpulse + Afwd.shape [0] + 0.5)
Ainp = np.empty ([k,2], dtype = np.float32)

# Connect buffer to ports.
#
J.set_output_data (0, Afwd)
J.set_input_data (0, Ainp [:,0])
J.set_input_data (1, Ainp [:,1])

# Run the test
#
J.process()
J.wait ()
del J

# Process and store result
#
AL = np.convolve (Ainp [:,0], Ainv, mode = 'valid')
AR = np.convolve (Ainp [:,1], Ainv, mode = 'valid')
write_audio (AL, "imp-L.wav")
write_audio (AR, "imp-R.wav")

