#!/usr/bin/env python

"""
Simple script which plays a vsti synth 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} {synthdll} {effectdll} [{note-pitch} {note-seconds} {totaltime}]"
	print ""
	print "Set midipitch to 0 to play random notes"
	sys.exit(1)

if len(sys.argv) > 4:
	notepitch = int(sys.argv[4])
else:
	notepitch = 64

if len(sys.argv) > 5:
	notelength = float(sys.argv[5])
else:
	notelength = 0.3

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

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

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

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

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

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

if notepitch < 1:
	print "Now sending random notes and randomizing parameters every ",notelength," seconds for ",totaldur," seconds"
else:
	print "Now sending note ",notepitch," and randomizing parameters every ",notelength," seconds for ",totaldur," seconds"

# Play notes and randomize parameters

endtime = totaldur + time.time()
while time.time() < endtime:
	if notepitch < 1:
		pt = int(random.random() * 128) % 128
	else:
		pt = notepitch

	# Randomize the parameters of both VST plugins
	vstrandparam(synth)
	vstrandparam(effect)

	# Send a MIDI note-on and note-off to the VST synth
	synth.send_midi(1,pt,8000,80)
	time.sleep(notelength)
	synth.send_midi(1,pt,8000,0)

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

sys.exit(0)
