#!/usr/bin/python

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


# Use JackSignal to test the 'dezippering' of JackGainctl.
# This will diplay the output signal on both a linear and
# dB scale. Zoom in to measure the times.


S = JackSignal("S")
if S.get_state() < 0:
    print ("Failed to create JackSignal -- is Jack running ?")
    exit(1)
S.create_output (0, "out-1")
S.create_input (0, "in-1")
S.silence()

G = JackGainctl (1, 'G')
S.connect_output (0, "G:in_0")
S.connect_input  (0, "G:out_0")


name, fsamp, period = S.get_jack_info ()
fsamp = 48000
Lout = fsamp // 10
Linp = fsamp
Aout = np.zeros ((Lout,), dtype = np.float32)
Ainp = np.zeros ((Linp,), dtype = np.float32)

T = np.linspace (0, 1, Linp, endpoint = False)

w = 2e3 * 2 * pi / fsamp
for i in range (Lout): Aout [i] = sin (w * i)

S.set_output_data (0, Aout, nloop = 11)
S.set_input_data (0, Ainp, nskip = period)
S.process()
sleep (0.1)

# Off to -20 dB, linear fade-in in 10 ms.
G.set_gain (-20.0)
sleep (0.15)

# -20 to 0 dB, this should take three 10 ms
# segments of +6 dB, plus one segment of +2 dB,
# for a total of 40 ms.
G.set_gain (0.0)
sleep (0.15)

# Mute, linear fade-out in 10 ms.
G.set_mute (1)
sleep (0.15)

# Unmute, linear fade-in in 10 ms.
G.set_mute (0)
sleep (0.15)

# 60 dB gain change, 100 ms.
G.set_gain (-60)
sleep (0.15)

# 90 dB gain change, 10 ms because
# target value is equivalent to 'off'.
G.set_gain (-150)
S.wait()


del S
del G

X1 = np.abs (Ainp)
X2 = 20 * np.log10 (X1 + 1e-20)

fig = plt.figure (figsize=(8,6), facecolor='white')
ax1 = fig.add_axes ([0.07, 0.54, 0.9, 0.44])
ax2 = fig.add_axes ([0.07, 0.05, 0.9, 0.44])
ax1.grid ()
ax2.grid ()
ax1.set_ylim (0, 1.2)
ax2.set_ylim (-120, 10)
ax1.plot (T, X1, color='g', lw=1)
ax2.plot (T, X2, color='b', lw=1)
plt.show()
