SuperAPI AI Directory

m4l-javascript

Coding & development

View repository

Updated 10-16 03:41

About this skill

JavaScript inside Max for Live

1. Pick the right object: js vs v8 vs jsui vs v8ui

Object Engine Language UI drawing? Recommend for
js SpiderMonkey (legacy) ES5 No Maintaining legacy patches only
v8 V8 (Max 8.2+) ES6+ No Default for new code. ES6, classes, async
jsui SpiderMonkey (legacy) ES5 sketch + mgraphics Legacy custom UI
v8ui V8 (Max 9+) ES6+ sketch + mgraphics Default for new custom UI

All four expose LiveAPI identically inside M4L. Pick by language tier.

No browser APIs: no window, no document, no fetch, no setTimeout/setInterval. Use Task for scheduling.

v8 advantages:

  • ES6+ syntax: let, const, arrow =>, template literals, class, for...of, optional chaining ?., destructuring.
  • Promise, async/await, modules.
  • console.log works (prints to Max window). In js you must use post().
  • Symbol, BigInt, modern Array/Object methods.

js pitfalls (silently fails on):

  • let, const, class, arrow functions, template strings
  • Promise, async/await
  • for...of, destructuring, default parameters
  • Optional chaining

2. Required boilerplate

Top-level globals (set in global code, not inside a function):

inlets  = 2;
outlets = 3;
autowatch = 1;   // auto-recompile when the .js file changes

autowatch = 1 is essential during development — otherwise edits to the .js don't take effect until you re-instantiate the object.

Standard handlers

function bang()       { /* responds to bang */ }
function msg_int(n)   { /* responds to int */ }
function msg_float(n) { /* responds to float; if only one numeric handler is defined the other type auto-converts */ }
function list()       { /* responds to messages starting with a number; use 'arguments' for variadic */ }
function anything()   { /* catch-all; check global 'messagename' to see what came in */ }
function loadbang()   { /* fires when the patcher file loads (NOT on object instantiation) */ }

Output

outlet(0, "value", v);
outlet(1, x, y, z);

Logging

post("hello", n, "\n");   // Max window
error("oh no\n");          // Max window in red
cpost("system console\n"); // system console

// v8 only:
console.log("v8 only");    // also goes to Max window

pattr integration

function getvalueof()  { return myState; }
function setvalueof(v) { myState = v; }
function save() { embedmessage("restore", state1, state2); }

jsthis (implicit) globals

  • inlet — which inlet fired this message
  • inlets, outlets — current configuration
  • jsarguments — arguments array; [0] is filename, [1]… are typed args
  • messagename — which message triggered the current handler
  • patcher, box, maxclass — host references
  • Max — the Max global controller

Helpers:

  • outlet(n, ...)
  • arrayfromargs(messagename, arguments) — convert variadic to Array
  • declareattribute(name, getter, setter, persist) — pattr-compatible attribute
  • embedmessage("methodname", ...) — save methodcall in patcher
  • setinletassist(i, "txt"), setoutletassist(i, "txt") — assist labels
  • messnamed("targetSymbol", ...args) — send to a global receive

Mark helper functions private (un-callable from Max messages):

function helper() { ... }
helper.local = 1;

3. The LiveAPI class

Only defined inside .amxd. In standalone Max, new LiveAPI(...) throws.

Constructor (all args optional)

var api = new LiveAPI(callback, "path");
var api = new LiveAPI("path");
var api = new LiveAPI(callback);
var api = new LiveAPI(callback, idString);

Properties

Property Type Notes
id number Dynamic — session-only, don't persist
path string Quoted canonical path
unquotedpath string Same without quotes
type string Class name at current path
mode 0/1 0 follows the object; 1 tracks UI position
property string Assigning starts observation; callback fires on change
proptype string Type of observed property
children array Child names
info string Multi-line debug dump
valid bool True when path resolves to a real object

Methods

Method Purpose
goto(path) Navigate; callback gets id or 0
get(prop) Read property (returns Array)
getstring(prop) Read as String
set(prop, value) Write
call(fn, ...args) Invoke LOM function
getcount(child) Number of named children
getchildren() Names of immediate children
getchildids() Ids of immediate children
info Property — multi-line dump (id, type, children, ...)

Observation pattern

function callback(args) {
    // args[0] = property name (or "id" when navigating)
    // args[1...] = values
    if (args[0] == "id") {
        post("path resolved to id", args[1], "\n");
    } else if (args[0] == "name") {
        post("name changed to", args[1], "\n");
    }
}

