#!/usr/bin/env python

"""
Simple script which plays a wave file through a VST effect,
randomizing parameters.
"""

import time
import nosuch.vstutil
import sys
import random
from nosuch.vstutil import *

# Utility functions

def vstinfo(v1,doparams=0):
	print "VST: ",v1.name()
	print "        product = ",v1.product_string()
	print "        Is VST2 = ",v1.is_vst2()
	print "        Is synth = ",v1.is_synth()
	print "        num_programs = ",v1.num_programs()
	print "        num_params = ",v1.num_params()
	print "        num_inputs = ",v1.num_inputs()
	print "        num_outputs = ",v1.num_outputs()
	print "        can_receive_midi = ",v1.can_receive_midi()

def vstrandparam(p):
	for i in range(p.num_params()):
		f = random.random()
		p.set_param(i,f)

# Main script

if len(sys.argv) < 4:
	print "Usage: demo1 {vstdir} {effectdll} {wavfile} [{totaltime}]"
	sys.exit(1)

if len(sys.argv) > 4:
	totaldur = float(sys.argv[4])
else:
	totaldur = 60.0

vstdir = sys.argv[1]
effectdll = sys.argv[2]
wavfile = sys.argv[3]

# Instantiate the VST plugin
effect = VstPlugin(dll=vstdir+"\\"+effectdll)
vstinfo(effect,doparams=0)

# Start the audio device
audio = PaAudioDevice()
audio.open()
audio.start()

sound = AudioSnippet(filename=wavfile)
print("wave file=",wavfile,"   duration=",sound.duration())

loop = AudioLoop(sound,loops=-1)  # -1 means loop forever

# Connect the output of the loop to the input of the effect
effect.setinput(loop)

# Connect the output of the effect to the audio device
audio.attach(effect)

print "Now looping wavfile ",wavfile," and randomizing parameters every second for ",totaldur," seconds"

endtime = totaldur + time.time()
while time.time() < endtime:
	vstrandparam(effect)
	time.sleep(1.0)

# Stop the audio device
audio.stop()
audio.close()

sys.exit(0)
