#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Control GStreamer filters in a pipeline using analog sticks of gamepads
# Copyright (c) 2010-12-22 Thomas Perl <thp.io>
#
# Tested with Sony DualShock 3 and Logitech RumblePad 2
#

import time
import sys

import gst
import pygame

from pygame import joystick
from pygame import event

if len(sys.argv) < 2:
    print >>sys.stderr, """
    Usage: python %s /path/to/song.mp3
""" % (sys.argv[0],)
    sys.exit(1)

pygame.init()
joystick.init()

if joystick.get_count() < 1:
    print >>sys.stderr, """
    PyGame (SDL) has not found any joysticks. Connect one!
"""
    sys.exit(2)

j = joystick.Joystick(0)
j.init()
print 'axes:', j.get_numaxes()

pipeline = gst.parse_launch("""
filesrc location="%s" ! decodebin ! audioconvert !
  ladspa-tap-pitch name=pitch !
  audiochebband name=bandpass !
  volume name=volume volume=1 !
audioconvert ! alsasink
""" % sys.argv[-1])

elements = dict((e.get_name(), e) for e in pipeline.elements())
pitch = elements['pitch']
bandpass = elements['bandpass']
volume = elements['volume']

pipeline.set_state(gst.STATE_PLAYING)

def axes_changed(old, new):
    diff = sum(abs(x-y) for x, y in zip(old, new))
    print diff
    return x > .5

old_axes = [0]*j.get_numaxes()

try:
    while True:
        ev = event.wait()
        if ev.type == pygame.JOYAXISMOTION and ev.axis < 4:
            axes = [float(j.get_axis(x)) for x in range(j.get_numaxes())]
            if axes_changed(axes, old_axes):
                print axes[:4]
                pitch.set_property('Semitone-Shift', axes[0]*12)
                volume.set_property('volume', 1+axes[1]*1)
                bandpass.set_property('lower-frequency', 500+axes[2]*500)
                bandpass.set_property('upper-frequency', 2000+axes[3]*2000)
                old_axes = axes
            else:
                print 'axes not changed'
except KeyboardInterrupt:
    sys.exit(0)

joystick.quit()