function bang() {
    var t = new LiveAPI(callback, "live_set view selected_track");
    t.property = "name";   // starts observing
}

For list-valued properties (like devices), args looks like:

["devices", "id", 17, "id", 24, "id", 31]

…each id prefixed with the literal symbol "id". Loop for (var i = 2; i < args.length; i += 2).

Init timing — THE rule

Never instantiate new LiveAPI(...) in global code or in loadbang().

The Live API is not yet bound. Always drive construction from live.thisdevice's left outlet wired into your JS object's inlet:

[live.thisdevice]
       |
       v
[js mything.js]

In the JS:

function bang() {
    // bang comes from live.thisdevice — safe to create LiveAPI now
    this.api = new LiveAPI(callback, "this_device canonical_parent");
}

Threading constraint

"The LiveAPI object cannot be created or used in the high-priority thread."

When a message can arrive at high priority (e.g., from a metro with Overdrive on), insert [deferlow] between the source and the JS object. Within JS, defer Live mutations via Task.schedule(0).

4. The Task class — replacement for setTimeout

var t = new Task(myFn, this, arg1, arg2);  // function, this-context, args
t.schedule(500);   // one-shot after 500 ms
t.repeat(8, 100);  // 8 iterations, 100 ms apart; negative count = forever
t.execute();       // run now (same as calling myFn(arg1, arg2))
t.cancel();        // stop pending; safe to call from inside the task
t.interval = 250;  // ms between repeats; default 500
// read-only: t.running, t.iterations

Self-modifying from inside the task body (works in js; in strict-mode v8 use a closure):

function myFn() {
    var intv = arguments.callee.task.interval;
    arguments.callee.task.interval = intv * 1.1;  // gently slow down
}

Tasks run on the low-priority scheduler — perfect for deferred API work and breaking out of "Changes cannot be triggered by notifications" errors. Not sample-accurate.

5. Threading model

Max with Overdrive has two threads:

  • High-priority scheduler — timing-sensitive (metros, MIDI clock)
  • Low-priority — UI, file I/O, heavy computation

"By default, the js object executes all Javascript code in the low-priority thread. If it finds itself running in the high-priority thread, it will defer execution of whatever it was supposed to do to the low-priority thread."

Practical:

  • LiveAPI calls always low-priority (enforced).
  • Audio-rate processing in JS is impossible — defer to gen~ / MSP.
  • Sample-accurate triggers: use gen~/codebox, not JS.
  • For UI redraws, throttle with Task.repeat(-1, 33) (~30 fps) + mgraphics.redraw().

6. v8ui / jsui — custom UI drawing

Two drawing APIs available; pick mgraphics for modern UIs.

Init (global code)

mgraphics.init();
mgraphics.relative_coords = 1;  // 1 = world (-1..+1), 0 = pixel
mgraphics.autofill = 0;

paint() callback (auto-invoked on refresh)

function paint() {
    with (mgraphics) {
        set_source_rgba(0.2, 0.2, 0.2, 1);
        set_line_width(0.03);
        move_to(-1, -1);
        line_to(1, 1);
        stroke();
    }
}

Primitives: move_to, line_to, curve_to, rectangle, arc, fill, stroke, set_source_rgb(a), set_font_size, text_path, translate, rotate, scale.

Trigger redraw: mgraphics.redraw() (or refresh() for sketch).

Event handlers (on the UI object)

function onclick(x, y, button, modifiers, shift, capslock, alt) { ... }
function ondblclick(x, y, ...) { ... }
function ondrag(x, y, button, modifiers, shift, capslock, alt) { ... }
function onidle(x, y, ...) { ... }
function onidleout(x, y, ...) { ... }
function onresize(w, h) { ... }

Mouse coords are in screen space (pixels), not your relative coords.

sketch alternative

Older OpenGL-style API with origin at center, (+1 top, -1 bottom):

function bang() {
    sketch.glclear();
    sketch.glcolor(0.5, 0.7, 0.3);
    sketch.moveto(0.25, -0.25);
    sketch.circle(0.3);
    refresh();
}

sketch.screentoworld(x,y), sketch.worldtoscreen(x,y,z) convert coordinates.

Critical gotcha

"Mouse position and object redrawing will only be reported correctly in the jsui object if the patching and Presentation mode sizes of the object are the same."

If they differ, hit-testing drifts. Either keep them equal, or use a live.* object for the actual control and v8ui only for decoration.

