Skip to content

Instantly share code, notes, and snippets.

@timowest
Created January 28, 2013 07:25

Revisions

  1. timowest created this gist Jan 28, 2013.
    81 changes: 81 additions & 0 deletions gistfile1.clj
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,81 @@
    (ns synth
    (include "cmath"
    "lv2/lv2plug.in/ns/lv2core/lv2.h"))

    (defstruct Synth
    (sample-rate double)
    (phase float)
    (freq float*)
    (output float*))

    (defn ^void* instantiate
    [^LV2_Descriptor.const* descriptor
    ^double rate
    ^char.const* bundle-path
    ^LV2_Feature.const*.const* features]
    (let [self (new Synth)]
    (set! (.sample-rate self) rate)
    self))

    (defn connect-port
    [^LV2_Handle instance ^uint port ^void* data]
    (let [self (cast Synth* instance)]
    (match port
    (uint 0) (set! (.freq self) (cast float* data))
    (uint 1) (set! (.output self) (cast float* data)))))

    (defn activate
    [^LV2_Handle instance]
    (let [self (cast Synth* instance)]
    (set! (.phase self) (float 0.0))))

    (defn run
    [^LV2_Handle instance ^uint32_t n-samples]
    (let [self (cast Synth* instance)
    PI (float 3.1415)
    volume (float 0.3)
    freq (pref (.freq self))
    output (.output self)
    samples-per-cycle (/ (float (.sample-rate self)) freq)
    phase-increment (/ (float 1.0) samples-per-cycle)]
    (dotimes [pos (long n-samples)]
    (pset! output pos (* (sin (* (.phase self) (float 2.0) PI)) volume))
    (set! (.phase self) (+ (.phase self) phase-increment))
    (if (> (.phase self) (float 1.0))
    (set! (.phase self) (float 0.0))))))

    (defn deactivate
    [^LV2_Handle instance])

    (defn cleanup
    [^LV2_Handle instance]
    (delete (cast Synth* instance)))

    (defn ^void.const* extension-data
    [^char.const* uri]
    nil)

    (extern "C"
    "
    /** The LV2_Descriptor for this plugin. */
    static const LV2_Descriptor descriptor = {
    \"http://lv2plug.in/plugins/eg-synth\",
    instantiate,
    connect_port,
    activate,
    run,
    deactivate,
    cleanup,
    extension_data
    };
    LV2_SYMBOL_EXPORT
    const LV2_Descriptor*
    lv2_descriptor(uint32_t index) {
    switch (index) {
    case 0: return &descriptor;
    default: return 0;
    }
    }")