Custom UI vs live.* boxes

  • For a mappable parameter → use live.dial. v8ui can be a parameter (parameter_enable + parameter_mappable) but it's a single param.
  • For many user controls → assemble live.* boxes; cheaper, themed, native automation.
  • For a custom visualization (envelope editor, XY pad, scope, mini sequencer) → v8ui.

7. Buffer access

From Buffer constructor (JS)

var b = new Buffer("snd");  // scripting name of the buffer~ object
b.channelcount();
b.framecount();
b.length();            // ms
b.peek(channel, frame, count);          // 1-based channel, 0-based frame; returns array
b.poke(channel, frame, sampleArray);    // write
b.send("normalize", 0.9);               // pass any message to the buffer~
b.freepeer();                            // release native memory

Ad-hoc messages

messnamed("snd", "read", "kick.wav");

8. JSON / file I/O

In v8: use the File and Folder globals. require/import work with limits.

var f = new File("config.json", "read");
if (f.isopen) {
    var s = f.readstring(f.eof);
    f.close();
    var cfg = JSON.parse(s);
}

In js: same File API but no require/import.

9. Common LLM mistakes

  1. new LiveAPI(...) in global code — Live API not ready. Always wait for live.thisdevice bang.
  2. Forgetting autowatch = 1 while iterating — old code keeps running after save.
  3. console.log in js — undefined. Use post(). (In v8, both work.)
  4. ES6 in js — silent parse failures on let/class/=>/template strings.
  5. setTimeout/setInterval — don't exist. Use Task.
  6. Treating observer args as the value — it's [propertyName, ...values], not the value alone.
  7. Race: querying LiveAPI right after goto — id updates async; observe the callback or Task.schedule(0).
  8. Globals not surviving script reload — when autowatch reloads, top-level vars reset. Persist via pattr (getvalueof/setvalueof) or Dict.
  9. High-priority entry into LiveAPI — insert [deferlow] upstream of the JS object.
  10. Drawing in jsui/v8ui with patching size ≠ presentation size — hit-testing skews.
  11. Persisting ids — they're session-scoped. Re-resolve from a path at load.
  12. Returning from observer with a set — fails with "Changes cannot be triggered by notifications". Wrap in Task.schedule(0).

10. Performance

  • JS runs on the low-priority thread. Even v8's JIT can't reach DSP-vector budgets — never per-sample work in JS.
  • For UI: throttle redraws via Task.repeat(-1, 33) (~30 fps).
  • LiveAPI I/O = JS; numeric work = MSP/gen~; sample-accurate DSP = gen~ only.

Threading priority cheatsheet:

Concern Where
LiveAPI JS / low-priority
UI redraw JS / low-priority
Tempo-locked sequencing metro (high) → deferlow → JS, OR gen~
DSP gen~ / MSP only

11. Mini boilerplate templates

LiveAPI: read a property once after init

autowatch = 1;
outlets = 1;

function bang() {
    var d = new LiveAPI(null, "this_device");
    outlet(0, "name", d.get("name")[0]);
}

LiveAPI: observe selected track name forever

autowatch = 1;
outlets = 1;

function bang() {
    this.api = new LiveAPI(function(args) {
        if (args[0] == "name") outlet(0, "track", args[1]);
    }, "live_set view selected_track");
    this.api.property = "name";
}

LiveAPI: set a parameter safely (defers when needed)

autowatch = 1;

function bang() {
    this.dev = new LiveAPI(null, "this_device");
}

function setvol(v) {
    var t = new Task(function() {
        this.dev.set("value", v);   // never throws "Changes cannot be triggered by notifications"
    }, this);
    t.schedule(0);
}

v8ui: simple custom XY pad output

inlets = 0;
outlets = 2;
autowatch = 1;
mgraphics.init();
mgraphics.relative_coords = 0;
mgraphics.autofill = 0;

var posX = 0.5, posY = 0.5;

function paint() {
    var sz = box.rect;
    var w = sz[2] - sz[0], h = sz[3] - sz[1];
    with (mgraphics) {
        set_source_rgba(0.15, 0.15, 0.15, 1); rectangle(0, 0, w, h); fill();
        set_source_rgba(0.9, 0.5, 0.2, 1);
        arc(posX * w, posY * h, 6, 0, 2 * Math.PI); fill();
    }
}

function ondrag(x, y) {
    var sz = box.rect;
    var w = sz[2] - sz[0], h = sz[3] - sz[1];
    posX = Math.max(0, Math.min(1, x / w));
    posY = Math.max(0, Math.min(1, y / h));
    outlet(0, posX);
    outlet(1, posY);
    mgraphics.redraw();
}