You are on page 1of 2008

Unofficial Max/MSP 6 documentation

in PDF format
Compiled on June, 2012 from the official documentation
Max Reference
abs
Calculate an absolute value

Description
Outputs the absolute (non-negative) value of any given number. Floats will be output only if the argument to abs is a float.

Arguments
Name Units Type Opt Description
format number opt Float argument forces a float output.

Messages
int input [int] The absolute (non-negative) value of the input is sent out the output.
float input [float] Converted to int, unless abs has a float argument.

Information for box attributes common to all objects

Output
float: Floats are output only if there is an argument with a decimal point.
int: The absolute value of the input.

Examples

Output is non-negative........Used here to invert input

See Also
Name Description
expr Evaluate a mathematical expression
absolutepath
Convert a file name to an absolute path

Description
Converts a file name or path to an absolute path. If the file is not found, the symbol notfound is output.

Arguments
None.

Messages
anything pathname [symbol] A file name or path as a symbol. Input pathnames can contain slashes, colons, or
backslashes as separators.
types filetypes [list] The types message followed by a list of four-letter, filetype codes will designate
the types of files which absolutepath can recognize.

Information for box attributes common to all objects

Output
any symbol: If the incoming file name or path is found, the output is an absolute path. The output pathnames contain slash
separators.

Absolute pathnames look like this:

"C:/Max Folder/extras/mystuff/mypatch.pat"

Examples

See Also
Name Description
conformpath Convert file paths styles
opendialog Open a dialog to ask for a file or folder
relativepath Convert an absolute to a relative path
savedialog Open a dialog asking for a filename
strippath Separate filename from a full pathname
File Preferences File Preferences
accum
Store, add to, and multiply a number

Description
Stores a value (int or float), then adds or multiplies into it. If the argument is an integer, the multiplication is done in floating-
point then converted to integer.

Arguments
Name Units Type Opt Description
initial int or float opt Sets the initial value stored in accum. An argument with a decimal point causes
the value to be stored as a float.

Messages
bang In left inlet: Outputs the value currently stored in accum.
int input [int] In left inlet: Replaces the value stored in accum, and sends the new value out the
outlet.
(inlet1) input [int] In middle inlet: The number is added to the stored value, without triggering
output.
(inlet2) input [float] In right inlet: The stored value is multiplied by the input, without triggering
output.
float input [float] In left and middle inlet: Converted to int, unless accum has a float argument.

In right inlet: Multiplication is done with floats, even if the value is stored as an
int.
set input [int] In left inlet: The word set, followed by a number, sets the stored value to that
number, without triggering output.

Information for box attributes common to all objects

Output
float: Floats are output only if there is an argument with a decimal point.
int: The value currently held by accum.

Examples

Add to and/or multiply a stored value....... Used here to increment by different amounts

See Also
Name Description
counter Keep count based on bang messages
float Store a decimal number
int Store an integer value
acos
Arc-cosine function

Description
Use the acos object to calculate and output the arc-cosine of any given number.

Arguments
Name Units Type Opt Description
initial-value float or int opt Sets the initial value for the arc-cosine function.

Messages
bang Calculates the arc-cosine of the number currently stored. If there is no argument,
acos initially holds 0.
int input [int] Input to the arc-cosine function
float input [float] Input to the arc-cosine function

Information for box attributes common to all objects

Output
float: The arc-cosine of the input.
int: The arc-cosine of the input.

Examples

See Also
Name Description
acosh Hyperbolic arc-cosine function
cos Cosine function
cosh Hyperbolic cosine function
acosh
Hyperbolic arc-cosine function

Description
Use the acosh object to calculate and output the hyperbolic arc-cosine of any given number.

Arguments
Name Units Type Opt Description
initial-value float or int opt Sets the initial value for the hyperbolic arc-cosine function.

Messages
bang Calculates a hyperbolic arc-cosine of the number currently stored. If there is no
argument, acosh initially holds 0.
int input [int] Input to the hyperbolic arc-cosine function
float input [float] Input to the hyperbolic arc-cosine function

Information for box attributes common to all objects

Output
float: The hyperbolic arc-cosine of the input.
int: The hyperbolic arc-cosine of the input.

Examples

See Also
Name Description
acos Arc-cosine function
cos Cosine function
cosh Hyperbolic cosine function
active
Send 1 when patcher window is active, 0 when inactive

Description
active will output a 1 when the Patcher window becomes active (i.e., it is the front-most window and its title bar is highlighted),
and output a 0 when the Patcher window becomes inactive. You can use this to change the user interface of your window. For
example, messages from the key object can be turned off when the window is made inactive.

Arguments
None.

Messages
int internal-messaging [int] There are no inlets. Output is triggered automatically when the patcher window is
activated or deactivated.

Information for box attributes common to all objects

Output
int: When the patcher window that contains active is activated, active sends out 1. When the window is made inactive, active
sends out 0.

Examples

Turn on a process or open a gate when the window is made active

See Also
Name Description
closebang Send a bang on close
loadbang Send a bang when a patcher is loaded
loadmess Send a message when a patch is loaded
anal
Make a histogram of number pairs

Description
Reports how many times a number pair has been received.

Arguments
Name Units Type Opt Description
input-limit int opt Sets a maximum limit for the values that can be input into anal. Input values are
clipped between zero and this value. The default value, when no argument is
present, is 128. By supplying an argument, you can change the maximum input
value up to a maximum of 16384.

Messages
int input [int] Reports how many times this number and the previously received number have
occurred in immediate succession. (The first time a number is received, there has
been no previous number, so nothing happens.)
clear Erases the memory of the anal object entirely, but retains the most recently
received number to use as the next "previous" value.
reset Erases the most recently received number from the memory of the anal object.
The next number to be received gets stored in its place, to serve as the next
"previous" value (but nothing else happens).

Information for box attributes common to all objects

Output
list: The first two numbers in the list are the two most recently received numbers, and the third number shows how many times
that particular succession of two numbers has been received. This list of three numbers is designed to be used as input to the
prob object, to create a probability matrix of transitions from one number to another (known as a first-order Markov chain).

Examples

Keep track of number pairs and their relative frequency of occurrence pass the information to prob to generate similar
transitions

See Also
Name Description
histo Create a histogram of numbers received
prob Create a weighted transition table
append
Append arguments to the end of a message

Description
append will add arguments to the end of any message you input.

Arguments
Name Units Type Opt Description
appended- anything opt Sets message that will be appended
message

Messages
bang bang will cause append to output the message which was most recently stored in
memory (bang is particularly useful for triggering output following the set
message).
int input [int] The incoming integer value(s) will be appended by the message stored in append,
preceded by a space, and the combined message is sent out the outlet.
float input [float] The incoming floating-point value(s) will be appended by the message stored in
append, preceded by a space, and the combined message is sent out the outlet.
list input [list] The incoming list values will be appended by the message stored in append,
preceded by a space, and the combined message is sent out the outlet.
anything input-message [list] The incoming message or list will be appended by the message stored in append,
preceded by a space, and the combined message is sent out the outlet.
set set [list] The word set, followed by any message, will replace the message stored in
append, without triggering output.

Information for box attributes common to all objects

Output
anything: The message received in the inlet is combined with the message stored in append, and then sent out the outlet.

Examples

Symbols can be combined into meaningful messages with append

See Also
Name Description
combine Combine multiple items into a single symbol
join Combine items into a list
pack Create a list
pak Output a list when any element changes
prepend Add a message in front of input
zl Process lists in many ways
asin
Arc-sine function

Description
Use the asin object to calculate and output the arc-sine of any given number.

Arguments
Name Units Type Opt Description
initial-value float or int opt Sets the initial value for the arc-sine function.

Messages
bang Calculates the arc-sine of the number currently stored. If there is no argument,
asin initially holds 0.
int input [int] Input to the arc-sine function
float input [float] Input to the arc-sine function

Information for box attributes common to all objects

Output
float: The arc-sine of the input.
int: The arc-sine of the input.

Examples

See Also
Name Description
asinh Hyperbolic arc-sine function
sin Sine function
sinh Hyperbolic sine function
asinh
Hyperbolic arc-sine function

Description
Use the asinh object to calculate and output the hyperbolic arc-sine of any given number.

Arguments
Name Units Type Opt Description
initial-value float or int opt Sets the initial value for the hyperbolic arc-sine function.

Messages
bang Calculates the hyperbolic arc-sine of the number currently stored. If there is no
argument, asin initially holds 0.
int input [int] Input to the hyperbolic arc-cosine function
float input [float] Input to the hyperbolic arc-cosine function

Information for box attributes common to all objects

Output
float: The hyperbolic arc-sine of the input.
int: The hyperbolic arc-sine of the input.

Examples

See Also
Name Description
asin Arc-sine function
sin Sine function
sinh Hyperbolic sine function
atan
Arc-tangent function

Description
Use the atan object to calculate and output the arc-tangent of any given number.

Arguments
Name Units Type Opt Description
initial-value float or int opt Sets the initial value for the arc-tangent function.

Messages
bang Calculates the arc-tangent of the number currently stored. If there is no argument,
atan initially holds 0.
int input [int] Input to the arc-tangent function
float input [float] Input to the arc-tangent function

Information for box attributes common to all objects

Output
float: The arc-tangent of the input.
int: The arc-tangent of the input.

Examples

See Also
Name Description
atan2 Two-variable arc-tangent function
atanh Hyperbolic arc-tangent function
tan Tangent function
tanh Hyperbolic tangent function
atan2
Two-variable arc-tangent function

Description
Use the atan2 object to calculate and output the arc-tangent of any two given numbers where the left input is the y value and the
right input is the x value.

Arguments
Name Units Type Opt Description
Two ints may be used to set the initial value for the arc-tangent function.

Messages
bang Calculates the arc-tangent of the numbers currently stored. If there are no
arguments, atan2 initially holds 0 for both input values.
int y-value [int] In left input: y value input to an arc-tangent function
(inlet1) x-value [int] In right input: x value input to an arc-tangent function
float y-value [float] In left input: y value input to an arc-tangent function
(inlet1) x-value [float] In right input: x value input to an arc-tangent function

Information for box attributes common to all objects

Output
float: The arc-tangent of the input values (i.e. Arc-tangent (y/x)).
int: The arc-tangent of the input values (i.e. Arc-tangent (y/x)).

Examples

See Also
Name Description
atan Arc-tangent function
atanh Hyperbolic arc-tangent function
tan Tangent function
atanh
Hyperbolic arc-tangent function

Description
Use the atanh object to calculate and output the hyperbolic arc-tangent of any given number.

Arguments
Name Units Type Opt Description
initial-value float or int opt Sets the initial value for the hyperbolic arc-tangent function.

Messages
bang Calculates the hyperbolic arc-tangent of the number currently stored. If there is no
argument, atanh initially holds 0.
int input [int] Input to the hyperbolic arc-tangent function
float input [float] Input to the hyperbolic arc-tangent function

Information for box attributes common to all objects

Output
float: The hyperbolic arc-tangent of the input.
int: The hyperbolic arc-tangent of the input.

Examples

See Also
Name Description
atan Arc-tangent function
atan2 Two-variable arc-tangent function
tan Tangent function
tanh Hyperbolic tangent function
atodb
Convert linear amplitude to decibels

Description
Converts any given linear amplitude value to its corresponding decibel value.

Arguments
None.

Messages
bang The most recently calculated decibel value is sent out the outlet.
int linear-amplitude [int] A linear amplitude value. The corresponding gain/attenuation in decibels is sent
out the outlet.
float linear-amplitude [float] A linear amplitude value. The corresponding gain/attenuation in decibels is sent
out the outlet.
list amplitude-list [list] A list of linear amplitude values. Corresponding gain/attenuation values in
decibels for each list item are sent out the outlet.
set linear-amplitude [float] The message set followed by a linear amplitude value will set the next value to be
calculated into decibels without sending anything out the outlet.

Information for box attributes common to all objects

Output
float: The gain or attenuation from unity gain, expressed in decibels.
int: The gain or attenuation from unity gain, expressed in decibels.

Examples

See Also
Name Description
expr Evaluate a mathematical expression
atodb~ Convert linear amplitude to a signal-rate deciBel value
dbtoa Convert decibels to a linear amplitude
dbtoa~ Convert a deciBel value to linear amplitude at signal rate
atoi
Convert ASCII characters to integers

Description
Arguments
None.

Messages
bang In left inlet: a bang message can be used to trigger the output of the currently
stored numerical list. A bang in the right two inlets is treated as a symbol.
int input [int] In left inlet: The ASCII value of each of the digits of the number is stored
internally and sent out the outlet as a list.
float input [float] In left inlet: The ASCII value of each of the digits of the number is stored
internally and sent out the outlet as a list.
list input [list] Each int in the list is converted to ASCII as described above, and a space character
(ASCII value 32) is inserted between items in the list. The middle inlet is used to
append to the currently stored list, and the right inlet will set the contents of the
internally stored list, without causing output.
anything input [list] In left inlet: The ASCII value of each letter, digit, or other character in the symbol
is stored internally and sent out the outlet as a list.

In middle inlet: The ASCII value of each letter, digit, or other character in the
symbol is appended to the currently stored list. No output is triggered.

In right inlet: The ASCII value of each letter, digit, or other character in the
symbol is stored internally, replacing the previously stored list, but not output.
clear In left inlet: The clear message is used to clear the contents of the internally-
stored numerical list. The word clear in the right two inlets is treated as a symbol.

Information for box attributes common to all objects

Output
list: The ASCII representation of the input is sent out as a list of integers.

Examples

See Also
Name Description
itoa Convert integers to ASCII characters
key Report keyboard presses
keyup Report key information on release
message Send any message
regexp Use regular expressions to process input
spell Convert input to ASCII codes
sprintf Format a message of words and numbers
attrui
Inspect attributes

Description
Use attrui object to inspect the attribute values of the object(s) it is connected to.

Arguments
Name Units Type Opt Description
OBJARG_NAME OBJARG_TYPE

Messages
int input [int] Set the value of the currently selected attribute to every objects attrui is connected
to.
float input [float] See the int listing
list input [any] See the int listing
anything input [any] See the int listing
(mouse) Click in the attribute name to choose an attribute from the popup menu to inspect
(only the common attribute for every connected object appears). Interact with the
numbers, text input to change the value(s) of the selected attribute.

Attributes
Name Type g/s Description
align int Alignment
def.:0 'Left' = TEXT_HERE
'Center' = TEXT_HERE
'Right' = TEXT_HERE
arrowcolor float Set the color of the arrow
attr symbol Set the name of the inspected attribute. You can also click in the attribute name to
def.:nothing display a popup menu which contains every common attributes.
attr_display int Attribute Display
def.:0 'Name' = TEXT_HERE
'Label' = TEXT_HERE
attrfilter symbol Set the names of the attribute you want to display in the popup menu. This is
def.:none particularly useful for objects which have a lot of attributes.
bgcolor float Set the background color
bgcolor2 float Set the second background color
bordercolor float Set the border color
displaymode int Set the way of displaying the attribute value
def.:0 'Automatic' = TEXT_HERE
'Single Number (int)' = TEXT_HERE
'Single Number (float)' = TEXT_HERE
'Multi Number (int)' = TEXT_HERE
'Multi Number (float)' = TEXT_HERE
'List' = TEXT_HERE
'Color (RGBA)' = TEXT_HERE
'Color (ARGB)' = TEXT_HERE
'Checkbox' = TEXT_HERE
htricolor float Set the highlighted triangle color (when the numbers are focussed)
lock int Prevent you from changing the attribute by clicking in the attribute name
def.:0
menu_display int Menu Display
def.:0 'Label' = TEXT_HERE
'Name' = TEXT_HERE
'Label & Attribute' = TEXT_HERE
orientation int Display attrui horizontally or vertically
def.:0 'Horizontal' = TEXT_HERE
'Vertical' = TEXT_HERE
rounded float Set the roundness of the border
def.:8.
showcaption int Display attribute label on mouse over
text_width float Set the with of the attribute name in horizontal mode. You can also click and drag
def.:100. in the middle line to change it.
textcolor float Set the text color
tricolor float Set the triangle color

Information for box attributes common to all objects

Examples

See Also
Name Description
getattr Query object attributes
pattr Provide an alias with a named data wrapper
autopattr
Expose multiple objects to the pattr system

Description
Causes multiple objects within a patcher to be automatically included in the pattr system.

Note: you should use only one instance of an autopattr object per level in a patch.

Arguments
Name Units Type Opt Description
name symbol opt A symbol argument can be used to set the autopattr object's name. In the absence
of an argument, the autopattr object is given an arbitrary, semi-random name,
such as u197000004.

Messages
bang bang is passed through the autopattr object and output from its center right
outlet.
int input [int] An int is passed through the autopattr object and output from its center right
outlet.
float input [float] float is passed through the autopattr object and output from its center right
outlet.
list input [list] list is passed through the autopattr object and output from its center right outlet.
anything input/arguments [list] Any message is analyzed. If the first element of the message matches the name
of an object maintained by the autopattr, the subsequent arguments in the
message set that object's value. If the first element of the message matches get
(name), where (name) matches the name of an object maintained by the
autopattr, the value of that object is sent from the autopattr object's right outlet,
prepended by the object's name. Otherwise, the message is passed through the
autopattr object and output from its center right outlet.
getattributes Causes a list of all objects names maintained by the autopattr object to be output
from the right outlet, prepended by the symbol attributes.
getstate Causes a series of lists to be output from the autopattr object's right outlet, one
for every object maintained by the autopattr. Each list begins with the name of
the object, and is followed by the object's current value.

Attributes
Name Type g/s Description
autoname int The word autoname, followed by a 1 or 0, enables or disables the autopattr
object's autoname state. The default is 0 (off). When enabled, the autopattr object
will automatically name any unnamed objects in the patcher supported by the
pattr system and bind to them, if possible. Naming only occurs when the patcher
loads, when the autopattr object is again instantiated, or when the autopattr
object receives the message autoname 1. New objects placed in a patcher after the
autopattr has been instantiated will not be autonamed until one of these
conditions is met.
autorestore int The word autorestore, followed by a 1 or 0, enables or disables the autopattr
object's autorestore state. The default is 1 (on). When enabled, the autopattr
object will automatically output its last-saved values when the patcher is loaded,
and distribute them to bound objects. Values are saved whenever the patcher is
saved.
dirty int The word dirty, followed by a 1 or 0, enables or disables the patcher-dirty flag. The
default is 0 (disabled). When enabled, the autopattr object will dirty the patch
whenever its state changes.
greedy int The word greedy, followed by a 1 or 0, enables or disables the attribute-gathering
feature of the autopattr object. The default is 0 (disabled). When enabled, any
internal attributes of objects attached to the left outlet of the autopattr object will
be exposed to the pattr system (as well as the normal value, if present).
name symbol The word name, followed by a symbol, sets the autopattr object's patcher name.

Information for box attributes common to all objects

Output
(internal): Out left outlet: Any user interface object (or other object that responds to the internal messaging system utilized by
autopattr) connected to the left outlet of the autopattr object will be automatically named (if necessary) and bound to. If the
autopattr object's greedy attribute has been enabled, any attributes associated with the bound object will also be exposed to the
pattr system. The name is automatically generated from the object's class name (e.g. a connected number box might be named
number[1].) At the time of this writing, the following Max user interface objects can be bound in this fashion: dial, function,
gain~, ggate, gswitch, js, jsui (see the JavaScript in Max manual for more information on using the pattr system with
JavaScript), led, matrixctrl, multislider, number box (int and float), pictctrl, pictslider, radiogroup, rslider, slider, table,
textedit, toggle and umenu.

Out center-left outlet: Any user interface object (or other object that responds to the internal messaging system utilized by
autopattr) connected to the center left outlet of the autopattr object will be automatically named (if necessary) and excluded
from the autopattr object's bound-object list.
anything: Out center-right outlet: Any message not matching a get or set request to an object maintained by the autopattr is
passed, unchanged, through the center right outlet.

Out right outlet: get queries to an object maintained by the autopattr are output from the right outlet, also known as the
dumpout outlet.

Examples

See Also
Name Description
pattr Provide an alias with a named data wrapper
pattrforward Send any message to a named object
pattrhub Access all pattr objects in a patcher
pattrmarker Provide pattr communication between patchers
pattrstorage Save and recall pattr presets
Max pattr Tutorial 2: Automatic Max pattr Tutorial 2: Automatic Bindings and Storage
Bindings and Storage
bag
Store a collection of numbers

Description
Stores and manages a collection of numbers. You can add to or delete an integer from a bag as report its contents. bag with any
argument maintains multiple entries with the same item; otherwise it holds only one of each.

Arguments
Name Units Type Opt Description
duplicate-flag symbol opt The presence of any symbol argument causes the bag to store duplicate values. If
there is no argument, bag will store only one of each number at a time.

Messages
bang In left inlet: Causes bag to send all its collected numbers out the outlet.
int input [int] In left inlet: The number is either added to or deleted from the collection of
numbers stored in the bag object, depending on the number in the right inlet.

In right inlet: The number is stored as an indicator of whether to include or delete


the next number received in the left inlet. If non-zero, the number received in the
left inlet is added to the bag. If 0, the number is deleted from the collection.

No output is triggered by a number received in either inlet.


(inlet1) function [int] In right inlet: The number is stored as an indicator of whether to include or delete
the next number received in the left inlet. If non-zero, the number received in the
left inlet is added to the bag. If 0, the number is deleted from the bag.

No output is triggered by a number received in either inlet.


float input [float] Converted to int.
clear In left inlet: Deletes the entire contents of the bag.
cut In left inlet: Sends out the oldest (earliest received) number stored in the bag
object, and deletes it from the bag.
length In left inlet: Reports how many numbers are currently stored in the bag.
send receive-name [list] In left inlet: The word send, followed by the name of a receive object, sends the
result of a bang message to all receive objects with that name, instead of out the
bag object's outlet.
list input [int] Any list composed of two numbers behaves as though the first list item was sent to
function [int] the left inlet and the second list item was sent to the right inlet. If the second
element of the list is a non-zero number, the number is added to the collection.

Information for box attributes common to all objects

Output
int: When bang is received in the left inlet, all the numbers stored in bag are sent out one at a time, in reverse order from that
in which they were stored.

When cut is received in the left inlet, the oldest stored number is sent out.

When length is received in the left inlet, the number of items in the bag object is sent out.

Examples
Store a collection of numbers........ Used here to detect held notes

See Also
Name Description
coll Store and edit a collection of data
funbuff Store pairs of numbers
offer Store one-time number pairs
bangbang
Output a bang from many outlets

Description
Outputs bang messages out of each outlet (in right-to-left order) when it receives any input. The number of outlets is determined
by an argument.

Arguments
Name Units Type Opt Description
outlets number opt Sets the number of outlets. The number of outlets can be any number between 1
and 40. Floats are converted to ints.

Messages
bang Causes a bang to be sent out all outlets in right-to-left order.
int input [int] Causes a bang to be sent out all outlets in right-to-left order.
float input [float] Causes a bang to be sent out all outlets in right-to-left order.
anything input [list] Causes a bang to be sent out all outlets in right-to-left order.

Information for box attributes common to all objects

Output
bang: When a message is received in the inlet, a bang is sent out each outlet, in order from right to left.

Examples

Order is right-to-left....... Order is specified by bangbang

See Also
Name Description
button Blink and send a bang
jstrigger Execute Javascript instructions sequentially
trigger Send input to many places
Max Basic Tutorial 5: Message Max Basic Tutorial 5: Message Order and Debugging
Order and Debugging
bendin
Output MIDI pitch bend values

Description
Outputs pitch bend values received from a MIDI device. The MIDI port and channel can be chosen with messages or by double-
clicking on the object.

Arguments
Name Units Type Opt Description
port symbol opt Specifies the port from which to receive incoming pitch bend messages. If there is
no argument, bendin receives from all channels on all ports.
midi-device symbol opt The name of a MIDI input device may be used as the first argument to specify the
port.
port-and-channel symbol A letter and number combination (separated by a space) indicates a port and a
specific MIDI channel on which to receive pitch bend messages. Channel numbers
greater than 16 will be wrapped around to stay within the 1-16 range.
channel int A number alone can be used in place of a letter and number combination. The
exact meaning of the channel number argument depends on the channel offset
specified for each port in the MIDI Setup dialog.

Messages
anything arguments [list] See the port message
(mouse) Double-clicking on a bendin object shows a pop-up menu for choosing a MIDI
port or device.
(MIDI) The bendin object receives its input from a MIDI pitch bend message received
from a MIDI input device.
port MIDI-port [symbol] The word port, followed by a letter a-z or the name of an MIDI port or device,
sets the port from which the object receives incoming pitch bend messages. The
word port is optional and may be omitted.

Information for box attributes common to all objects

Output
int: If a specific channel number is included in the argument, there is only one outlet. The output is the incoming pitch bend
value from 0-127 (the most significant byte of the MIDI pitch bend message) on the specified channel and port.

If there is no channel number specified by the argument, bendin will have a second outlet, on the right, which will output the
channel number of the incoming pitch bend message.

Examples

Pitch bend messages can be received from everywhere, a specific port, or a specific port and channel
See Also
Name Description
bendout Send MIDI pitch bend messages
ctlin Output received MIDI control values
midiin Output raw MIDI data
notein Receive MIDI note messages
rtin Receive MIDI real time messages
xbendout Format extra precision MIDI pitch bend messages
xbendin Interpret extra precision MIDI pitch bend values
Max MIDI Tutorial 3: MIDI Parsing Max MIDI Tutorial 3: MIDI Parsing
bendout
Send MIDI pitch bend messages

Description
Transmits MIDI pitchbend values to a MIDI device.

Arguments
Name Units Type Opt Description
port symbol opt Specifies the port for transmitting MIDI pitch bend messages. Channel numbers
greater than 16 received in the right inlet will be wrapped around to stay within the
1-16 range. If there is no argument, bendout initially transmits out port a, on
MIDI channel 1.
port-and-channel list and int A letter and number combination (separated by a space) indicates a port
and a specific MIDI channel on which to transmit pitch bend messages. Channel
numbers greater than 16 will be wrapped around to stay within the 1-16 range.
midi-device symbol opt The name of a MIDI output device may be used as the first argument to specify the
port.
channel int A number alone can be used in place of a letter and number combination. The
exact meaning of the channel number argument depends on the channel offset
specified for each port in the MIDI Setup dialog.

Messages
int input [int] In left inlet: The number is transmitted as a MIDI pitch bend value on the
specified channel and port. Numbers are limited between 0 and 127.
(inlet1) MIDI-channel [int] In right inlet: The number is stored as the channel number on which to transmit
the pitch bend messages.
float input [float] Converted to int.
anything MIDI-port [list] See the port message
(mouse) Double-clicking on a bendout object shows a pop-up menu for choosing a MIDI
port or device.
port MIDI-port [symbol] In left inlet: The word port, followed by a letter a-z or the name of a MIDI output
port or device, specifies the port used to transmit MIDI messages. The word port
is optional and may be omitted.

Information for box attributes common to all objects

Output
(MIDI): There are no outlets. The output is a MIDI pitch bend message transmitted directly to the object's MIDI output port.

Examples

Letter argument transmits to only one port....... Otherwise, number specifies both port and channel

See Also
Name Description
bendin Output MIDI pitch bend values
midiout Transmit raw MIDI data
xbendout Format extra precision MIDI pitch bend messages
xbendin Interpret extra precision MIDI pitch bend values
bgcolor
Set background color

Description
Set the background color of the patcher window. The bgcolor object's functionality is equivalent to a brgb message sent to
thispatcher.

Arguments
Name Units Type Opt Description
red int opt A number in the range 0-255 sets the red value for the background color of the
patcher.
green int opt A number in the range 0-255 sets the green value for the background color of the
patcher.
blue int opt A number in the range 0-255 sets the blue value for the background color of the
patcher.

Messages
bang bang will reset the patcher's background to the RGB values most currently
received by bgcolor.
int red [int] A number in the range 0-255 sets the red value of the patcher background color.
(inlet1) green [int] A number in the range 0-255 sets the green value of the patcher background color.
(inlet2) blue [int] A number in the range 0-255 sets the blue value of the patcher background color.
list red [int] A list of three numbers in the range 0-255 sets the background color of the patcher
green [int] in RGB format.
blue [int]
set red [int] The word set followed by a list of three numbers in the range 0-255 sets the
green [int] background color of the patcher in RGB format.
blue [int]

Information for box attributes common to all objects

Output
(Visual): The background color of the patcher is set.

Examples

See Also
Name Description
thispatcher Send messages to a patcher
&
Bitwise intersection of two numbers

Description
Performs a bit-by-bit AND of two numbers as expressed in binary. Outputs a number composed of all those bits which are 1 in
both of the two numbers.

Arguments
Name Units Type Opt Description
initial-value int opt Sets an initial value to be AND-ed with a number received in the left inlet.

Messages
bang In left inlet: Performs the comparison with the numbers currently stored. If there
is no argument, & initially holds 0 for comparison.
int input [int] In left inlet: The number is compared, in binary form, with the number in the right
inlet. The output is a number composed of those bits which are 1 in both numbers.
(inlet1) comparison-number [int] In right inlet: The number is stored for comparison with a number received in the
left inlet.
float input [float] Converted to int.
set set-input [int] In left inlet: The word set followed by a number will set the input to the bitwise-
and operation without causing output (a successive bang will output the result).
list input [number] In left inlet: Compares the first and second numbers bit-by-bit, and outputs a
comparison-value [number] number composed of those bits which are 1 in both numbers.

Information for box attributes common to all objects

Output
int: The two numbers received in the inlets are compared, one bit at a time. If a bit is 1 in both numbers, it will be 1 in the output
number, otherwise it will be 0 in the output number.

Examples

Nonzero bits shared by both numbers........ Can be used as an odd/even detector

See Also
Name Description
&& Perform a logical AND
| Bitwise union of two numbers
|| Perform a logical OR
Max Basic Tutorial 19: Timing Max Basic Tutorial 19: Timing
|
Bitwise union of two numbers

Description
Performs a bit-by-bit OR of two numbers (expressed in binary for the task). Outputs a number composed of all those bits which
are 1 in either of the two numbers.

Arguments
Name Units Type Opt Description
initial-value int opt Sets an initial value to be OR-ed with a number received in the left inlet.

Messages
bang In left inlet: Performs the calculation with the numbers currently stored. If there is
no argument, | initially holds 0.
int input [int] In left inlet: Outputs a number composed of all those bits which are 1 in either of
the two numbers.
(inlet1) comparison-number [int] In right inlet: The number is stored for combination with a number received in the
left inlet.
float input [float] Converted to int.
set set-input [int] In left inlet: The word set followed by a number will set the input to the bitwise-or
operation without causing output (a successive bang will output the result).
list input [number] In left inlet: Combines the first and second numbers bit-by-bit, and outputs a
comparison-value [number] number composed of all those bits which are 1 in either of the two numbers.

Information for box attributes common to all objects

Output
int: All the non-zero bits of the two numbers received in the inlets are combined. If a bit is 1 in either one of the numbers, it will
be 1 in the output number, otherwise it will be 0 in the output number.

Examples

All non-zero bits are combined......... Can be used to pack two numbers into one int

See Also
Name Description
& Bitwise intersection of two numbers
&& Perform a logical AND
|| Perform a logical OR
Max Basic Tutorial 19: Timing Max Basic Tutorial 19: Timing
bline
Generate ramps using bang

Description
Generates a linear ramp driven by incoming bang messages. It takes a list of breakpoint segments (and the number of events to
span) and outputs a smooth ramp between values.

Arguments
Name Units Type Opt Description
initial-value number opt Optional. An argument may be used to set the initial value to be stored and the
output type for the object--if the first argument is an int, the bline object outputs
integer values, and a float will set the bline object to output floating point values.
If there is no argument, the initial value is 0 and the output type is int.

Messages
bang Sends a new step in the breakpoint list out the left outlet. If the current list of
ramp segments is finished, a bang message will be sent out the right outlet
int input [int] Sets the bline object to the specified integer value. Any and all pending breakpoint
segments are forgotten (i.e. the time is considered 0 and bline outputs the target
value when it receives a bang).
float input [float] Sets the bline object to the specified float value. Any and all pending breakpoint
segments are forgotten (i.e. the time is considered 0 and bline outputs the target
value when it receives a bang).
list segment-pairs [list] The bline object sets breakpoint segment values using lists of data composed of
pairs of numbers. The first number in each pair can be either an int or a float
specifying a target value, followed by an integer that specifies the number of bang
messages that will have to be received before reaching the target value--note that
this differs from other Max breakpoint objects like line, which specify a time-to-
target value in milliseconds.
set input [number] Sets the bline object to the specified value. Any and all pending breakpoint
segments are forgotten (i.e. the time is considered 0 and bline outputs the target
value when it receives a bang).
stop Stops bline from sending out numbers, until a new list of ramp segments is
received.

Information for box attributes common to all objects

Output
bang: Out right outlet: When bline has arrived at its target value, bang is sent out.
int: Out left outlet: Numbers are sent out in response to received bang messages, describing a straight line toward a target value.
If a list of breakpoint segments is specified before the line is completed, the new line starts from the most recent output value in
order to avoid discontinuities.

If a value is received in the left inlet without an accompanying time value, it is sent out immediately.

Examples
See Also
Name Description
funbuff Store pairs of numbers
line Generate timed ramp
uzi Send many bang messages
bondo
Synchronize a group of messages

Description
Synchronizes and outputs a set of inputs when any input is received. It can also be set with a time interval value (in milliseconds)
to wait before sending its output.

Arguments
Name Units Type Opt Description
inlets-outlets int opt Specifies the number of inlets and outlets. The default number of inlets and outlets
is 2.
delay ms int opt Specifies the number of milliseconds to delay when a message is received before
sending messages out the outlets.
list-flag symbol opt Using the symbol "n" as an argument, bondo is able to synchronize lists which
arrive in different inlets.

Messages
bang Send all stored messages
int input [int] In any inlet: The input is stored in the location corresponding to that inlet, and
causes anything previously stored to be sent out its corresponding outlet. If no
message has yet been received in a particular inlet, 0 is sent out of the
corresponding outlet.
float input [float] In any inlet: The input is stored in the location corresponding to that inlet, and
causes anything previously stored to be sent out its corresponding outlet. If no
message has yet been received in a particular inlet, 0 is sent out of the
corresponding outlet.
list input [list] In any inlet: The elements of the list are parsed among the inlets. The first element
in the list is sent out the outlet which corresponds to the inlet which received the
list and each subsequent element in the list is sent out each subsequent outlet.

If the "n" argument was used, bondo will store and output lists for each outlet in
addition to single numbers.
anything input [list] In any inlet: The input is stored in the location corresponding to that inlet, and
causes anything previously stored to be sent out its corresponding outlet. If no
message has yet been received in a particular inlet, 0 is sent out of the
corresponding outlet.
set input [list] In any inlet: The word set, followed by any message, stores the input in the
location corresponding to that inlet without triggering any output.

Information for box attributes common to all objects

Output
any message: Anything stored in an inlet is sent out the corresponding outlet numbers. Output is immediate if triggered by a
bang. If output is triggered by a message, and a second argument has been typed in, output will be delayed by the number of
milliseconds specified in the second argument.

Examples
bondo can synchronize messages arriving from different sources

See Also
Name Description
buddy Synchronize arriving data
join Combine items into a list
onebang Gate bangs using a bang
pack Create a list
thresh Combine messages when received close together
borax
Report note-on and note-off information

Description
Acquires and outputs comprehensive information regarding note-on and note-off events. Information includes note counts, event
details and time between note events.

Arguments
None.

Messages
bang In right inlet: Resets borax by sending note-offs for all notes currently being held,
erasing the borax object's memory of all notes received, and setting its counters
and its clock to 0.
int pitch [int] In left inlet: The number is the pitch value of a MIDI note-on message or note-off
message (note-on with a velocity of 0). The pitch is paired with the velocity in the
middle inlet. borax ignores note-on messages for pitches it is already holding, and
ignores note-off messages for pitches that have already been turned off. If the note
is not a duplicate, borax sends out the pitch and velocity values, as well as other
information.
(inlet1) velocity [int] In middle inlet: The number is stored as the velocity, to be paired with pitch
numbers received in the left inlet.
delta Causes the delta time (the time elapsed since the last note-on) and the delta count
(the number of delta times that have been reported) to be sent out.
list pitch [int] The second number is stored as the velocity, and the first number is used as the
velocity [int] pitch, of a pitch-velocity pair. If the note is not a duplicate, borax sends out the
pitch and velocity values, as well as other information.

Information for box attributes common to all objects

Output
int: Out left outlet: Each note-on received by borax is assigned a unique number, equal to the total count of note-ons received
(since the last reset). That number is sent out when the note-on is received, and the same number is sent out when the note is
turned off.

Out 2nd outlet: Each note is also assigned a unique voice number, equal to the lowest available number. (A voice becomes
available when the note assigned to it is turned off.) That number is sent out when the note-on is received, and the same number
is sent out when the note is turned off.

Out 3rd outlet: The number of notes being held by borax is sent out each time a note-on or a note-off is received.

Out 4th outlet: The pitch of the note-on or note-off is sent out.

Out 5th outlet: The velocity of the note-on or note-off is sent out.

Out 6th outlet: When a note-off is received, the total count of all completed notes (since the last reset) is sent out.

Out 7th outlet: When a note-off is received, the duration of that note, in milliseconds, is sent out.

Out 8th outlet: Each time a delta time is reported, the total count of delta times is sent out.

Out right outlet: When a note-on is received, the delta time is sent out (the time elapsed since the previous note-on, in
milliseconds). A delta message in the left inlet causes the same output.

bang received in the right inlet causes borax to provide note-offs for any notes it currently holds. These note-offs trigger the
same outputs as if they had actually been received.

Examples

borax provides extensive information about the notes passing through

See Also
Name Description
midiparse Interpret raw MIDI data
poly Allocate notes to different voices
bpatcher
Embed a subpatch with a visible UI

Description
Abstracts the contents of a patcher or subpatcher for use in other patchers, displaying only those visual elements which are
desired. The number of inlets and outlets in a bpatcher object is determined by the number of inlet and outlet objects contained
in its subpatch window.

Arguments
None.

Messages
(drag) When a patcher file is dragged from the Max 5 File Browser to a bpatcher object,
the file will be loaded.
(mouse) When the window containing the bpatcher object is locked (or the Command key
on Macintosh or Control key on Windows is held down) and the mouse is clicked
inside the bpatcher objects box, the gesture is handled by the patch inside the
box.
If the Shift and Command keys on Macintosh or Shift and Control keys on
Windows are held down while clicking on a bpatcher object, dragging the mouse
moves the upper-left corner of the visible part of the patch inside the box. The
Assistance area of the patcher window shows the pixel values of the offset. If
Enable Drag-Scrolling is unchecked in the bpatcher Inspector window, this feature
is disabled.
If the Command and Option keys on Macintosh or Control and Alt keys on
Windows are held down while clicking in a bpatcher object, a pop-up menu allows
you to open the original file of the patch contained inside the box in its own
window, or change the patch currently contained inside the box in its own window.
replace filename [symbol] The replace message is intended for use in conjunction with scripting messages to
the thispatcher object. If you send a replace message via an inlet to the bpatcher
object, it will only work if there is no patcher inside the bpatcher; the inlet to the
bpatcher object is used for sending messages into its subpatcher, not for sending
messages to the bpatcher object itself.
To use the replace message feature via scripting messages, give your bpatcher
object a Scripting Name using the Inspector, then use the message script
sendbox <bpatcher-name> replace <patcher-name> to send the message
to the named bpatcher object.

Attributes
Name Type g/s Description
args atom When followed by a number of ints, floats, or symbols, this attribute lets you input
def.: arguments to your patcher which will be saved along with the main patch.
bgcolor float Sets the background color of the patcher visible in the bpatcher window.
def.:1. 1. 1. 1.
bgmode int Sets the display mode for displaying the bpatcher's background color. The options
def.:0 are:

0: Transparent. The bpatcher window has no background color


1: Background Color. The bpatcher window uses the background color of the
patcher
2: Override Background Color. The bpatcher window uses the color set using the
Background Color attribute as the background color.
'Transparent' = TEXT_HERE
'Patcher Background Color' = TEXT_HERE
'Override Background Color' = TEXT_HERE
border int Toggles the drawing of a border around the bpatcher. This value can only be set
def.:0 using the Border setting in the bpatcher object's Inspector. The default
appearance is unchecked (no border).
clickthrough int Toggles the ability to have any mouse activity inside the bpatcher window handled
def.:0 by the patch inside the box. This value can only be set using the Click-through
setting in the bpatcher object's Inspector.
embed int Toggles the ability to embed the subpatch you are using and save it as part of the
def.:0 main patch (just as with a patcher object) instead of the subpatch being saved in a
separate file. This value can only be set using the Embed Patcher in Parent setting
in the bpatcher object's Inspector. The default behavior is 0 (save the subpatch as
a separate file).
enablehscroll int Toggles the creation of a horizontal scrollbar in the bpatcher window for use in
def.:0 horizontally traversing a visible area of the embedded patcher. This value can only
be set using the Enable Horizontal Scrollbar setting in the bpatcher object's
Inspector.
enablevscroll int Toggles the creation of a vertical scrollbar in the bpatcher window for use in
def.:0 vertically traversing a visible area of the embedded patcher. This value can only be
set using the Enable Vertical Scrollbar setting in the bpatcher object's Inspector.
lockeddragscroll int Enables/disables drag-scrolling in the bpatcher window when the patcher is
def.:0 locked.
name symbol Designates the pathname of the patcher file for the bpatcher to use. This value
def.:<none> can only be set using the Patcher File setting in the bpatcher object's Inspector.
offset float Specifies the number of pixels by which the upper left corner of the subpatch is to
def.:0. 0. be offset horizontally and vertically within the bpatcher. If the subpatch being
used in the bpatcher contains a thispatcher object connected to one of its inlet
objects, the view of the subpatch can be changed by an offset message received in
the corresponding inlet of bpatcher. In this way, a single bpatcher can be used to
give different views of the subpatch. User interface objects in the subpatch that are
partially outside the bpatcher objects box will redraw completely (even outside
the bounds of the bpatcher) in response to messages received in their inlet. It is
therefore advised that user interface objects in the subpatch be either completely
inside or completely outside the bpatcher objects box.

Information for box attributes common to all objects

Output
(User-Defined): If the patcher being used in a bpatcher contains outlet objects, they will appear in corresponding left-to-right
order as outlets in the bpatcher object's box.

Examples

View the contents of a subpatcher...... The contents of this patch can be windowed... ...using offset messages to a small bpatcher
containing it
See Also
Name Description
patcher Create a subpatch within a patch
pcontrol Open and close subwindows
thispatcher Send messages to a patcher
Max Interface Tutorial 1: Max Interface Tutorial 1: bpatchers
bpatchers
Search Path Search Path
bucket
Pass numbers from outlet to outlet

Description
Outputs incoming values to outlets in bucket-brigade fashion. bucket acts as an n-stage shift register which can shift its contents
from outlet to outlet in either direction.

Arguments
Name Units Type Opt Description
outlets int opt Sets the number of outlets. If there is no argument, there will be one outlet.
output-flag int opt A second non-zero argument sets the bucket object to "echo to output" mode,
whereby the number received in the inlet is stored and sent out the left outlet
when it is received. This makes it somewhat easier to visualize the data coming
from the outlets.

Messages
bang All stored values are sent out, but their position is not shifted.
int input [int] The numbers currently stored in bucket are sent out, then each number is moved
one outlet to the right and the new number is stored to be sent out the left outlet
the next time a number is received.
float input [float] The numbers currently stored in bucket are sent out, then each number is moved
one outlet to the right and the new number is stored to be sent out the left outlet
the next time a number is received.
L2R Sets bucket to shift its stored values from left to right (the default) whenever it
receives a number in its inlet.
R2L Sets bucket to shift its stored values from right to left whenever it receives a
number in its inlet, placing the incoming number in the rightmost outlet.
freeze Suspends the bucket output, but new incoming numbers continue to shift the
stored values internally.
l2r Sets bucket to shift its stored values from left to right (the default) whenever it
receives a number in its inlet.
set input [number] The word set, followed by a number, sends that number out each outlet, and
stores the number as the next value to be sent out each of its outlets.
r2l Sets bucket to shift its stored values from right to left whenever it receives a
number in its inlet, placing the incoming number in the rightmost outlet.
roll The word roll, followed by any number, causes bucket to use the value stored in
its rightmost outlet as input; thus, it sends its output, shifts all stored values to the
right, then stores the value which had been in the rightmost outlet in the leftmost
outlet (as if it had been received in the inlet).
thaw Resumes bucket output.

Information for box attributes common to all objects

Output
int or float: When a number is received, it is not sent out immediately, but the numbers stored in bucket are sent out. The
numbers are all moved one outlet to the right, and the newly received number is stored in the left position. When using the "echo
to output" mode (set with a non-zero second argument to the object) the number received is sent out immediately, instead of the
previous input value.

Examples
Numbers are passed from one outlet to another

See Also
Name Description
cycle Round-robin messages to outlets
decode Send 1 or 0 out a specific outlet
gate Pass input to an outlet
spray Distribute a value to a numbered outlet
Max Basic Tutorial 15: Max Basic Tutorial 15: Abstractions
Abstractions
buddy
Synchronize arriving data

Description
Outputs incoming data after something has been received in all inlets.

Arguments
Name Units Type Opt Description
inlets int opt Sets the number of inlets and outlets. If there is no argument, there are two inlets
and two outlets.

Messages
bang In any inlet: Same as sending the number 0.
int input [int] In any inlet: When data has been received in all its inlets, buddy sends the
received messages out their corresponding outlets, then waits until data has
arrived again in all inlets.
float input [float] In any inlet: When data has been received in all its inlets, buddy sends the
received messages out their corresponding outlets, then waits until data has
arrived again in all inlets.
list input [list] In any inlet: When data has been received in all its inlets, buddy sends the
received messages out their corresponding outlets, then waits until data has
arrived again in all inlets.
anything input [list] In any inlet: When data has been received in all its inlets, buddy sends the
received messages out their corresponding outlets, then waits until data has
arrived again in all inlets.
clear In left inlet: Deletes all values stored in the inlets.

Information for box attributes common to all objects

Output
any message: When a data has arrived in each inlet, it is sent out the outlets, in order from right to left.

Examples

Output is synchronous, even if input is not synchronous

See Also
Name Description
bondo Synchronize a group of messages
onebang Gate bangs using a bang
join Combine items into a list
pack Create a list
swap Swap position of two numbers
thresh Combine messages when received close together
unjoin Break a list into messages
unpack Break a list into individual messages
button
Blink and send a bang

Description
button provides visual feedback of an action and is used to trigger other messages and processes.

Arguments
None.

Messages
bang See the anything listing
int input [int] See the anything listing
float input [float] See the anything listing
list input [list] See the anything listing
anything input [list] When any message is received in the inlet, button flashes briefly and a bang is
sent out the outlet.
(mouse) Clicking on the button object will cause it to blink briefly and send a bang out the
outlet.

Attributes
Name Type g/s Description
bgcolor float Sets the background color of the button object in RGBA format.
blinkcolor float Sets the blink color of the button object in RGBA format.
fgcolor float Sets the color of the button object in RGBA format.
outlinecolor float Sets the outline color of the button object in RGBA format.

Information for box attributes common to all objects

Menu Items
Name Description
Color Choosing the Color... menu item from the Object menu when the object is
selected opens a color picker, permitting adjustment to the appearance of the
button object.

Output
bang: A mouse click or any message in the inlet causes button to blink and output a bang.

Examples

Triggers other messages and processes.... Converts other messages to a bang

See Also
Name Description
bangbang Output a bang from many outlets
loadbang Send a bang when a patcher is loaded
loadmess Send a message when a patch is loaded
matrixctrl Matrix switch control
pictctrl Picture-based control
trigger Send input to many places
ubutton Send a bang with a transparent button
Max Basic Tutorial 2: Bang! Max Basic Tutorial 2: Bang!
capture
Store values to view or edit

Description
Stores up to 512 items in the order they are received for viewing, editing, and saving.

Arguments
Name Units Type Opt Description
maximum int opt The first argument sets a maximum number of items to store. If there is no
argument, capture will store up to 512 items. Once the maximum has been
exceeded, the earliest stored item is dropped as each new item is received.
display-format symbol opt If the second argument is a, all items will be displayed in ASCII form in the editing
window. If the second argument is x, all numbers will be displayed in hexadecimal
form in the editing window. If the second argument is m, numbers less than 128
are displayed in decimal, and numbers greater than 128 are in hexadecimal. If
there is no argument, all items are displayed in decimal.

Messages
int input [int] Numbers or symbols are stored in the order in which they are received.
float input [float] Numbers or symbols are stored in the order in which they are received.
list input [list] All numbers and/or symbols in the list are stored in order from first to last.
anything input [list] All numbers and/or symbols are stored in order from first to last.
(mouse) Double-clicking on the object in a locked patcher will open a window which
displays all values stored internally.
clear Erases the contents of a capture object.
dump Outputs the contents of the capture object, one item at a time, out the left outlet.
count input [int] Sends the number of items collected since the last count message out the right
outlet of the capture object.
open Causes the window associated with the capture object to become visible. The
window is also brought to the front. Double-clicking on the capture object in a
locked patcher has the same effect.
wclose Closes the window associated with the capture object.
write filename [symbol] The word write, followed by a symbol, saves the contents of the capture object
into a text file, using the symbol as the filename.

Information for box attributes common to all objects

Output
int: Out right outlet: The number of items received since last count message was received is sent out the right outlet in response
to a count message.
int, float, symbol: Out left outlet: The captured contents are sent out the left outlet, one at a time, in response to the dump
message.

Double-clicking on capture (when the patcher window is locked) opens an editing window in which the stored numbers can be
viewed and edited. Editing the window does not actually alter the contents of capture, but is useful for cutting and pasting values
into a table or a separate file. (Although capture can continue to store items while the editing window is open, the editing
window is not updated. It must be closed and reopened to view the newly stored items.)

Examples
Collect numbers to paste into a table... or just to see what's been going on

See Also
Name Description
itable Graphic display of a table
text Format messages as a text file
cartopol
Convert cartesian to polar coordinates

Description
Converts a cartesian-coordinate pair consisting of real and imaginary values into a polar-coordinate pair consisting of distance
and angle values.

Arguments
None.

Messages
bang bang will output the most recently stored coordinate pair conversion.
int coordinate [int] Converted to float.
float coordinate [float] In left inlet: The x coordinate of a Cartesian pair to be converted into a polar
coordinate pair consisting of distance and angle values. When used in an audio
context, the value represents the real part of a frequency domain value to be
converted into a polar coordinate pair consisting of amplitude and phase values.

In right inlet: The y coordinate of a Cartesian pair to be converted into a polar


coordinate pair consisting of distance and angle values. When used in an audio
context, the value represents the imaginary part of a frequency domain value to be
converted into a polar coordinate pair consisting of amplitude and phase values.

Information for box attributes common to all objects

Output
float: Out left outlet: The distance portion of the polar coordinate pair. When used in an audio context, the value represents the
magnitude (amplitude) of the frequency represented by the currently input.

Out right outlet: The angle portion of the polar coordinate pair. When used in an audio context, the value represents the phase,
expressed in radians, of the frequency represented by the current input. If only the left outlet is connected, the phase
computation is not performed.

Examples

Convert Cartesian to Polar coordinates

See Also
Name Description
atan2 Two-variable arc-tangent function
lcd Draw graphics in a patcher window
poltocar Convert polar to cartesian coordinates
pow Computes input to the nth power
Max Basic Tutorial 11: Procedural Max Basic Tutorial 11: Procedural Drawing
Drawing
change
Filter out repetitions of a number

Description
Output a number only if it is different from the stored number and will reset the stored number to that differing input number.
Alternate modes of operation also identify greater-than or less-than the conditions.

Arguments
Name Units Type Opt Description
initial-value int or float opt Sets the initial value for comparison to incoming numbers. If there is no argument,
the initial value is 0.
mode symbol opt A second argument may be + or -, a change to mode + or mode -. Subsequent
mode messages can change this behavior.

Messages
int input [int] The number is sent out the outlet only if it is different from the currently stored
value. Replaces the stored value.
float input [float] Outputs the number only if it is different from the currently stored value. Replaces
the stored value.
mode flag (+ or -) [symbol] Sets the detection mode of change. The word mode, followed by a +, causes
change to send a 1 out its left outlet if the received number is greater than the
previously received number.
The word mode, followed by a -, causes change to send out a -1 if the received
number is less than the previously received number.
The word mode by itself returns change to its default mode of sending out
received values that differ from the previously received input.
set stored value [number] Replaces the stored value without triggering output.

Information for box attributes common to all objects

Output
int: Out left outlet: The number received in the inlet is sent out only if it is different from the stored value.

Out middle outlet: If the stored value is 0 and the input is not 0, 1 is sent out; otherwise nothing is sent out.

Out right outlet: If the stored value is not 0 and the input is 0, 1 is sent out; otherwise nothing is sent out.

Examples

Filter out undesirable repetitions

See Also
Name Description
peak Output larger numbers
togedge Report zero/non-zero transitions
trough Output a number if it is less than previous numbers
Max Basic Tutorial 15: Max Basic Tutorial 15: Abstractions
Abstractions
clip
Limit numbers to a certain range

Description
Arguments
Name Units Type Opt Description
minimum number opt The minimum value is the lower limit to the range of output values allowed. If
only one argument is present, it is used as both the minimum and maximum limit.
If no argument is present, the minimum and maximum limit is 0.
maximum number opt The maximum value is the upper limit to the range of output values allowed. If
only one argument is present, it is used as both the minimum and maximum limit.
If no argument is present, the minimum and maximum limit is 0.

Messages
int input [int] The number is sent out the outlet, constrained within the minimum and maximum
limits specified by the minimum and maximum limits.
float input [float] The number is sent out the outlet, constrained within the minimum and maximum
limits.
list input [list] Each number in the list is constrained within the minimum and maximum limits,
and the constrained numbers are sent out as a list.
set minimum/maximum [list] The word set, followed by two numbers, resets the minimum and maximum
limits.

Information for box attributes common to all objects

Output
float: If the received number is a float, it is constrained within the specified minimum and maximum limits, then sent out the
outlet as a float.
int: When an int is received in the inlet, it is constrained within the specified minimum and maximum limits, then sent out the
outlet. If the received number is less than the minimum limit, the minimum value is sent out; if the received number is greater
than the maximum limit, the maximum value is sent out.
list: When a list is received in the inlet, each number is constrained within the specified minimum and maximum limits, and the
numbers are sent out as a list.

Examples

Numbers are always kept within the specified range

See Also
Name Description
maximum Output the highest value
minimum Output the smallest value
split Look for a range of numbers
< Compare numbers for less than condition
<= Compare numbers as less than or equal to
> Compare numbers for greater than condition
>= Compare numbers for greater than or equal to condition
clocker
Report elapsed time, at regular intervals

Description
The clocker object is a metronome that reports the time elapsed since it was started. This object uses the Max time format
syntax, so the interval that the clocker object uses can be either fixed or tempo-relative. Its output can be quantized using tempo-
relative syntax, and if the autostarttime attribute is set, the object can also start at a tempo-relative point.

Arguments
Name Units Type Opt Description
time- int, float, The first argument sets an initial value for the time interval at which clocker
interval symbol sends out its output. This time interval can be either a number which specifies
time in milliseconds (e.g. clocker 200) or a notevalue (e.g. clocker 4nd).

Note: While the clocker object lets you specify time in any of Max's standard time
formats, the Interval attribute argument should be used when specifying time in
any other time unit besides milliseconds or notevalues.

If there is no argument, the initial time interval is set to 5 milliseconds. If


notevalue, ticks, or bars.beats.units are specified for the delay interval, the clocker
object will not operate unless the transport is running.

Messages
bang In left inlet: Starts the clocker object. If the clocker object is not running, a bang
message will start the count. If the clocker object is running, a bang message will
reset the count.
int non-zero-to-start [int] In left inlet: Any non-zero number starts the clocker object. The time elapsed
since clocker was started is sent out the outlet at regular intervals. 0 stops the
clocker object. If clocker is already running when it receives a non-zero number,
it continues reporting the elapsed time at regular intervals from that new point,
but without resetting the clock time to 0.
float non-zero-to-start [float] In left inlet: Any non-zero number starts the clocker object. The time elapsed
since clocker was started is sent out the outlet at regular intervals. 0 stope the
clocker object. If clocker is already running when it receives a non-zero number,
it continues reporting the elapsed time at regular intervals from that new point,
but without resetting the clock time to 0. The clocker objects minimum interval
time is 0.02 second.
list input [list] In right inlet: A list may be used to specify time in one of the Max time formats.
anything interval [list] Same as list.
clock setclock object name The word clock, followed by the name of an existing setclock object, sets the
[symbol] clocker object to be controlled by that setclock object rather than by Maxs
internal millisecond clock. The word clock by itself sets the clocker object back to
using Maxs regular millisecond clock.
stop In left inlet: Stops the clocker object.
reset In left inlet: Resets the elapsed time to 0 without stopping or restarting the clock;
clocker continues to report the new elapsed time at the same regular interval.
This message is meaningless when the clocker is not running, since it always
resets to 0 anyway when stopped.

Attributes
Name Type g/s Description
active int Turns the clocker object on and off.
autostart int If turned on (non-zero) the clocker object will begin running automatically at the
time specified with the autostarttime attribute.
autostarttime atom If the autostart attribute is enabled (non-zero) the clocker object will begin
running automatically at the time specified with the this attribute. The autostart
operates as a timepoint object that is internal to the clocker object.
defer float Turn this on to send output in the low-priority queue.
interval atom Sets the The time interval at which the clocker object sends out a bang. Time can
be specified in any of the time formats used in Max.
quantize atom Send output only on the specified time-boundary if appropriate. This is achieved
by making internal adjustments to the times used for sending output. The
quantization can be specified in the following time formats: bars.beats.units, ticks
or note values.
transport symbol This attribute names a master time transport. If the time is specified using a
'relative' unit (for example: ticks, bars.beats.units, or notevalues), then the named
transport is used to determine delay times based on tempo, time-signature, and
other related information.

Information for box attributes common to all objects

Examples

See Also
Name Description
counter Keep count based on bang messages
cpuclock Retrieve the CPU time
delay Delay a bang
setclock Create and control an alternative clock
tempo Output numbers at a metronomic tempo
transport Control a master clock
uzi Send many bang messages
closebang
Send a bang on close

Description
Sends a bang whenever the patcher window within which it resides is closed.

Arguments
None.

Messages
bang There are no inlets. Output occurs when the patcher window is closed.
closebang TEXT_HERE

Information for box attributes common to all objects

Output
bang: Sent automatically when the patcher window is closed.

Examples

Stop a process when window is about to be closed ...or turn off held notes and sustain pedal

See Also
Name Description
active Send 1 when patcher window is active, 0 when inactive
button Blink and send a bang
freebang Send a bang when a patcher is freed
loadbang Send a bang when a patcher is loaded
loadmess Send a message when a patch is loaded
coll
Store and edit a collection of data

Description
Allows for the storage, organization, editing, and retrieval of different messages.

Arguments
Name Units Type Opt Description
name symbol opt Determines the named context of the coll object. All coll objects that share the
same name share their contents. When a patch containing a named coll is loaded,
Max will search for a file that matches the name; if found, the file is automatically
loaded.
no-search any opt An optional nonzero value as a second argument will prevent the coll object from
searching for a file with the named symbol.

Messages
bang See the next listing.
int index [int] The number refers to the address of a message stored in coll. If a message is
stored at that address, the stored message is output.
float index [float] The number refers to the address of a message stored in coll. If a message is
stored at that address, the stored message is output.
list index [int] The first value is used as the address (the storage location within coll) at which to
data [list] store the remaining items in the list. The address will always be stored as an int.
anything index [any] See the symbol listing.
assoc address name [symbol] Associates a symbol with the numeric address, provided that the number address
data index [int] already exists. After association, any reference to that symbol will be interpreted as
a reference to the number address. Each number address can have only one
symbol associated with it.
deassoc address name [symbol] Removes the association between a symbol and the number address. The symbol
data index [int] will no longer have any meaning to coll.
delete index [any] Removes the data at the address provided. If the specified address is numeric, all
higher numbered addresses are decremented by 1.
clear Clear all data
(mouse) Double-click on the coll object to display the contents as text in an editing
window. The data can be manually edited within this editor.
dump Sends all of the stored addresses out the 2nd outlet and all of the stored messages
out the 1st outlet, in the order in which they are stored. A bang is sent out the 4th
outlet when the dump is completed.
end Sets the pointer (as used by the goto, next, and prev messages) to the last
address.
goto index [list] Sets the pointer (as used by the goto, next, and prev messages) at a specific
address, but does not trigger output. If the specified address does not exist, the
pointer is set at the beginning of the collection. Data will be output in response to
a subsequent bang, next, or prev message.
filetype filetype [symbol] Sets the file types which can be read and written into the coll object. The message
filetype with no arguments restores the default file behavior.
flags save-setting [int] Sets the flags used to save its contents within the patch that contains it. The
unused [int] message flags 1 0 notifies the object to save its contents as part of the patcher
file. The message flags 0 0 causes the contents not to be saved.
insert index [int] Inserts the message at the address specified by the number, incrementing all equal
data [list] or greater addresses by 1 if necessary.
insert2 index [int] See the insert listing.
data [list]
length Counts the number of entries contained in the coll and sends the number out the
1st outlet.
next Sends the address and data stored at the current address, then sets the pointer to
the next address. If the pointer is currently at the last address in the collection, it
wraps around to the first address. If the address is a symbol rather than a number,
0 is sent out the second outlet.
nstore index [int] Stores the message at the specified number address, with the specified symbol
association [symbol] associated. This has the same effect as storing the message at an int address, then
data [list] using the assoc message to associate a symbol with that number.
max maximum [int] Return the highest numeric index
merge index [int] Appends data at the end of the data found at the specified index. If the address
data [list] does not yet exist, it is created.
nth index [int] Returns the data element found at a specific position in the stored list and send it
position [int] out the first outlet. As an example, nth 75 2 will output the second item in the list
stored at address 75.
nsub index [int] Replaces a data element with a new value. As an example, nsub 2 4 7 replaces
position [int] the fourth element of address 2 with the value 7. Number values and symbols can
data [any] both be substituted in this manner.
min minimum [int] Return the lowest numeric index
prev Sends the address and data stored at the current address, then sets the pointer to
the previous address. If the pointer is currently at the first address in the
collection, it wraps around to the last address. If the address is a symbol rather
than a number, 0 is sent out the second outlet.
open Opens a data editing window for the current data and bring it into focus.
separate data index [int] Increments the numerical indices for all data whose index is greater than the
provided. This creates an open 'slot' for a subsequent add.
sort sort order (-1 or 1) [int] Sorts the data into a specified order. If the first argument is -1, the items are
entry (-1, 0, or 1) [int] sorted in ascending order. If the first argument is 1, the items are sorted in
descending order.
The second argument specifies what data is used to sort the contents. If the second
argument is -1, the index (either number or symbol) associated with the data is
used. If the second argument is not present or is 0, the first item in the data is
used. If the second argument is 1 or greater, that data elements is used for the
sorting order.
start Sets the pointer (used by the goto, next, and prev messages) to the first address
in the coll.
store index [symbol] Stores the message at an address named by the provided symbol. As an example,
data [list] store triad 0 4 7 will store 0 4 7 at an address named triad.
subsym new name [symbol] Changes the symbol associated with data. The first argument is the new symbol to
old name [symbol] use, the second argument is the symbol associator to replace.
swap index [int] Exchanges the indices associated with two addresses. The data is unchanged, but
index [int] the indexes that they use are swapped.
symbol index [symbol] Retrieves a message stored at the address named by the symbol. If no address is
associated with the symbol, no output is produced.
read filename [symbol] With no arguments, read puts up a standard Open Document dialog box to choose
a file to load. If an argument is provided, the named file is loaded.
readagain Loads the contents of the most recently read file. If no prior file load has occurred,
the request is treated like a read message.
refer object name [symbol] Changes the reference to the data in another named coll object. Changes to the
data stored in any referenced coll will be shared by all other similarly named
objects.
remove index [any] Removes that address and its contents from the collection.
sub index [int] Same as nsub, except that the message stored at the specified address is sent out
position [int] after the item has been substituted.
data [list]
renumber data index [int] Renumbers data entries as consecutive and in increasing order. The optional
argument specifies the starting number address for the data.
renumber2 data index [int] Increment indices by one
wclose Close the data editing window
write filename [symbol] With no arguments, write puts up a standard Open Document dialog box to
choose a filename to write. If an argument is provided, the name is used as a
filename for storage.
writeagain Saves the contents to the most recently written file. If no prior file write has
occurred, the request is treated like a write message.

Attributes
Name Type g/s Description
embed int Toggles the ability to embed the contents of the coll as part of the main. This
value can only be set using the Save Data with Patcher setting in the Object
Inspector. The default behavior is 0 (don't save the data with the patch).

Information for box attributes common to all objects

Output
anything: Messages stored in coll are sent out the 1st outlet. If the message consists of only a single symbol, it will be preceded
by the word symbol when it is sent out.
bang: Out 3rd outlet: Sent out when coll has finished loading in or writing a file of data.

Out 4th outlet: Sent out when coll has finished sending all of the stored addresses and messages in order out the 1st and 2nd
outlets in response to a dump message.
int: Out 1st outlet: The number of messages contained in coll is sent out in response to the length message.
int or symbol: Out 2nd outlet: The address is sent out whenever a message out the 1st outlet is triggered by bang, dump, next,
prev, or sub.

Examples
Complex messages can be recalled with a single number or word... Results for successive next and prev messages

See Also
Name Description
bag Store a collection of numbers
itable Graphic display of a table
jit.cellblock Two-dimensional storage and viewing
table Store and edit an array of numbers
funbuff Store pairs of numbers
Max Basic Tutorial 18: Data Max Basic Tutorial 18: Data Collections
Collections
Max Data Tutorial 3: Gesture Max Data Tutorial 3: Gesture Capture
Capture
colorpicker
Select and output a color

Description
Arguments
None.

Messages
bang Same as double-clicking the object. See the entry for (mouse).
list red [number] A list of numbers can be used to set the RGB or RGBA color components of the
green [number] default color that initially appears in the Color Picker dialog when it is opened. A
blue [number] list of four floating poing numbers in the range 0. - 1.0 will specify the default
alpha [number] color in RGBA format. For compatibility, a list of three integers in the range 0 -
255 will specify the color in the old style RGB format.
(mouse) Double-clicking the object opens the Color Picker dialog box. If the patcher is
unlocked, hold down the Command key on Macintosh or the Control key on
Windows while double-clicking to open the dialog.

Attributes
Name Type g/s Description
compatibility int Sets the output format used by the colorpicker object. When set to zero, the
output will be in RGBA format (four floating point numbers in the range 0. - 1.0).
Setting this attribute to 1 (the default) will output RGB format (three integer
values in the range 0 - 255).
currentcolor float Picker Initial Color

Information for box attributes common to all objects

Output
list: After you open the Color Picker dialog box and make a selection, clicking on the OK button will send a list of the RGB
equivalents of the color you selected out the outlet. If you click the Cancel button, no messages are sent.

Examples

Display a color, or retrieve selected RGB color values

See Also
Name Description
panel Colored background area
swatch Select and display RGB colors
combine
Combine multiple items into a single symbol

Description
Combines a list of items into a single symbol. It works similar to pack and sprintf. The behavior can be modified with attributes
that provide number padding and triggered output.

Arguments
Name Units Type Opt Description
inlets anything opt The number of inlets is determined by the number of arguments. Each argument
sets an initial type and value for an item in the list stored by the combine object.
If a number argument contains a decimal point, that item will be stored as a float.
If the argument is a symbol, that item will be stored as a symbol.

Messages
bang Causes combine to send out a list of the items currently stored.
int input [int] The number is stored in combine as an item in a list, with its position in the list
corresponding to the inlet in which it was received. The combined output is then
generated from this list and sent out the outlet.
float input [float] The number is stored in combine as an item in a list, with its position in the list
corresponding to the inlet in which it was received. The combined output is then
generated from this list and sent out the outlet.
list input [list] When a list is sent into any inlet of the combine object, each item in the list is
converted to symbols and stored. Its position in the list corresponds to the inlet in
which it was received. If the list is sent to the left inlet, the combined output is
then generated and sent out the outlet.
anything input [list] The symbol is stored in combine as an item in a list, with its position in the list
corresponding to the inlet in which it was received. The combined output is then
generated from this list and sent out the outlet.

Attributes
Name Type g/s Description
padding int A list that determines the number of zeros to add to a number if appropriate.
triggers int Define a list of inputs that will automatically trigger output (i.e. adding an input to
this list will make the inlet "hot"). A value of -1 will cause the object to trigger
output for any inlet.

Information for box attributes common to all objects

Examples

See Also
Name Description
join Combine items into a list
pack Create a list
pak Output a list when any element changes
sprintf Format a message of words and numbers
transport Control a master clock
comment
Explanatory note or label

Description
comment displays text which is typed into it in order to serve as a label or explanatory text.

Arguments
None.

Messages
append message [list] The word append followed by any message will set the comment object to display
that message after any text which it already contains.
prepend message [list] The word prepend followed by any message will set the comment object to
display that message before any text which it already contains.
set message [list] The word set followed by any message will set the comment object to display that
message.

Attributes
Name Type g/s Description
bgcolor float Sets the background color of the comment box.
bubble int Bubble
def.:0
bubblepoint float Bubble Arrow Point (0-1)
def.:0.5
bubbleside int Sets the side from which the arrow will originate on bubble comments.
def.:1 'Top' =
'Left' =
'Bottom' =
'Right' =
bubbletextmargin int Bubble Text Margin
def.:5
underline int Toggles underlining the comment's text. This value can only be set using the
def.:0 Underline setting in the comment object's Inspector.

Information for box attributes common to all objects

Menu Items
Name Description
Color Choosing the Color... menu item from the Object menu when the object is
selected opens a color picker, permitting adjustment to the appearance of the
comment object.

Output
(visual): comment has no outlets, sends no output, and does not affect patch functionality.

Examples
Elucidate.......... Label......... Make functional (covered with a ubutton)

See Also
Name Description
ubutton Send a bang with a transparent button
textedit Enter text within a patcher
message Send any message
textbutton A user interface button/toggle
Max Data Tutorial 1: Data Max Data Tutorial 1: Data Viewing
Viewing
conformpath
Convert file paths styles

Description
Converts paths between the older colon style formats and the current slash style. It can also be used to conform paths to either
absolute, relative, boot volume relative, or Cycling 74 folder relative types.

Arguments
Name Units Type Opt Description
pathtype symbol opt An optional symbol argument specifies the pathtype to be used as output. The
possible pathtype arguments are:

absolute: Specifies the output of the absolute pathname of the file or folder as a
symbol.

boot: Specifies the output of the pathname of the file or folder relative to the boot
volume as a symbol.

C74: Specifies the output of the pathname of the file or folder relative to the
Cycling 74 folder as a symbol.

ignore: Specifies that no pathtype conversion is performed.

relative: Specifies the output of the pathname of the file or folder relative to the
Max application folder as a symbol.
pathstyle symbol opt An optional symbol argument specifies the pathstyle to be used as output. The
possible pathstyle arguments are:

colon: Specifies that the colon pathstyle is used for output (See description in
Input section for more details).

max: Specifies that the max pathstyle is used for output (See description in Input
section for more details).

native: Specifies that the native pathstyle is used for output (See description in
Input section for more details).

native_win: Specifies that the native_win pathstyle is used for output (See
description in Input section for more details).

Note: The use of the native_win style paths is not advised except for display
purposes.

slash: Specifies that the slash pathstyle is used for output (See description in Input
section for more details).

Messages
anything filepath [symbol] A file name or path as a symbol. The conformpath object converts paths of one
pathstyle (i.e., file paths that use colons or slashes as separators) and/or pathtype
(paths that are absolute, relative, boot volume-relative, or Cycling 74 folder-
relative) to another. It provides a superset of the functionality of the
absolutepath and relativepath objects.
pathstyle pathstyle [symbol] The word pathstyle, followed by a word that specifies a pathstyle, will conform
the output pathname to the chosen styles. The possible styles are:

colon: The colon style will use colons as separators when passing paths between
objects. This style was used in Max versions 4.2 and earlier on Macintoshes Note:
Since the native Macintosh pathstyle is the same as the colon path style, there is
no native_mac pathstyle.

max: (default) The max style will use whatever style the currently running version
of Max uses to pass paths between objects.

native: The native style will use whatever format is used by the currently running
operating system to specify paths. Note: When working with native paths, only
absolute paths will be valid for the operating system.

native_win: The native_win style will use native Windows OS format (i.e.,
backslashes as separators) to specify paths. Note: The use of the native_win
style paths is not advised except for display purposes- In Max, the backslash
character is used as an escape character and could lead to problems if used in
conjunction with message boxes, sprintf, coll, and other objects which parse text
into atoms.

slash: The slash style will use slashes as separators when passing paths between
objects.
pathtype pathtype [symbol] The word pathtype, followed by a word that specifies a pathtype, will conform the
output pathname to the chosen type. The possible types are:

absolute: The absolute type will output the absolute pathname of the file or
folder as a symbol.

boot: The boot type will output the pathname of the file or folder relative to the
boot volume as a symbol. If the file is not relative to the boot file, the
conformpath object will send a zero out the right outlet and send the output path
out the left outlet unchanged.

C74: The C74 type will output the pathname of the file or folder relative to the
Cycling 74 folder as a symbol. If the file is not relative to the Cycling 74 folder, the
conformpath object will send a zero out the right outlet and send the output path
out the left outlet unchanged.

ignore: (default) The ignore type will perform no path type conversion.

relative: The relative type will output the pathname of the file or folder relative to
the Max application folder as a symbol. If the file is not relative to the Max
application folder, the conformpath object will send a zero out the right outlet
and send the output path out the left outlet unchanged.

Information for box attributes common to all objects

Output
int: Out right outlet: If the input file or folder is conformed to specified pathtype and/ or pathtype, the output is 1. if the filepath
cannot be conformed (e.g., if the file is not relative to a requested path type), the output is 0.
symbol: The pathname of the folder or file conformed to the specified pathstyle and/or pathtype.

Examples
Use the getsystem message to Max to automatically conform file pathnames across platforms

See Also
Name Description
absolutepath Convert a file name to an absolute path
opendialog Open a dialog to ask for a file or folder
relativepath Convert an absolute to a relative path
savedialog Open a dialog asking for a filename
strippath Separate filename from a full pathname
cos
Cosine function

Description
Use the cos object to calculate and output the cosine of any given number.

Arguments
Name Units Type Opt Description
initial-value float or int opt Sets the initial value for the cosine function.

Messages
bang Calculates the cosine of the number currently stored. If there is no argument, cos
initially holds 0.
int input [int] Input to the cosine function
float input [float] Input to the cosine function

Information for box attributes common to all objects

Output
float: The cosine of the input.

Examples

See Also
Name Description
acos Arc-cosine function
acosh Hyperbolic arc-cosine function
cosh Hyperbolic cosine function
cosh
Hyperbolic cosine function

Description
Use the cosh object to calculate and output the hyperbolic cosine of any given number.

Arguments
Name Units Type Opt Description
initial-value float or int opt Sets the initial value for the hyperbolic cosine function.

Messages
bang Calculates the hyperbolic cosine of the number currently stored. If there is no
argument, cosh initially holds 0.
int input [int] Input to the hyperbolic cosine function
float input [float] Input to the hyperbolic cosine function

Information for box attributes common to all objects

Output
float: The hyperbolic cosine of the input.
int: The hyperbolic cosine of the input.

Examples

See Also
Name Description
acos Arc-cosine function
acosh Hyperbolic arc-cosine function
cos Cosine function
counter
Keep count based on bang messages

Description
Outputs the current count of bang message constrained to a specified range. Can be set to count up, down, or up-then-down.

Arguments
Name Units Type Opt Description
options int opt If there is only one argument, it sets an initial maximum count value for counter.
If there are two arguments, the first number sets an initial minimum value, and
the second number sets an initial maximum value. If there are three arguments,
the first number specifies the direction of the count, the second number is the
minimum, and the third number is the maximum. If there are no arguments, the
direction is up, the minimum is 0, and the maximum is 2,147,483,647 (the largest
possible 32-bit signed integer).

Messages
bang In left inlet: Sends out the current count of the bang messages received in the left
inlet.

In left-middle inlet: Changes the direction of the count.

In middle inlet: Resets the count to its specified minimum value, which will be
sent out the next time a bang is received in the left inlet.

In right-middle inlet: Resets the count to its specified minimum value, and sends
out that value immediately.

In right inlet: Resets the count to its specified maximum value, which is sent out
immediately.
int input [int] In left inlet: Same effect as bang.

In left-middle inlet: Sets the direction of the count. 0 causes counter to count up,
1 causes it to count down, and 2 causes it to count up and down.

In middle inlet: The number sets the counter to a new value, to be sent out the
next time a bang is received in the left inlet. If the number is less than the current
minimum value, the minimum will be reset to that number. If the number is
greater than the current maximum value, the counter will be set to that number,
but the maximum value actually remains the same and the minimum is set equal
to the maximum.

In middle-right inlet: The number sets the counter to a new value and sends it out
immediately. If the number is less than the current minimum value, the minimum
will be reset to that number. If the number is greater than the current maximum
value, the number is sent out, but the maximum value actually remains the same
and the minimum is set equal to the maximum.

In right inlet: Resets the maximum value sent out by counter. If the number is
less than the current minimum, the maximum is equal to the minimum. If the
minimum is subsequently changed to a value below the maximum value you input,
the counter objects retains the correct maximum value it received through this
inlet. Unlike a bang message, an int in this inlet does not cause the counter object
to output anything.
float input [float] In all other inlets: Converted to int.
dec
In left inlet: Decrements the counter (downward) and sends out the new value,
regardless of the direction in which the object has been set to count ordinarily.
down In left inlet: Sets the counter to count in a downward direction.
carrybang In left inlet: Causes counter to send a bang out the right-middle outlet when the
count is going upward and reaches its maximum limit, and causes counter to send
a bang out the left-middle outlet when the count is going downward and reaches
its minimum limit. (By default, counter sends out the number 1 in those
situations, instead of bang.) The state of the carrybang message is saved along
with the patcher it is used in.
carryint In left inlet: Undoes the effect of a previously received carrybang message. Resets
the counter to send the numbers 1 and 0 out the left-middle and right-middle
outlets (instead of bang) to signal when the counter reaches and leaves its
minimum and maximum values. The state of the carryint message is saved along
with the patcher it is used in.
goto input [int] In left inlet: Same effect as set.
flags carry-mode [int] The flags message followed by two numbers will set the Underflow/Carry Mode
minimum-mode [int] and set the Minimum-Mode resetting capability. If the first number is 0, counter
will output a 1 when it hits the maximum or else output a 0. If the first number is
1, counter will output a bang when it hits the maximum. If the second number is
0, an integer in inlets 3 and 4 will override the minimum count temporarily. If the
second number is 1, an integer in inlets 3 and 4 will change the minimum count
permanently.
inc In left inlet: Increments the counter (upward) and sends out the new value,
regardless of the direction in which the object has been set to count ordinarily.
jam input [int] In left inlet: The word jam, followed by a number, sets the counter to that number
and sends the number out immediately. If the number is outside the minimum
and maximum count range, this message is ignored.
next In left inlet: Same as bang.
max maximum [int] In left inlet: The word max followed by a number, resets the maximum value of
counter to that number. If the number is less than the current minimum value,
the maximum is considered to be equal to the minimum, although the actual
maximum value you set is stored inside the counter object.
min minimum [int] In left inlet: The word min followed by a number, resets the minimum value of
counter to that number, and causes the counter object to set itself to that
number and output immediately. If the number is greater than the current
maximum value, the minimum is set equal to the maximum.
set input [int] In left inlet: The word set, followed by a number, sets the counter to that number,
which will be sent out the next time a bang is received in the left inlet.
setmin minimum [int] In left inlet: The word setmin, followed by a number, sets the counter object's
minimum count without affecting its current count value or causing any output.
state The message state will cause the counter object to report its current state to the
Max window.
up In left inlet: Sets the counter to count in an upward direction.
updown In left inlet: Sets the counter object's direction so that it counts upward until it
reaches the specified maximum, then counts down until it reaches the specified
minimum, then up, then down, and so on.

Attributes
Name Type g/s Description
carryflag int Sets the type of data output from the third outlet (numbers or bangs).
'Numeric' = TEXT_HERE
'Bang' = TEXT_HERE
compatmode int Provides compatibility when importing patches created with versions 3.x and
earlier of Max. When "Ancient" is selected, sending an int to inlets 3 and 4 will
change the min count instead of just resetting it temporarily (which causes the
fourth inlet to behave exactly as thought the min message were sent to the
counter object).
'Current' = TEXT_HERE
'Ancient' = TEXT_HERE

Information for box attributes common to all objects

Output
bang: Out left-middle outlet: If a carrybang message has been received in the left inlet, then when the count is moving
downward and reaches the minimum limit, a bang is sent out (instead of the number 1 which is sent out by default). When the
count leaves the minimum limit, nothing is sent out.

Out right-middle outlet: If a carrybang message has been received in the left inlet, then when the count is moving upward and
reaches the maximum limit, a bang is sent out (instead of the number 1 which is sent out by default). When the count leaves the
maximum limit, nothing is sent out.
int: Out left outlet: When bang, next, inc, dec, or a number is received in the left inlet, the current count is sent out, within the
minimum and maximum limits specified. If the direction of the count is both up and down, the count is folded back in the other
direction when it reaches the specified limits. If the count is in only one direction, up or down, the count is wrapped around to
the opposite extreme when it reaches its limit.

When the direction is up, or up and down, counter, begins counting from the specified minimum value. When the direction is
down, counter begins from the maximum value.

Out left-middle outlet: When the count is moving downward and reaches the minimum limit, the number 1 is sent out. When
the count leaves the minimum limit, 0 is sent out.

Out right-middle outlet: When the count is moving upward and reaches the maximum limit, the number 1 is sent out. When the
count leaves the maximum limit, 0 is sent out.

Out right outlet: An additional count is kept of the number of times counter reaches its maximum limit. Each time the maximum
is reached, that count is sent out.

Examples

Keep track of how many events have occurred, or create a continuous loop

See Also
Name Description
tempo Output numbers at a metronomic tempo
Max Basic Tutorial 11: Procedural Max Basic Tutorial 11: Procedural Drawing
Drawing
cpuclock
Retrieve the CPU time

Description
Accesses a precise value from the system timer. This allows for timing calculations with very high resolution.

Arguments
None.

Messages
bang bang causes the current time to be output. The time value is calculated from when
Max is launched (starting from 0.0).
reset Resets the system timer value to 0.0.

Information for box attributes common to all objects

Output
float: The current time, in milliseconds.

Examples

See Also
Name Description
metro Output a bang message at regular intervals
translate Convert between different units of time.
timepoint Bang at a specific time
transport Control a master clock
when Report the current transport time
ctlin
Output received MIDI control values

Description
Output the value from a specific controller number and MIDI channel.

Arguments
Name Units Type Opt Description
port symbol opt Specifies the port (a-z) from which to receive incoming control messages. If there
is no letter present as an argument, ctlin can receive from all ports.
device symbol opt The name of a MIDI input device may be used as the first argument to specify the
port.
ctrllr-channel list opt Following the (optional) port argument, the next argument is a single controller
number to be recognized by ctlin. If there is no controller number, or if the
argument is a negative number, ctlin recognizes all controller numbers. If a single
controller number is specified in the argument, the outlet which normally sends
the controller number is unnecessary, and is not created.

Following the controller number argument is a single channel number on which to


receive control messages. If the channel argument is not present, ctlin receives
control messages on all channels. In order for this argument to be used, a
controller number argument must precede it. To specify a channel number without
specifying a controller number, use -1 for the controller number.

If a single channel number is specified as an argument, the outlet which normally


sends the channel number is unnecessary, and is not created. If a port has been
specified with a letter argument, channel numbers greater than 16 will be wrapped
around to stay within the 1-16 range. If no port argument is present, a channel
number can be used in place of a letter and number combination. The exact
meaning of the channel number argument depends on the channel offset specified
for each port in the MIDI Setup dialog.

Messages
anything port [list] Performs the same function as port.
(mouse) Double-clicking on a ctlin object shows a pop-up menu for choosing a MIDI port
or device.
(MIDI) ctlin receives its input from a MIDI control change message received from a MIDI
input device.
port port [symbol] The word port, followed by a letter a- z or the name of a MIDI input port or
device, sets the port from which the object receives incoming control messages.
The word port is optional and may be omitted.
set controller [int] The word set, followed by a number from 0 to 127, specifies a single controller
number to be paid attention to by ctlin. This message is appropriate only if a
specific controller number was originally typed in as an argument; it is ignored by
ctlin if no controller number argument was originally typed in.

Information for box attributes common to all objects

Output
int: Out left outlet: The number is the control value of an incoming MIDI control change message.

If a specific controller number is not specified as an argument, the controller number is sent out the 2nd outlet.
If a specific channel number is not included in the argument, the channel number is sent out an additional, right, outlet.

Examples

Control messages can be filtered in a variety of ways

See Also
Name Description
bendin Output MIDI pitch bend values
ctlout Transmit MIDI controller messages
midiin Output raw MIDI data
notein Receive MIDI note messages
rtin Receive MIDI real time messages
xbendin Interpret extra precision MIDI pitch bend values
Max MIDI Tutorial 1: Basic MIDI Max MIDI Tutorial 1: Basic MIDI
ctlout
Transmit MIDI controller messages

Description
Transmits MIDI continuous controller values to a MIDI device.

Arguments
Name Units Type Opt Description
port symbol opt Specifies the port (a-z) for transmitting MIDI control messages. If there is no
argument, ctlout initially transmits out port a, on channel 1. When a port is
specified by a letter argument, channel numbers greater than 16 received in the
right inlet will be wrapped around to stay within the 1-16 range.
device symbol opt The name of a MIDI output device may be used as the first argument to specify the
port.
ctrllr-channel list opt Following the (optional) port argument, the next argument is an initial value for
the controller number to be used in control messages transmitted by ctlout.
Controller numbers are automatically limited between 0 and 127. If there is no
controller number specified, the initial controller number is 1.

Following the controller number argument is an initial value for the channel
number on which to transmit control messages. If the channel argument is not
present, ctlout initially transmits control messages on channel 1. In order for this
argument to be used, a controller number argument must precede it.

If a port has been specified with a letter argument, channel numbers greater than
16 will be wrapped around to stay within the 1-16 range. If no port argument is
present, the channel number specifies both the port and the channel. The exact
meaning of the channel number argument depends on the channel offset specified
for each port in the MIDI Setup dialog.

Messages
int input [int] In left inlet: The number is used as the control value, and ctlout transmits a MIDI
control change message. Numbers are limited between 0 and 127.
(inlet1) controller [int] In middle inlet: The number is stored as the controller number of the control
change messages transmitted by ctlout. Numbers are limited between 0 and 127.
(inlet2) channel [int] In right inlet: The number is stored as the channel number on which to transmit
the control messages.
float input [float] Converted to int.
anything port [list] Performs the same function as port.
(mouse) Double-clicking on a ctlout object shows a pop-up menu for choosing a MIDI port
or device.
port port [symbol] In left inlet: The word port, followed by a letter a-z or the name of a MIDI output
port or device, specifies the port used to transmit MIDI control messages. The
word port is optional and can be omitted.

Information for box attributes common to all objects

Output
(MIDI): There are no outlets. The output is a MIDI control message transmitted directly to the object's MIDI output port.

Examples
Letter argument transmits to only one port......... Otherwise, number specifies both port and channel

See Also
Name Description
bendout Send MIDI pitch bend messages
ctlin Output received MIDI control values
midiout Transmit raw MIDI data
noteout Transmit MIDI note messages
xbendout Format extra precision MIDI pitch bend messages
Max MIDI Tutorial 1: Basic MIDI Max MIDI Tutorial 1: Basic MIDI
cycle
Round-robin messages to outlets

Description
Each incoming number is sent to the next outlet, wrapping around to the first outlet after the last has been reached.

Arguments
Name Units Type Opt Description
outlets int opt Determines the number of outlets. If there is no argument, there will be one outlet.
mode int opt Sets the output mode. If it is non-zero, cycle detects separate "events" and restarts
at the leftmost outlet when a new event occurs. Examples of separate events
include messages with delays between them, and messages triggered by successive
mouse clicks or MIDI events. A stream of items separated by commas in a message
box is considered a single event. If this argument is not present or is 0, the values
cycle through all the outlets, regardless of whether they are attached to separate
events or not.

Messages
bang Sends a bang to the next outlet.
int input [int] The input to be directed to successive outlets.
float input [float] The input to be directed to successive outlets.
list input [list] The stream of ints, floats, or symbols to be directed to successive outlets.
anything input [list] The stream of ints, floats, or symbols to be directed to successive outlets.
thresh mode [int] The word thresh, followed by a number, sets the output mode, in the same way as
the second typed-in argument. If the number is non-zero, cycle will detect
separate "events" and restart at the leftmost outlet whenever a new event occurs.
If the number is 0, each number received will be directed to the next outlet in the
cycle.
set outlet number [int] The word set, followed by a number, specifies an outlet to which the next input
should be directed, if in cycle mode. Outlets are numbered beginning with 0; if an
outlet number is specified that does not actually exist, the message is ignored.
(This message has no effect when cycle is in event-sensitive mode, in which case
each message is always sent out beginning at the leftmost outlet.)
symbol input [symbol] The stream of ints, floats, or symbols to be directed to successive outlets.

Information for box attributes common to all objects

Output
anything: Out any outlet: In cycle mode, each successive int, float, or symbol received, either separately or as part of a list, is
directed to an outlet to the right of the previous number. When the cycle reaches the rightmost outlet, the next number is sent
out the left outlet.

In event-sensitive mode, any int, float, or symbol which is a new event restarts the output at the left outlet.

Examples
Using cycle to get ASCII relief

See Also
Name Description
bucket Pass numbers from outlet to outlet
counter Keep count based on bang messages
spell Convert input to ASCII codes
spray Distribute a value to a numbered outlet
date
Report current date and time

Description
Reports the current date, time, or the number of 1/60th-second ticks since startup.

Arguments
None.

Messages
date Outputs the current date as a list (month/day/year) out the left outlet.
ticks Outputs the current value of Ticks (the number of 1/60ths of a second since
system startup) out the right outlet.
time Outputs the current time as a list (military hours/minutes/seconds) out the
middle outlet.

Information for box attributes common to all objects

Output
int: Out right outlet: When the ticks message is received, date sends the current value of Ticks.
list: Out left outlet: When the date message is received, date sends the current date as a list.
list: Out middle outlet: When the time message is received, date sends the current time as a list.

Examples

For pieces which change slowly, date can be used as a clock to trigger events

See Also
Name Description
clocker Report elapsed time, at regular intervals
timer Report elapsed time between two events
dbtoa
Convert decibels to a linear amplitude

Description
Converts a decibel value to its corresponding linear amplitude.

Arguments
None.

Messages
bang The most recently stored linear amplitude value is sent out the outlet.
int dB-gain [int] Converts a gain/attenuation in deciBels into its corresponding linear amplitude.
float dB-gain [float] Converts a gain/attenuation in deciBels into its corresponding linear amplitude.
list gain-values [list] Converts a list of gain/attenuation values in deciBels into their corresponding
linear amplitude values.
set dB-gain [number] Converts a gain/attenuation in deciBels into its corresponding linear amplitude,
but no output is sent.

Information for box attributes common to all objects

Output
float: A linear amplitude value.

Examples

See Also
Name Description
expr Evaluate a mathematical expression
atodb Convert linear amplitude to decibels
atodb~ Convert linear amplitude to a signal-rate deciBel value
dbtoa~ Convert a deciBel value to linear amplitude at signal rate
decide
Choose randomly between 1 and 0

Description
Outputs random 1 and 0 messages. The output sequence depends on the seed value to determine the sequence of values.

Arguments
Name Units Type Opt Description
seed int opt Sets a "seed" value to cause a specific (reproducible) sequence of pseudo-random
0 and 1 outputs to occur. If there is no argument, the time elapsed since system
startup (an unpredictable value) is used as the seed, ensuring an unpredictable
sequence for output.

Messages
bang Causes a randomly chosen output of 1 or 0.
int input [int] In left inlet: Same as bang.
(inlet1) seed [int] In right inlet: A given "seed" number causes a specific (reproducible) sequence of
pseudo-random 0 and 1 outputs to occur. The number 0 uses the time elapsed
since system startup (an unpredictable value) as the seed, ensuring an
unpredictable sequence of 0 and 1 outputs.

Information for box attributes common to all objects

Output
int: 1 or a 0, chosen at random. With certain seed values, the output may seem at first to follow a "non-random" pattern, but
over the course of many iterations the sequence becomes unpredictable and the balance between 1 and 0 becomes even.

Examples

Simulate a coin toss switch randomly between on and off

See Also
Name Description
drunk Output random numbers within a step range
random Generate a random number
toggle Switch between off and on (0/1)
urn Generate random numbers without duplicates
Max Interface Tutorial 2: Picture Max Interface Tutorial 2: Picture UI Elements
UI Elements
decode
Send 1 or 0 out a specific outlet

Description
Provides hierarchical switching. The right inlet is the master disable switch, while the middle inlet is a submaster enable. The left
inlet can turn on a single outlet provided neither the submaster switch nor the master switch is active.

Arguments
Name Units Type Opt Description
outlets int opt Sets the number of outlets. The default is one outlet.
outlets float opt Converted to int.

Messages
bang The message bang causes decode to output its current state.
int outlet [int] In left inlet: The number specifies an outlet out to turn on, turning off all other
outlets. (Whenever an outlet is turned on that was previously turned off, a 1 is
sent out. Conversely, whenever an enabled outlet is disabled, a 0 is sent out.) The
outlets are referred to by number, beginning with 0 on the left, and numbers
received in the left inlet are automatically limited between 0 and the number of
outlets minus 1.
(inlet1) submaster [int] In middle inlet: Any positive number other than 0 enables all disabled outlets
(sends a 1 out them), unless all outlets are disabled. When 0 is received, decode
turns off all outlets except the one that had previously been on.
(inlet2) master [int] In right inlet: Any positive number other than 0 disables all enabled outlets (sends
a 0 out them). Once all outlets have been disabled in this manner, no outlet can be
enabled until a 0 is received in the right inlet. When a 0 is received, decode re-
enables all outlets that it had just disabled.

Information for box attributes common to all objects

Output
int: When an outlet is enabled that was previously disabled, a 1 is sent out that outlet. When an outlet is disabled that was
previously enabled, a 0 is sent out that outlet. The left outlet is initially enabled.

Examples

decode is a hierarchical on/off switch

See Also
Name Description
bucket Pass numbers from outlet to outlet
gate Pass input to an outlet
toggle Switch between off and on (0/1)
defer
Defer execution of a message

Description
Defers the output of all messages sent through it to the lower priority main thread. This is most applicable when using Overdrive
mode.

Arguments
None.

Messages
bang Same as anything.
int input [int] Same as anything.
float input [float] Same as anything.
list input [list] Same as anything.
anything input [list] Reduces the priority of the message received. This allows other messages (which
may be more time-critical) to execute first.

Information for box attributes common to all objects

Output
anything: Same as the input.

Examples

Overdrive's priority given to MIDI or timing messages can be overridden with defer

See Also
Name Description
deferlow Defer the execution of a message (always)
uzi Send many bang messages
deferlow
Defer the execution of a message (always)

Description
The deferlow object places all incoming messages at the tail of the low priority queue. This is unlike the defer object, however,
which places high priority messages at the front of the low priority queue, and passes low priority messages immediately. The
deferlow object is useful to preserve message sequencing that might otherwise be reversed with the defer object and/or
guarantee that an incoming message will be deferred to a future servicing of the low priority queue even if that message is low
priority itself.

Arguments
None.

Messages
bang The deferlow object places the received message at the tail of the low priority
queue for deferred execution.
int value [int] The deferlow object places the received message at the tail of the low priority
queue for deferred execution.
float value [float] The deferlow object places the received message at the tail of the low priority
queue for deferred execution.
list args [list] The deferlow object places the received message at the tail of the low priority
queue for deferred execution.
anything args [list] The deferlow object places the received message at the tail of the low priority
queue for deferred execution.

Information for box attributes common to all objects

Output
anything: Same as the input.

Examples

Prevent a stack overflow in a feedback loop with deferlow

See Also
Name Description
defer Defer execution of a message
delay Delay a bang
uzi Send many bang messages
delay
Delay a bang

Description
Holds a bang for a specified amount of time before sending it to the next object. This object uses the Max time format syntax, so
the delay time (which is normally specified in milliseconds) can also be set to other fixed or tempo-relative values.

Arguments
Name Units Type Opt Description
time any Sets an initial amount of time to delay a bang received in the left inlet. This time
interval can be either a number which specifies time in milliseconds (e.g. delay
200) or a notevalue (e.g. delay 4nd).

Note: While the delay object lets you specify time in any of Max's standard time
formats, the delaytime attribute argument should be used when specifying time
in any other time unit besides milliseconds or notevalues (e.g. delay @delaytime
11025 samples).

If there is no argument, the initial time interval is 5 milliseconds. Any argument


less than 5 will be set to 5. If notevalue, ticks, or bars.beats.units are specified for
the delay interval, the object will not operate unless the transport is running.

Messages
bang In left inlet: A bang is delayed a certain number of milliseconds before being sent
out the outlet.
int time [int] In right inlet: The number is stored as the number of milliseconds to delay a bang
received in the left inlet. A number received in the right inlet changes the delay
time of the next bang received -- it does not modify the time of a bang currently
being delayed. In left inlet: The number is stored as the number of milliseconds to
delay a bang received in the left inlet. It then automatically sends a bang message
to itself to start the delay.
float time [float] In right inlet: The number is stored as the number of milliseconds to delay a bang
received in the left inlet. A number received in the right inlet changes the delay
time of the next bang received -- it does not modify the time of a bang currently
being delayed. In left inlet: The number is stored as the number of milliseconds to
delay a bang received in the left inlet. It then automatically sends a bang message
to itself to start the delay.
list input [list] In right inlet: A list may be used to specify time in one of the Max time formats.
anything time [list] Same as list.
clock setclock-object-name The word clock, followed by the name of an existing setclock object, sets the
[symbol] delay object to be controlled by that setclock object rather than by Maxs internal
millisecond clock. The word clock by itself sets the delay object back to using
Maxs regular millisecond clock.
stop In left inlet: Stops delay from outputting the bang it is currently delaying.

Attributes
Name Type g/s Description
delaytime atom Sets the delay time for the object. Delay time can be specified in any of the time
formats used in Max.
quantize atom Send output only on the specified time-boundary if appropriate. This is achieved
by making internal adjustments to the times used for sending output. The
quantization can be specified in the following time formats: bars.beats.units, ticks
or note values.
If the applicable time is a 'fixed' unit (for example: ms, seconds, hz, samples, etc.)
then this attribute will have no effect.

Information for box attributes common to all objects

Output
bang: bang received in the left inlet is delayed by the number of milliseconds specified by the right inlet, then is sent out the
outlet. Only one bang at a time can be delayed by delay. If a bang is already in delay when a new bang is received in the left
inlet, the first bang is forgotten.

Examples

Bang is delayed for a certain time..... Can be used to send triggers at specific times

See Also
Name Description
deferlow Defer the execution of a message (always)
pipe Delay numbers, lists or symbols
setclock Create and control an alternative clock
transport Control a master clock
Max Basic Tutorial 19: Timing Max Basic Tutorial 19: Timing
detonate
Play a score of note events

Description
Provides score playback managed using Max messages. The score may be loaded from a MIDI file, or generated using Max
functions. The score is not limited to MIDI notes and values; any information can be stored and played back with detonate.

Arguments
Name Units Type Opt Description
label symbol Supplies a name for the object. Any detonate objects with the same name
argument will share the same event data.

Messages
bang Performs the same function as next.
int parameter [int] After a record message has been received, all numbers received are treated as
parameters of a note event.

In left inlet: The delta time (delay), in milliseconds, since the previous recorded
event. This denotes the "inter-onset interval --the time between the beginnings of
notes--which effectively determines the rhythm in which the events are recorded.
This need not necessarily be the true time in which they occur; detonate believes
any (non-negative) delta time it receives.

When detonate receives a number in the left inlet while recording, it treats the
number as the inter-onset interval (the time elapsed since the previous event),
combines it with the numbers most recently received in the other inlets, and
records them together as a note event. As with most Max objects, the numbers
received in the other inlets are stored for use in subsequent note events triggered
by the receipt of a number in the leftmost inlet.

When detonate has received a follow message, a subsequent number in the 2nd
inlet is treated as the key number (pitch) of a note. If the number is the same as
the pitch of the current note in the score (or a nearby note), the information
recorded for that note--except for the delta time--is sent out.

When detonate is neither recording nor following, a number in the left inlet has
the same effect as the nth message.
(inlet1) pitch [int] In 2nd inlet: The number is treated as the key number (pitch) of the note. If no key
number has ever been received, 60 is used by default.
(inlet2) velocity [int] In 3rd inlet: The velocity of the note. If the velocity is 0--indicating a note-off-- the
event will be treated as the end of an earlier note-on the same key, and will
determine the duration of that earlier note. If no velocity number has ever been
received, it is 64 by default.
(inlet3) duration [int] In 4th inlet: In lieu of a note-off message, a note duration can be supplied as part
of the note-on event. If no duration value has ever been received, and no note-off
event is received to end the note, a duration of 10 milliseconds is used by default.
(inlet4) channel [int] In 5th inlet: The MIDI channel of the note. If no channel has ever been specified,
notes are recorded on channel 1.
(inlet5) track [int] In 6th inlet: The number of a track on which to record the note event. Overdub
recording is not possible with detonate, but each recorded note can be tagged
with a track number for storing separate tracks of notes internally. If no track
number has ever been received, notes are recorded on track 1.
(inlet6) extra [int] In 7th inlet: An "extra" number, which can be used for any purpose, attached to
the note event. This number can be used to provide an additional event parameter,
or to serve as a control value in sync with the note. If no number has ever been
received in this inlet, it is recorded as 0 by default.
(inlet7) extra-2 [int] In right inlet: A second "extra" number.
float parameter [float] Converted to int.
list event-values [list] The first number in the list is used as the delta time, and the other numbers are
treated as if they had been received in the other inlets, respectively from left to
right.
clear Erases the contents of detonate.
(mouse) Double-clicking on the detonate object in a locked patcher opens a graphical
editing window for editing the stored detonate data.
delay offset [int] The message delay followed by a number will move the entire sequence of
recorded note values over with the first note of the sequence beginning at the
specified number.
dump Output all note events
follow pitch [int] Causes detonate to behave like a score reader, comparing incoming pitch
information to the events stored in its score. When a key number is received in the
2nd (pitch) inlet, and it is the same as the pitch of the current note in the score,
detonate sends out the information recorded for that event--except for the delta
time--and then moves ahead to the next note event.
followat pitch [int] The word followat, followed by a pitch, a velocity, and a MIDI channel number,
velocity [int] causes detonate to look for a note event with those attributes in its stored score. If
channel [int] such a note is found, detonate commences score-following from the next event
onward. If not, it simply prints detonate: note not found in the Max window.
export time [int] Same as write.
file-format [int]
import filename [list] Same as read.
next Once playback of the score has been started with a start message, next sends out
the event information (except the delta time) for the current note in the score,
then sends out the delta time for the next note. That delta time can in turn be used
as a delay time before sending another next message to detonate. When next is
received on the last note of the score, there is no note following that one, so a
unique value of -1 is sent out the left outlet to signal the end of the score. If a
next message is received while the score is not being played back, detonate
simply prints the message not playing in the Max window.
nth event [int] The word nth, followed by a number, sends out the note information of the event
in the score indicated by the number. (Events are numbered beginning with 0.) In
place of the delta time for the event, the (cumulative) starting time of the event is
sent out the left outlet.
mute event-parameter [int] Permits the selective muting of note events that meet specific criteria. The word
parameter-value [int] mute must be followed by an event parameter number, a parameter value, and a
mute-flag [int] value of 1 or 0 signifying "mute" or "unmute".
params tolerance [int] The word params, followed by three numbers, modifies the score-following
advance [int] behavior of detonate for cases when the received pitch does not match the pitch
octave-match [int] of the current note in the score. The first number tells detonate how many errors
to tolerate before moving ahead in the score. The second number tells how many
milliseconds to move ahead in the score when too many errors have occurred. The
third number, if non-zero, tells detonate to treat a received pitch that is an octave
too high or too low as if it were a match. For example, the message params 3
1000 1 means to allow three successive errors (with octave displacements
considered to be a match) before moving ahead one second in the score and
resuming. By default, detonate allows 2 errors before moving ahead 200
milliseconds, and does not consider octave pitch displacements to be a match for
the stored note.
open See the (mouse) message.
setparam parameter [number] The message setparam followed by nine list elements will set the parameters of
name [symbol] the object much like entering the information into the object's inspector. The first
display-mode [int] element in the list is a number and signifies which parameter to edit. The
minimum [int] remaining elements are the desired settings listed, from left to right, as the
maximum [int] "parameter name", the "display mode", the "minimum value", the "maximum
default [int] value", the "default value", the "graph interval", the "default scaling", and the
interval [int] "Display MIDI note number" flag.
scaling [int]
note-number [int]
start Begins playing back the score, by simply sending out the first delta time. Once
playback of the score has been started, next messages can be used to send out the
next event information.
record In left inlet: Begins recording numbers coming in the inlets, treating them as
parameters of note events to be recorded. The onset of an event is recorded each
time a number is received in the left inlet.
startat pitch [int] The word startat, followed by a pitch, a velocity, and a MIDI channel number,
velocity [int] causes detonate to look for a note event with those attributes in its stored score. If
channel [int] such a note is found, detonate sends out the delta time of the next event, and a
subsequent next message will refer to that next event. If no such note is found,
detonate simply prints detonate: note not found in the Max window.
stop Stops detonate from recording, playing, or following. It is not necessary to stop
detonate before switching directly between record, start, and follow.
read filename [list] The word read by itself opens a dialog for loading in a standard MIDI file as
contents of the detonate score. If read is followed by the name of a MIDI file in
Max's search path, that file is read in directly without opening a dialog box. The
read message can also be followed by a number which--if non-zero--causes the
time values in the file to be interpreted as milliseconds rather than as bars, beats
and ticks at a certain tempo. If the number is 0 or not present, the times are read
as bars and beats.
restore Same as record.
unmute parameter [int] The word unmute, followed by an event parameter number and a parameter
value [int] value, undoes an earlier mute of the same criterion. For example, unmute 4 10
has the same meaning as mute 4 10 0.
unmuteall Undoes the effects of all previous mute messages.
wclose Closes a previously opened editing window.
write filename [symbol] Opens a dialog for saving the contents of detonate as a standard MIDI file. The
time [int] word write may optionally be followed by up to two numbers. If the first number
file-format [int] is non-zero, the file will be saved with time represented in milliseconds rather
than as bars, beats, and ticks in a certain tempo. If the number is 0 or not present,
the file is saved as beats. The second number indicates the MIDI file format: 0 (all
notes on a single track) o multi-track format, using the track parameter to
separate the notes). The contents of detonate are also saved as part of the patch,
when the patch is saved.
writemax filename [symbol] The message writemax followed by a symbol, saves the patch as a Max text file
named after the symbol.

Attributes
Name Type g/s Description
name symbol Names the object for data sharing. Any detonate object that shares this name will
share event data.

Information for box attributes common to all objects

Output
int: Out left outlet: When a start, startat, or subsequent next message is received in the left inlet, the delta time of the next note
event is sent out. When the last event in the score is played by a next message, there is no note following that one, so a unique
delta time of -1 is sent out to signal that the last note has been played.

When an nth message is received in the left inlet (or an int if detonate is stopped), the starting time of the specified note is sent
out.

Out 2nd outlet: In response to an nth message, or an int while detonate is stopped, or a next message while playing back, or a
matched pitch while following, the pitch of the note is sent out.

Out 3rd outlet: The velocity of the note.

Out 4th outlet: The duration of the note.

Out 5th outlet: The MIDI channel of the note.

Out 6th outlet: The track number of the note.

Out 7th outlet: An extra value associated with the note.

Out right outlet: A second extra value associated with the note.

Examples

Note events are recorded with a delta time, which can be used to play notes back in rhythm

See Also
Name Description
follow Compare a live performance to a recorded performance
seq Sequencer for recording and playing MIDI data
dial
Output numbers using an onscreen dial

Description
Outputs numbers according to its degree of rotation. dial can be set with a certain range, offset, multiplier, as well as numerous
visual settings.

Arguments
None.

Messages
bang Sends out the number currently stored in dial.
int input [int] The number received in the inlet is displayed graphically by dial, and is passed out
its outlet. Optionally, dial can multiply the number by some amount and add an
offset to it before sending it out the outlet.

The dial will also send out numbers in response to clicking or dragging on it
directly with the mouse.
float input [float] Converted to int.
(mouse) The dial object will send out numbers in response to clicking or dragging on it
directly with the mouse.
set input [int] The word set, followed by a number, changes the displayed value of the dial,
without triggering output.
setminmax min-max-values [list] The word setminmax, followed by two numbers, sets the low and high range
values for the dial object. If the number list consists of floating point values, the
floatoutput attribute will automatically be set.
resize input [int] The word resize, followed by a number, changes the size of the dial dial object in
pixels.

Attributes
Name Type g/s Description
bgcolor float Sets the background color of the dial in RGBA format.
clip int Causes the dial object's vertical mouse tracking to operate with or without clipping
def.:1 within the specified output range. Clipping is enabled with a non-zero (the default)
or disabled with a zero.
degrees int Sets the limits of dial object's rotation.
def.:270
fgcolor float Sets the foreground color of the dial in RGBA format.
floatoutput int Toggles floating-point output from the dial object. The default is 0 (off).
def.:0
min float Sets a value that will be added to the dial object's value before it is sent out the
def.:0. outlet. The default is 0.
mult float Sets a multiplier value for the dial object. The object's value will be multiplied by
def.:1. this number before it is sent out the outlet. The multiplication happens before the
addition of the Offset value.
needlecolor float Sets the needle color of the dial in RGBA format.
outlinecolor float Sets the outline color of the dial in RGBA format.
parameter_enable int Parameter Mode Enable
size float Sets the range of the dial object. The default value is 128. Setting the size to 1
def.:128. disables the dial visually (since it can only display one value). Any specified size
less than 1 will be set to 2.
vtracking int Selects the mouse tracking mode.
def.:1 circular: Causes the dial to use circular tracking. Moving the mouse clockwise in a
circular arc relative to the control's center increases the controls value, and
moving it counterclockwise decreases its value.
vertical: (the default) Causes the dial to use vertical tracking. Moving the mouse
up increases the objects value, and moving it down decreases the value.
'Circular' = TEXT_HERE
'Vertical' = TEXT_HERE

Information about attributes available for Parameter-aware objects

Information for box attributes common to all objects

Menu Items
Name Description
Color Choosing the Color... menu item from the Object menu when the object is
selected opens a color picker, permitting adjustment to the appearance of the
dial object.

Output
int: Numbers received in the inlet, or produced by clicking or dragging on dial with the mouse, are first multiplied by the
multiplier, then have the offset added to them, then are sent out the outlet.

Examples

Produce output by dragging onscreen... or use to display numbers passing through

See Also
Name Description
pictctrl Picture-based control
pictslider Picture-based slider control
rslider Display or change a range of numbers
slider Move a slider to output values
Max Basic Tutorial 7: Numerical Max Basic Tutorial 7: Numerical User Interfaces
User Interfaces
dialog
Open a dialog box for text entry

Description
Allows entry of a symbol (as text) and sends it out the outlet when you click on the OK button in the dialog box.

Arguments
Name Units Type Opt Description
label symbol opt Sets the prompt which will appear above the text entry box in the dialog window.

Messages
bang In left inlet: Opens the dialog box with the previous text displayed as the default.
int text [int] See the symbol entry.
(inlet1) output-mode [int] In right inlet: The number 0 sets dialog so that whatever the user types into the
dialog box is sent out as a symbol preceded by the word symbol. A non-zero
number sets dialog so that the typed-in text is sent out exactly as is if it begins
with a word, or preceded by the word list if it begins with a number. If no number
is received, it is considered 0 by default.
float text [float] In left inlet: Same as symbol.
symbol text [symbol] In left inlet: The word symbol, followed by any word, opens a dialog box
prompting the user to enter text. The word following symbol is shown as the
default text. If you want more than one word to appear as the default text, you
must enclose the words in double quotes.

Information for box attributes common to all objects

Output
bang: If the dialog box is cancelled by the user, a bang message is sent out the right outlet.
symbol: If the user clicks OK, dialog makes a symbol out of the entered text (even if it's a number or it's more than one word)
and sends it out its outlet with the word symbol prepended. If a non-zero number has been received in the right inlet, the typed-
in message is sent out as is (without being preceded by the word symbol). This message can be displayed by prepending the
word set and sending it to a message box (as shown in the example). If the user clicks Cancel, nothing is sent out.

Since your patch continues to run while waiting for the user to type text into your dialog box, you can't count on getting the
typed-in symbol immediately after sending the message that opens the dialog box.

Examples

Typed-in message is sent out when OK button is clicked other processes continue while dialog box is open A dialog box is opened
by the dialog object

See Also
Name Description
message Send any message
opendialog Open a dialog to ask for a file or folder
savedialog Open a dialog asking for a filename
sprintf Format a message of words and numbers
dict.deserialize
Create a dictionary from text

Description
Use the dict.deserialize object to create a dictionary from text passed in using Max's dictionary syntax or JSON. Alternatively,
compressed forms of either format may be used.

Arguments
Name Units Type Opt Description
name symbol opt Name of the dictionary to create from serialized input

Messages
anything serialized-dictionary [list] Dictionary syntax, JSON, or a compressed form of either, from which a dictionary
will be created

Attributes
Name Type g/s Description
name symbol Name associated with the created/sent dictionary

Information for box attributes common to all objects

Examples

See Also
Name Description
dict Create and access dictionaries
dict.view View the contents of a dictionary
dict.serialize Convert a dictionary's content to text
Dictionaries Dictionaries
dict.group
Build a dictionary iteratively

Description
Use the dict.group object to build up a dictionary by sending key-value pairs as lists. The key-value pairs will be collected into the
dictionary until a 'bang' is received. The 'bang' will send out the dictionary and start the process over again.

Arguments
Name Units Type Opt Description
name symbol opt Name of the dictionary to create

Messages
bang Send out the dictionary and reset the contents
anything dictionary-or-keyvaluepair A key-value pair will add the key/value to the dictionary or use dictionary syntax
[list] to add more complex structures.

Attributes
Name Type g/s Description
name symbol Name associated with the created/sent dictionary

Information for box attributes common to all objects

Examples

See Also
Name Description
dict Create and access dictionaries
dict.view View the contents of a dictionary
dict.pack Create a dictionary and set its values
zl Process lists in many ways
Dictionaries Dictionaries
dict.iter
Stream the content of a dictionary

Description
Use the dict.iter object to send all key-value pairs out from a dictionary as a series of standard Max list messages.

Arguments
None.

Messages
dictionary name [symbol] Name of the dictionary through which to iterate

Information for box attributes common to all objects

Examples

See Also
Name Description
dict Create and access dictionaries
dict.view View the contents of a dictionary
dict.unpack Extract values from a dictionary
dict.group Build a dictionary iteratively
Stream the content of a dictionary
Dictionaries Dictionaries
dict.join
Merge the content of two dictionaries

Description
Use the dict.join object to merge the content of two dictionaries together into a single dictionary.

Arguments
Name Units Type Opt Description
default-values list opt Dictionary syntax composing a dictionary to be joined with the object's input. See
the "Dictionaries" vignette for more information on dictionary syntax. This
dictionary will be replaced by any dictionaries received at the object's right inlet.

Messages
bang Resend the most recently combined dictionary
dictionary name [symbol] Dictionary from the second inlet is combined with the dictionary from the first
inlet and a new dictionary is sent

Information for box attributes common to all objects

Examples

See Also
Name Description
dict Create and access dictionaries
dict.view View the contents of a dictionary
dict.group Build a dictionary iteratively
dict.slice Split a dictionary into two dictionaries
dict.route Compare dictionaries
Dictionaries Dictionaries
dict
Create and access dictionaries

Description
Use the dict object to create named dictionaries, clone existing dictionaries, and query existing dictionaries to access their data.

Arguments
Name Units Type Opt Description
name symbol opt Name to be associated with this dictionary. If no argument is given, then a unique
name will be generated.
filename symbol opt Name of a JSON file to be imported into this dictionary.

Messages
bang Send a reference to the dictionary from the first outlet.
append ARG_NAME_0 [list] TEXT_HERE
clear Erase the contents of the dictionary, restoring to a clean state.
clone name [symbol] Make a clone of the incoming dictionary. If received at the first inlet, send a
reference to this new clone from the first outlet. Otherwise just clone the
dictionary and don't send it out.
dictionary name [symbol] Make a clone of the incoming dictionary. If received at the first inlet, send a
reference to this new clone from the first outlet. Otherwise just clone the
dictionary and don't send it out.
edit Open the dictionary editor window.
export filename [symbol] Write the dictionary contents to a file. If no path/filename is provided, a dialog
will be presented.
(mouse) Double-click a dict object to open a dictionary editor window.
get key [symbol] Return the value associated with a key to the second outlet.
getkeys alphabetize [bool] Return a list of all the keys in a dictionary to the third outlet. By default the keys
are sorted according to the order in which keys were added to the dictionary. Use
the optional argument to specify alphabetical sorting.
getnames Return a list of all the dictionaries that currently exist to the fourth outlet.
getsize key [symbol] Return the number of values associated with a key to the second outlet.
import filename [symbol] Read the dictionary contents from a file. If no path/filename is provided, a dialog
will be presented.
pull_from_coll coll-name [symbol] Pull the content of a named coll object into the dictionary. The indices in the coll
will become the keys, and the values for those indices the values for the
dictionary's keys.
push_to_coll coll-name [symbol] Push the dictionary's content into a named coll object. The keys in the dictionary
will become the indices in the coll, and the values for those indices the values of
the dictionary's keys.
set key [symbol] Set the value for a key to a specified value.
value [list]

Attributes
Name Type g/s Description
embed int Toggles the ability to embed the contents of the dict as part of the main paitch. If
the embed attribute is set to 1, this overrides this attribute on any other dicts with
the same name.
name symbol Name associated with the dictionary. All dictionaries are passed by reference using
a symbolic name. If you do not provide a name, a unique name will be generated
internally.

Information for box attributes common to all objects

Examples

See Also
Name Description
dict.view View the contents of a dictionary
dict.pack Create a dictionary and set its values
dict.unpack Extract values from a dictionary
dict.group Build a dictionary iteratively
dict.iter Stream the content of a dictionary
dict.join Merge the content of two dictionaries
dict.slice Split a dictionary into two dictionaries
dict.print Post a dictionary to the Max window
dict.route Compare dictionaries
dict.strip Remove keys from a dictionary
dict.serialize Convert a dictionary's content to text
dict.deserialize Create a dictionary from text
Dictionaries Dictionaries
dict.pack
Create a dictionary and set its values

Description
Use the dict.pack object to create a dictionary and set its values using dedicated inlets.

Arguments
Name Units Type Opt Description
name symbol opt Name of the dictionary to create
default-values list opt Dictionary syntax specifying initial keys and values composing the dictionary. See
the "Dictionaries" vignette for more information on dictionary syntax.

Messages
bang Send out the dictionary
int value [int] Define the value for the key associated with the inlet
float value [float] Define the value for the key associated with the inlet
list value [list] Define the value for the key associated with the inlet
anything value [list] Define the value for the key associated with the inlet
dictionary value [symbol] Define the value for the key associated with the inlet

Attributes
Name Type g/s Description
keys symbol List of keys associated with the inlets
name symbol Name associated with the created/sent dictionary
triggers int List of inlets that trigger output of the dictionary

Information for box attributes common to all objects

Examples

See Also
Name Description
dict Create and access dictionaries
dict.view View the contents of a dictionary
Create a dictionary and set its values
dict.unpack Extract values from a dictionary
dict.group Build a dictionary iteratively
dict.iter Stream the content of a dictionary
Dictionaries Dictionaries
dict.print
Post a dictionary to the Max window

Description
Use the dict.print object to post the content of a dictionary to the Max window. For more control over how the printing is
formatted, use dict.iter and print.

Arguments
None.

Messages
dictionary name [symbol] Dictionary whose contents will be posted to the Max window

Information for box attributes common to all objects

Examples

See Also
Name Description
dict Create and access dictionaries
dict.view View the contents of a dictionary
dict.iter Stream the content of a dictionary
dict.serialize Convert a dictionary's content to text
Dictionaries Dictionaries
dict.route
Compare dictionaries

Description
Use the dict.route object to compare two dictionaries. If the dictionary received at the left inlet meets the specifications set by the
dictionary at the right inlet, then pass the dictionary through the left outlet. Otherwise passes the dictionary through the right
outlet.

Arguments
Name Units Type Opt Description
default-values list opt Dictionary syntax composing a dictionary to be compared with the object's input.
See the "Dictionaries" vignette for more information on dictionary syntax. This
dictionary will be replaced by any dictionaries received at the object's right inlet.

Messages
dictionary name [symbol] Dictionary in the first inlet is compared with the reference. Dictionary in the
second inlet sets the reference.

Information for box attributes common to all objects

Examples

See Also
Name Description
dict Create and access dictionaries
dict.view View the contents of a dictionary
dict.slice Split a dictionary into two dictionaries
Dictionaries Dictionaries
dict.serialize
Convert a dictionary's content to text

Description
Use the dict.serialize object to output a serialized form of the contents of dictionary in text format. The text may be Dictionary
Syntax, JSON, or Base64-compressed forms of these formats.

Arguments
None.

Messages
dictionary name [symbol] Name of a dictionary whose content will be serialized

Attributes
Name Type g/s Description
compress int Apply compression to the serialized dictionary
mode symbol Switch between dictionary syntax and JSON format

Information for box attributes common to all objects

Examples

See Also
Name Description
dict Create and access dictionaries
dict.view View the contents of a dictionary
dict.deserialize Create a dictionary from text
Dictionaries Dictionaries
dict.slice
Split a dictionary into two dictionaries

Description
Use the dict.slice object to split a dictionary into two dictionaries. The first dictionary will be created from a set of keys you
provide, sent to the left outlet. The remaining dictionary content will form the second dictionary, sent to the right outlet.

Arguments
None.

Messages
dictionary name [symbol] Name of a dictionary to be split into two dictionaries

Attributes
Name Type g/s Description
keys symbol List of keys to extract from the incoming dictionary to create the two output
dictionaries

Information for box attributes common to all objects

Examples

See Also
Name Description
dict Create and access dictionaries
dict.view View the contents of a dictionary
dict.join Merge the content of two dictionaries
dict.route Compare dictionaries
Dictionaries Dictionaries
dict.strip
Remove keys from a dictionary

Description
Use the dict.strip object to remove the specified keys from a dictionary and return their values through an outlet. Following this
operation, the dictionary will no longer contain the specified keys.

Arguments
Name Units Type Opt Description
keys list opt Keys to be stripped from the dictionary

Messages
dictionary name [symbol] Name of a dictionary from which to strip the specified keys

Attributes
Name Type g/s Description
keys symbol List of keys to strip from incoming dictionaries

Information for box attributes common to all objects

Examples

See Also
Name Description
dict Create and access dictionaries
dict.view View the contents of a dictionary
dict.slice Split a dictionary into two dictionaries
Dictionaries Dictionaries
dict.unpack
Extract values from a dictionary

Description
Use the dict.unpack object to return the values of specified keys through dedicated outlets.

Arguments
Name Units Type Opt Description
name symbol opt Initial name of the dictionary to unpack when receiving a bang message. This will
be replaced by the name of any dictionaries received at the object's inlet.
default-values list opt Dictionary syntax specifying initial keys and values to be fetched. See the
"Dictionaries" vignette for more information on dictionary syntax.

Messages
bang Re-fetch the values from the dictionary last received
dictionary name [symbol] Name of a dictionary from which to fetch values for output

Attributes
Name Type g/s Description
keys symbol Keys

Information for box attributes common to all objects

Examples

See Also
Name Description
dict Create and access dictionaries
dict.view View the contents of a dictionary
dict.pack Create a dictionary and set its values
dict.group Build a dictionary iteratively
dict.iter Stream the content of a dictionary
dict.join Merge the content of two dictionaries
dict.slice Split a dictionary into two dictionaries
dict.print Post a dictionary to the Max window
dict.route Compare dictionaries
dict.serialize Convert a dictionary's content to text
dict.deserialize Create a dictionary from text
Dictionaries Dictionaries
dict.view
View the contents of a dictionary

Description
Use the dict.view object to view the contents of a dictionary.

Arguments
None.

Messages
bang Refresh the display
dictionary name [symbol] Display a dictionary.

Attributes
Name Type g/s Description

Information for box attributes common to all objects

Examples

See Also
Name Description
dict Create and access dictionaries
dict.print Post a dictionary to the Max window
Dictionaries Dictionaries
/
Divide two numbers

Description
Divides two numbers (according to the specified divisor assignment), and then outputs the result.

Arguments
Name Units Type Opt Description
initial int or float opt Sets an initial value for the divisor. If there is no argument, the divisor is set to 1
initially. A float argument causes the numbers to be divided as floats. (Division by
0 is not allowed. Int division by 0 will have the same result as dividing by 1. Float
division by 0 will always cause an output of -2 31 .)

Messages
bang In left inlet: Performs the division with the numbers currently stored.
int input [int] In left inlet: The number is divided by the number in the right inlet, and the result
is sent out the outlet.
(inlet1) divisor [int] In right inlet: The number is stored as the divisor (the number to be divided into
the number in the left inlet).
float input [float] Converted to int, unless / has a float argument.
set input [int] Sets the number to be divided without causing output (bang will output it).
list input and divisor [list] In left inlet: The first number is divided by the second number, and the result is
sent out the outlet.

Information for box attributes common to all objects

Output
float: Only if there is an argument with a decimal point.
int: The two numbers in the inlets are divided, and the result is sent out the outlet.

Examples

Remainder is discarded.......... Floats are truncated before division........... ......unless there is a float argument

See Also
Name Description
!/ Divide input from a number
expr Evaluate a mathematical expression
% Divide two numbers, output the remainder
Max Basic Tutorial 6: Simple Max Basic Tutorial 6: Simple Math in Max
Math in Max
dropfile
Interface for file drag and drop

Description
dropfile defines a region for dragging and dropping files into and then outputs the filepath and filetype upon file input.

Arguments
None.

Messages
(drag) When a file icon is dragged from the Finder or Max File Browser onto a dropfile
object in a locked patcher window, the object checks the file's type against those
that it has been told to accept. If the file is of an acceptable type, the outline of the
dropfile box is highlighted. If the mouse button is released while the cursor is
inside the dropfile box, the dropfile object outputs the type and full pathname of
the file out its outlets.

Attributes
Name Type g/s Description
border float Sets the size in pixels of the dropfile object's border.
def.:2.
bordercolor float Sets the color of the dropfile border in RGBA format.
folderslash int Toggles adding a slash character ( / ) at the end of a folder name when output is
def.:1 triggered.
rounded float Sets the amount in pixels by which to round the corners of the dropfile object.
def.:8.
types symbol The word types, followed by one or more four-letter symbols (e.g., sets the
dropfile object to search for the specified file type(s) and opens a standard dialog
window. Example type codes for files are TEXT for text files, maxb for Max binary
format patcher files, and AIFF for AIFF format audio files. types with no
arguments makes the object accept all file types, which is the default setting.

Information for box attributes common to all objects

Output
any symbol: Out right outlet: The four-letter type code of the acceptable file is sent out the right outlet.
symbol: Out left outlet: When an acceptable file icon has been dragged onto dropfile and the mouse released within its box, the
absolute pathname of the file is sent out as a single symbol. The output pathnames contain slash separators.

Absolute pathnames look like this:

"C:/Max Folder/extras/mystuff/mypatch.pat"

The conformpath object can be used to convert paths of one pathtype and/or pathstyle to another.

When aliases of folders are dragged onto dropfile, the aliases are resolved to create the output path.

If you want to use the dropfile object to cause a file to be read by another object that accepts the read message with a filename
argument, put a prepend read object between dropfile and the object that will open a file, as shown in the example.

Examples
See Also
Name Description
absolutepath Convert a file name to an absolute path
filepath Manage and report on the Max search path
folder List the files in a folder
opendialog Open a dialog to ask for a file or folder
relativepath Convert an absolute to a relative path
strippath Separate filename from a full pathname
drunk
Output random numbers within a step range

Description
Performs a "drunken" walk by outputting random numbers within a specified step range.

Arguments
Name Units Type Opt Description
maximum value int opt Sets the maximum number produced. If this argument is not provided, the
maximum value is set to 128.
step size int opt Sets an initial limit on the size of random steps taken; the absolute value of the
step size will always be less than the absolute value of this limit. If a negative value
is specified as a step size, steps of size zero are never generated. If this argument is
not provided, the step size is set to 2 (movement up or down by no more than 1).

Messages
bang Causes drunk to take a step of random size up or down from its currently stored
value. It updates the stored value and outputs it.
int input [int] The number replaces the stored value and is sent out the outlet.
(inlet1) maximum [int] In middle inlet: The number is stored as the maximum value that can be output by
drunk. If the specified maximum is less than 0 it is set to 0.
(inlet2) step-size [int] In right inlet: The number limits the step size taken in response to a bang in the
left inlet. The step (up or down) will always be less than the absolute value of this
number.
float input [float] Converted to int.
seed random-seed [int] Seeds the object's random generator, which causes a specific (reproducible)
sequence of pseudo-random numbers to occur. The number 0 uses the time
elapsed since system startup (an unpredictable value) as the seed, ensuring an
unpredictable sequence of numbers.
set input [int] The word set, followed by a number, sets the stored value to that number without
triggering output. The stored value is initially set in the center of the total range
(1/2 the maximum value).

Information for box attributes common to all objects

Output
int: The number sent out the outlet is automatically limited between 0 and the specified maximum value, and differs from the
previously stored number by less than the maximum step size.

Examples

Numbers vary aimlessly in small steps taken within the total range
See Also
Name Description
decide Choose randomly between 1 and 0
random Generate a random number
urn Generate random numbers without duplicates
Max Basic Tutorial 10: Random Max Basic Tutorial 10: Random Drawing
Drawing
==
Compare numbers for equal-to condition

Description
Compares two given numbers. If they are equal, outputs a 1, if they are not equal, outputs a 0.

Arguments
Name Units Type Opt Description
comparison- int or opt Sets the initial value, to be compared with a number received in the left inlet. A
value float float argument forces a float comparison.

Messages
bang In left inlet: Performs the comparison with the numbers currently stored. If there
is no argument, == initially holds 0 for comparison.
int input [int] In left inlet: The number is compared with the number in the right inlet. If the two
numbers are equal, == outputs 1. If they are not equal == outputs 0.
(inlet1) comparison-value [int] In right inlet: The number is stored to be compared with a number received in the
left inlet.
float input [float] Converted to int before comparison, unless == has a float argument.
set input [int] Sets the number to be compared without causing output (bang will output it).
list input [number] In left inlet: Compares first and second number, outputs 1 if they are equal, 0 if
comparison-value [number] they are not equal.

Information for box attributes common to all objects

Output
int: 1 if the numbers in the inlets are equal, 0 if they are not equal.

Examples

The numbers are equal...... The numbers are not equal..... Using == 0 as a logical 'not'

See Also
Name Description
select Output bangs based on input matching
split Look for a range of numbers
!= Compare numbers for not-equal-to condition
< Compare numbers for less than condition
<= Compare numbers as less than or equal to
> Compare numbers for greater than condition
>= Compare numbers for greater than or equal to condition
Max Basic Tutorial 19: Timing Max Basic Tutorial 19: Timing
error
Report Max errors

Description
Listens for and reports Max errors as message output. This will allow for error management in cases where it is not appropriate to
display the Max window.

Arguments
None.

Messages
int enable [int] The error object allows you to catch errors and output them as Max messages. A
non-zero number starts the error object "listening" for Max errors. The error
object must be listening to produce any output. A 0 turns off listening.
float enable [float] Converted to int.
error message [list] The word error followed by any message will send that message out the outlet.

Information for box attributes common to all objects

Output
symbol: Any Max error generated by any object in any patch while the error object is listening is sent out the outlet preceded by
the symbol error. The messages are output as individual words so you can check for specific failures.

If you want to strip off the initial error message from the object's output, use a routeerror object. If you want to use the error
object's output as a message, put a prependread object between routeerror and the object that will process the error message.

Examples

Intercept error messages

See Also
Name Description
print Print any message in the max window
expr
Evaluate a mathematical expression

Description
Evaluate an expression using a C-like language. Variables and operators are used to create output values.

Arguments
Name Units Type Opt Description
expression list The argument to the expr object is a mathematical expression composed of
numbers, arithmetic operators such as + or *, comparisons such as < or >, C
functions such as min () or pow (), names of table objects, and changeable
arguments ($i, $f, and $s) for ints, floats, and symbols received in the inlets.
constant number Numbers can be used as constants in the mathematical expression.
inlet-format symbol Changeable arguments that specify data formats associated with an inlet are
described using a combination of a data type ($i or $f) and an inlet number
(example: $i2). The argument will be replaced by numbers received in the
specified inlet.
table-info $s Changeable arguments that specify accessing data from a table are described using
the argument $s and an inlet number which is replaced by the name of a table to
be accessed. The argument should be immediately followed by a number in
brackets specifying an address in the table. (Examples: $s2[7] or $s3[$i1].)
(other) symbol The expr object understands the following arithmetic operators: +, -, *, /, %.
Other operators are ~ (one's complement), ^ (bitwise exclusive or), &, &&, |, ||,
and ! (not).

Messages
bang In left inlet: Evaluates the expression using the values currently stored.
int input [int] The number received in each inlet will be stored in place of the $i or $f argument
associated with it. (Example: The number in the second inlet from the left will be
stored in place of the $i2 and $f2 arguments, wherever they appear.)
(inlet1) input [int] See the int listing.
(inlet2) input [int] See the int listing.
(inlet3) input [int] See the int listing.
(inlet4) input [int] See the int listing.
(inlet5) input [int] See the int listing.
(inlet6) input [int] See the int listing.
(inlet7) input [int] See the int listing.
(inlet8) input [int] See the int listing.
(inlet9) input [int] See the int listing.
float input [float] The number in each inlet will be stored in place of the $f or $i argument
associated with it. The number will be truncated by a $i argument.
(inlet1) input [float] See the float listing.
(inlet2) input [float] See the float listing.
(inlet3) input [float] See the float listing.
(inlet4) input [float] See the float listing.
(inlet5) input [float] See the float listing.
(inlet6) input [float] See the float listing.
(inlet7) input [float] See the float listing.
(inlet8) input [float] See the float listing.
(inlet9) input [float] See the float listing.
set input [list] If the word set precedes the items of a list received in the left inlet, the list of
numbers are treated as if each had come in a different inlet, replacing the stored
value with the new value. However, the expression is not evaluated and nothing is
sent out the outlet. If there are fewer numbers in the message than there are
inlets, the stored value in each remaining inlet stays unchanged.
sm1 table [list] See the symbol listing.
sm2 table [list] See the symbol listing.
sm3 table [list] See the symbol listing.
sm4 table [list] See the symbol listing.
sm5 table [list] See the symbol listing.
sm6 table [list] See the symbol listing.
sm7 table [list] See the symbol listing.
sm8 table [list] See the symbol listing.
sm9 table [list] See the symbol listing.
symbol table [list] The word symbol, followed by the name of a table, will be stored in place of the
$s argument associated with that inlet, for accessing values stored in the table
object.
list input [list] The items of a list received in the left inlet are treated as if each had come in a
different inlet, and the expression is evaluated. If the list contains fewer items than
there are inlets, the most recently received value in each remaining inlet is used.
Any of the above messages in the left inlet will evaluate the expression and send
out the result. If a value has never been received for each changeable argument,
that value is considered 0 when the expression is evaluated. The number of inlets
is determined by how many changeable arguments are typed in. The maximum
number of inlets is 9.

Information for box attributes common to all objects

Output
float: The output is the result of the evaluated expression.
int: The output is the result of the evaluated expression.

Examples

Combine many calculations into one object, even using functions not available in other objects

See Also
Name Description
if Conditional statement in if/then/else form
vexpr Evaluate a math expression for a list
round Round to a value
Max Basic Tutorial 22: Designing Max Basic Tutorial 22: Designing Equations
Equations
filedate
Report the modification date of a file

Description
Arguments
None.

Messages
anything pathname [list] Outputs the modification date of a provided file path.

Information for box attributes common to all objects

Output
list: Sends the date that the file was last changed as a list (month, day, year, hours, minutes and seconds).

Examples

filedate displays how recently a file has been changed

See Also
Name Description
date Report current date and time
filein Read and access a file of binary data
filepath Manage and report on the Max search path
folder List the files in a folder
opendialog Open a dialog to ask for a file or folder
filein
Read and access a file of binary data

Description
filein reads a file of binary data and outputs the data at various points in the file given the appropriate input.

Arguments
Name Units Type Opt Description
filename symbol opt Specifies a filename to be read into the filein object automatically when the patch
is loaded.
spool symbol opt A second argument of the word spool will cause the file to be accessed from disk
rather than read into memory.

Messages
int offset [int] Specifies a byte offset in a binary file, and outputs the data stored at that point in
the file.
(inlet1) offset [int] In middle inlet: The 16-bit word contained at that byte offset in the file is sent out
the left outlet as an unsigned (short) integer.
(inlet2) byte-offset [int] In right inlet: The 32-bit word contained at that byte offset within the file is sent
out the left outlet as an unsigned (long) integer.
fclose Closes the file being read, making filein no longer respond to int or list messages.
spool filename [symbol] Displays a standard file dialog to select a file, which will be accessed from disk
whenever an int is received. If the word spool is followed by a filename found in
Max's search path, that file will be automatically pointed to for future access. This
method of accessing a file occupies less RAM, but does not output data
immediately at interrupt level in response to an int message.
read filename [symbol] Displays a standard file dialog to select a file to be read into memory. If the word
read is followed by a filename found in Max's search path, that file will be
automatically read into memory.

Information for box attributes common to all objects

Output
bang: Out middle outlet: When a number greater than or equal to the number of bytes in the file is received in an inlet, a bang is
sent out signifying that the end of the file (EOF) has been reached.

Out right outlet: Signifies that a read or spool operation has been completed. This bang indicates that the file has been accessed
successfully and that filein is ready to receive int messages.
int: Out left outlet: An unsigned integer representing the 8, 16, or 32 bits stored in the file at the location specified by the input
int.

Examples
Output the content of a file in 8-, 16-, or 32-bit chunks

See Also
Name Description
text Format messages as a text file
filepath
Manage and report on the Max search path

Description
Provides access to the Max search path, and allows modification to the search path used by a patch.

Arguments
Name Units Type Opt Description
path-type symbol Specifies one of the Max search path types (search, startup, help, action, or
default)
preference int opt A number greater than zero specifies a slot in the Preferences file. If the argument
is 0 or no number is supplied, the path will not be saved in the Preferences file.

Messages
bang bang causes the currently saved path name(s) to be output as a list.
append folder [list] The word append, followed by a symbol which specifies a folder, adds the folder
subfolder-flag [int] to the list of paths (but does not save it in the Preferences file). An optional integer
subfolder flag will also add any subfolders when set to 1.
clear input [int] This method is obsolete. Currently, it has no effect.
set pathtype [list] The word set, followed by the name of a Max search path type (search, startup,
subfolder-flag [int] help, action, or default), sets the current search path to the type specified. An
optional integer subfolder flag will also add any subfolders when set to 1.
revert Causes the pathnames to be reset to the last set of Max file preferences to be
saved.

Information for box attributes common to all objects

Output
symbol: The currently stored path name in response to a bang.

Examples

Use filepath to check your search path or temporarily set search path slots for a patch

See Also
Name Description
conformpath Convert file paths styles
filedate Report the modification date of a file
folder List the files in a folder
opendialog Open a dialog to ask for a file or folder
filewatch
Watch a file for changes

Description
Watch a specific file and reports a bang whenever that file is altered.

Arguments
Name Units Type Opt Description
filename symbol opt An optional symbol argument specifies the file name to watch.

Messages
bang See the int entry.
int flag [int] Turns on the filewatch object. Sending a non-zero number causes the filewatch
object to commence watching the file for changes. Sending a 0 causes the object to
ignore changes to the file.
anything filepath [list] A filepath or filename within the Max search path will set which file is to be
watched by filepath.
stop The stop message functions the same as sending a 0, causing the object to ignore
any file changes.

Information for box attributes common to all objects

Output
bang: When the filewatch object is active, any change to the specified file will cause filewatch to output a bang.

Examples

Max will be notified of any changes in a file

See Also
Name Description
absolutepath Convert a file name to an absolute path
opendialog Open a dialog to ask for a file or folder
relativepath Convert an absolute to a relative path
savedialog Open a dialog asking for a filename
float
Store a decimal number

Description
float can store and output any given floating-point number.

Arguments
Name Units Type Opt Description
initial-value float opt Sets an initial value to be stored in float. If there is no argument, the initial value
is 0.0. A float argument by itself, without the word float, is another way of
creating and initializing a float object.

Messages
bang In left inlet: Sends the stored value out the outlet.
int input [int] Converted to float.
(inlet1) set-input [float] In right inlet: The number replaces the stored value without triggering output.
float input [float] In left inlet: The number replaces the currently stored value and is sent out the
outlet.
send receive-object-name [list] In left inlet: The word send, followed by a name of a receive object, sends the
number stored in the float object to all receive objects with that name, without
sending it out the float object's outlet.
set set-input [float] In left inlet: The word set, followed by a number, replaces the stored value
without triggering output.

Information for box attributes common to all objects

Output
float: A number is stored in float as a single-precision floating point number. The precision possible in the decimal portion of the
number decreases as the integer part increases. Note: Because of the way decimal numbers are stored, a float value saved in a
patcher file might be slightly altered when the file is reopened.

Examples

Output the stored value... Replace stored value and output it..... Initial value is given

See Also
Name Description
int Store an integer value
pv Share data within a patch hierarchy
value Share a number with other objects
Max Basic Tutorial 16: Remote Max Basic Tutorial 16: Remote Messaging
Messaging
flonum
Display and output a number

Description
Display, input, and output floating-point numbers in a number box.

Arguments
None.

Messages
bang Sends the currently displayed number out the outlet.
int input [int] The number received in the inlet is stored and displayed in the number box and
sent out the outlet.
float input [float] The number received in the inlet is stored and displayed in the number box and
sent out the outlet.
max maximum-value [list] The word max, followed by a number, sets the maximum value that can be
displayed or sent out by the number box. The word max by itself sets the
maximum to None (removes a prior maximum value constraint).
min minimum [list] The word min, followed by a number, sets the minimum value that can be
displayed or sent out by the number box. The word min by itself sets the
minimum to None (removes a prior minimum value constraint).
(mouse) Clicking and dragging up and down on the number box with the mouse (when the
patcher window is locked) moves the displayed value up and down, and outputs
the new values continuously.
In the float number box, dragging to the left of the decimal point changes the
value in increments of 1. Dragging to the right of the decimal point changes the
fractional part of the number in increments of 0.01.
When the active patcher window is locked, numbers can be entered into a number
box by clicking on it with the mouse and typing in a number on the computer
keyboard. Typing the Return or Enter keys on Macintosh or the Enter key on
Windows, or clicking outside the number box, sends the number out the outlet.
select The word select will make the number box active so that you can type numbers
straight into it (click on any empty space in a locked patcher to deselect it).
set input [int] The word set, followed by a number, sets the stored and displayed value to that
number without triggering output.

Attributes
Name Type g/s Description
bgcolor float Sets the color for the number box object's displayed/unclicked background.
bordercolor float Sets the color for the number box object's outline.
cantchange int Toggles the ability to disallow changes with the mouse or the computer keyboard.
def.:0 The default is 0 (mouse/keyboard output active).
hbgcolor float Sets the RGBA values for the background of the number box when it is
highlighted or being updated.
htextcolor float Sets the RGBA values for the number values displayed by the number box when
it is highlighted or being updated.
htricolor float Sets the highlight color for the triangle inside the number box object that
indicates that the contents are editable.
maximum atom Sets the maximum value that can be displayed or sent out by the number box.
def.:<none>
minimum atom Sets the minimum value that can be displayed or sent out by the number box.
def.:<none>
mouseup int Toggles the ability to send a number only when the mouse button is released,
def.:0 rather than continuously. The default is 0 (continuous display).
numdecimalplaces int Specifies the number of decimal places used when displaying a value.
def.:0
outputonclick int Toggles outputting a value on mouse click.
def.:0
parameter_enable int Enable parameter mode
textcolor float Sets the color for the number box object's displayed/unclicked number values.
triangle int Toggles the drawing of a triangular arrow pointing to the number in the number
def.:1 box. The default is 1 (draw the triangle).
tricolor float Sets the color for the triangle inside the number box object that indicates that the
contents are editable.
triscale float Scales the size of the triangle drawn in the number box.
def.:1.
Legacy
brgba list (3 ints) brgba is a legacy RGB alias for the bgcolor RGBA attribute. See here for more
information.
frgba list (3 ints) frgba is a legacy RGB alias for the textcolor RGBA attribute. See here for more
information.
rgba2 list (3 ints) rgba2 is a legacy RGB alias for the htextcolor RGBA attribute. See here for more
information.
rgba3 list (3 ints) rgba3 is a legacy RGB alias for the hbgcolor RGBA attribute. See here for more
information.
rgba4 list (3 ints) rgba4 is a legacy RGB alias for the bordercolor RGBA attribute. See here for
more information.

Information about attributes available for Parameter-aware objects

Information for box attributes common to all objects

Menu Items
Name Description
Color Choosing the Color... menu item from the Object menu when the object is
selected opens a color picker, permitting adjustment to the appearance of the
number box.

Output
float: The number displayed in the number box is sent out the outlet. Numbers received in the inlet or typed on the computer
keyboard can exceed the limits of the number box, but the value that gets stored, displayed, and sent out will automatically be
limited to the specified range.
int: The number displayed in the number box is sent out the outlet. Numbers received in the inlet or typed on the computer
keyboard can exceed the limits of the number box, but the value that gets stored, displayed, and sent out will automatically be
limited to the specified range.

Examples

Displays numbers passing through.... Can be used to output numbers


See Also
Name Description
float Store a decimal number
int Store an integer value
Max Basic Tutorial 3: Numbers Max Basic Tutorial 3: Numbers and Lists
and Lists
flush
Output MIDI note-offs for held notes

Description
Outputss note-off messages for any held note-ons. flush keeps track of all note-ons passed through it, and produces note-off
messages for any held notes when it receives a bang message.

Arguments
None.

Messages
bang Immediately sends note-offs for any pitches that have passed through as note-ons
but not as note-offs by sending 0 out its right outlet followed by a pitch value out
its left outlet.
int pitch [int] The number is treated as the pitch value of a pitch-velocity pair and the note is
sent out.
(inlet1) velocity [int] The number is stored as the velocity to be paired with numbers received in the left
inlet.
clear In left inlet: Erases any numbers held by flush, without sending any note-offs.

Information for box attributes common to all objects

Output
int: Out left outlet: The output is the pitch of the note-on or note-off.

Out right outlet: The number is the velocity of the note-on or note-off.

The flush object keeps track of the notes that have passed through it. When a bang is received in the inlet, note-off messages are
provided for any notes that have passed through as note-ons only.

Examples

Make sure all notes are turned off by providing note-offs for held notes

See Also
Name Description
bag Store a collection of numbers
borax Report note-on and note-off information
makenote Generate a note-on/note-off pair
midiflush Send MIDI note-offs for hanging note-ons
offer Store one-time number pairs
stripnote Filter out note-off messages
sustain Hold note-off messages for release
Max MIDI Tutorial 2: MIDI Note Max MIDI Tutorial 2: MIDI Note Management
Management
folder
List the files in a folder

Description
Outputs the all of the file names in a given folder. This can be especially useful for loading a umenu.

Arguments
Name Units Type Opt Description
pathname symbol opt The absolute path to a folder

Messages
bang Gets the names of all files of a specific type within a specific folder, and outputs
those names to be placed in a message object or a pop-up umenu object.
int input [int] See the bang entry.
anything pathname [list] See the symbol entry.
symbol pathname [symbol] Specifies the pathname of a folder in the search path, and causes the contents of
that folder to be output for storage in a umenu or a message. Input pathnames
can contain slashes, colons, or backslashes as separators.
types typecode [list] The word types, followed by one or more four-letter type codes, sets the file types
that the folder object will look for in the specified folder.

Information for box attributes common to all objects

Output
append: Out left outlet: Immediately following the clear message, each filename in the specified folder is sent out in alphabetical
order preceded by the word append.
clear: Out left outlet: When a pathname or a bang is received in the inlet, the first message that is sent out the left outlet is clear,
which is intended to erase the contents of a receiving message or umenu object.
int: Out right outlet: When a pathname or a bang is received in the inlet, the number of items in the folder is sent out the right
outlet.

Examples

Read in filenames from a folder, then call them up from a pop-up menu

See Also
Name Description
conformpath Convert file paths styles
dropfile Interface for file drag and drop
filein Read and access a file of binary data
filepath Manage and report on the Max search path
opendialog Open a dialog to ask for a file or folder
pcontrol Open and close subwindows
umenu Create and fill a pop-up menu
follow
Compare a live performance to a recorded performance

Description
follow records pitches, or you can give it a MIDI file, in which case it looks at the file's note-ons and ignores other events. When
it is "following" it outputs the index of the last note matched.

Arguments
Name Units Type Opt Description
filename symbol opt The argument is the name of a file containing a previously recorded sequence, to
be read into follow automatically when the patch is loaded.

Messages
bang Starts playing back the sequence stored in follow.
int input [int] When follow is recording, the numbers received in its inlet are recorded as a
sequence. The numbers may be bytes of MIDI messages (from midiformat or
midiin), exactly as with the seq object. However, follow differs from seq in its
ability to record individual integers; with follow you can record notes as a single
pitch value. Whether the performance is recorded as complete MIDI messages or
just as note-on pitches, follow can effectively step through the note-on pitch
numbers later, when following a performance.
(inlet1) input [int] When follow is following, numbers received in its inlet are compared to the
numbers recorded in the sequence. When a number is received that matches the
number in the sequence, follow sends out the index of that number.
float input [float] Converted to int.
append Starts recording at the end of the stored sequence, without erasing the existing
sequence.
delay onset-time (milliseconds) The word delay, followed by a number, sets the onset time, in milliseconds, of the
[int] first event in the recorded sequence.
dump Calls up the standard Open Document dialog box, so that a previously recorded
sequence or standard MIDI file can be opened as text and displayed in a new
Untitled text window. This in fact has no direct effect on the follow object, but
does allow you to view or edit a sequence, save your changes in a file, then load
the new file into follow with a read message.
follow index [int] The follow message is the main feature that distinguishes follow from seq. In
effect, follow is like a score reader, comparing a live performance with the one
previously stored.

The word follow, and a number, causes follow to begin comparing incoming
numbers to its own stored numbers, beginning at the specified index (the specified
event in its own stored sequence). When follow is following, and a number is
received that matches the number recorded in follow, it sends out the index of
that number.

The follow object is a forgiving score reader, and will try to follow along even if
the incoming numbers do not exactly match the recorded sequence. If a number
arrives that does not match the next number, or either of the two subsequent
numbers in the sequence, follow does nothing. If a number arrives that matches a
number up to two notes ahead in the sequence, follow assumes that the performer
simply missed a note or two, and jumps ahead to the matched number.
next Causes follow to send out the index and the stored number it is currently trying to
match, and move on to the next number.
print Prints the first few events of the recorded sequence in the Max window.
start tempo [int] The word start by itself has the same effect as bang. The word start, followed by a
number, plays the stored sequence at a tempo determined by the number. The
message start 1024 indicates normal tempo. If the number is 512, follow plays
the sequence at half the original recorded speed, start 2048 plays it back at twice
the original speed, and so on.
stop Stops follow from recording, playing, or following. A stop message need not be
received before switching directly from recording to playing, following to
recording, etc.
read filename [list] The word read with no arguments puts up a standard Open Document dialog box
for choosing a sequence file to load into follow. If read is followed by a symbol
filename argument, the named file is located and loaded into follow.
record Starts recording integers received in the inlet.
write filename [list] Opens a standard Save As dialog box to save the follow sequence as a file.

Information for box attributes common to all objects

Output
int: Out left outlet: When follow is following, and the number received in the inlet matches the next number in the stored
sequence (or one of the two numbers after that), the index of the matched number is sent out. The index of the next number is
also sent out when a next message is received.

Out right outlet: When follow receives a bang or a start message, the recorded numbers are played back. When follow is
following, and a next message is received, the next number in the recorded sequence is sent out.

Examples

A note that matches the recorded note can trigger a process, or the notes can be stepped through

See Also
Name Description
seq Sequencer for recording and playing MIDI data
detonate Play a score of note events
Max MIDI Tutorial 4: MIDI Basic Max MIDI Tutorial 4: MIDI Basic Sequencing
Sequencing
fontlist
List system fonts

Description
Outputs a list of system fonts and, optionally, their system identification numbers. Optionally filters the list by font-family.

Arguments
Name Units Type Opt Description
font-type symbol opt Font types (see above) may be used as arguments to specify font types the fontlist
object will recognize.

Messages
bang Sends the names of all currently installed fonts out the fontlist object's outlet as a
series of messages. The messages are formatted for use by the umenu menu
display objects. The list begins with a single line containing the message clear,
followed by single line messages in the form append font-name.

Information for box attributes common to all objects

Output
list: The fontlist object generates a list of installed fonts and, optionally, their system identification numbers.

Examples

See Also
Name Description
umenu Create and fill a pop-up menu
forward
Send messages to specified receive objects

Description
Relays messages to other objects remotely. Unlike the send object, the destination receive object of forward can be changed with
each message.

Arguments
Name Units Type Opt Description
receiver symbol opt Sets the name for the receive object which will receive messages. This name can
later be changed with the send message.

Messages
bang See the anything entry.
int input [int] See the anything entry.
float input [float] See the anything entry.
list input [list] See the anything entry.
anything any message [list] Sends any message to all receive objects which share the name currently referred
to by forward.
send arguments [list] The word send, followed by the name of a receive object, sets the destination for
any subsequent messages received by the forward object. This ability to change
the destination of messages on the fly distinguishes forward from the send object.

Information for box attributes common to all objects

Output
anything: There are no outlets. A message (other than send) received in the inlet of forward is sent out the outlet of each
receive object of the same name, even if the receive is in another patch.

Examples

Using forward to send messages to multiple objects at once... The same thing, with two send objects... The message box can
perform the same function

See Also
Name Description
message Send any message
pattrforward Send any message to a named object
receive Receive messages without patch cords
route Select outlet based on input matching
send Send messages without patch cords
value Share a number with other objects
fpic
Display a picture from a graphics file

Description
Arguments
None.

Messages
(drag) When a image file is dragged from the Max 5 File Browser to an fpic object, the
image will be loaded.
noscale Disable image scaling
(mouse) In an unlocked patcher, you can change the offset of the picture by holding down
the Shift and Command keys on Macintosh or Shift and Control keys on Windows
and dragging on fpic; the current offset of the picture is shown in the Assistance
portion of the patcher window as you drag.
pict filename [list] The word pict, followed by the name of a graphics file in Max's search path, opens
the file and displays the picture, replacing whatever picture was previously
displayed. The fpic object accepts PNG files and, if QuickTime Version 7.1 or later
is installed, other picture file formats that are listed in the QuickTime appendix.
offset horizontal [int] The word offset, followed by two numbers, specifies the number of pixels by
vertical [int] which the left upper corner of the picture is to be offset horizontally and vertically
from the left upper corner of the fpic box. By default the left upper corner of the
picture is located at the left upper corner of fpic (that is, with an offset of 0,0).
With successive slightly different offset messages, a picture can be moved inside
fpic, and fpic can window different portions of a large picture. (In order to give
the appearance of smooth transitions when moving an image, the old image is not
erased when using the offset message. This may cause an undesired appearance if
your picture contains a blank background that doesn't cover up what's beneath it.)
read filename [list] The word read, followed by a symbol which specifies a filename, looks for a
QuickTime graphic file with that name in Max's file search path, and opens it if it
exists, displaying it in a graphic window. If the filename contains any spaces or
special characters, the name should be enclosed in double quotes or each special
character should be preceded by a backslash (\). The word read by itself puts up a
standard Open Document dialog box and displays the common graphics files
supported by QuickTime.
readany filename [list] The word readany, followed by a symbol which specifies a filename, functions in
the same manner as the read message, except that the Open Document dialog box
does not filter its display by the currently supported filetypes.
rect horizontal [int] The word rect, followed by four numbers that specify the size of scaling rectangle
vertical [int] to apply to fit the input image within, loads the graphics file from disc into RAM
width [int] and displays it. The first two numbers specify the placement in the graphic
height [int] window as offset values, and the second two numbers specify the width and height,
in pixels, of the rectangle.

Attributes
Name Type g/s Description
alpha float Sets the transparency of the displayed image. The range is a floating point value in
def.:1. the range 0. (transparent) to 1.0 (opaque).
autofit int Toggles the ability to automatically scale a loaded image file to fit the fpic object's
def.:0 display area.
destrect float Specifies the left-top and bottom-right positions of the loaded graphic image. If
these values do not correspond to the size of the graphic image, the image will be
scaled to fit the current fpic window size.
embed int Toggles the ability to embed the graphic you are using and save it as part of the
def.:0 main patch. The default behavior is 0 (don't save the image with the patcher file).
pic symbol Designates the pathname of the graphic file for the fpic to use.
def.:<none>
xoffset float Specifies the number of pixels by which the upper left corner of the subpatch is to
def.:0. be offset horizontally within the fpic object's viewing window.
yoffset float Specifies the number of pixels by which the upper left corner of the subpatch is to
def.:0. be offset vertically within the fpic object's viewing window.

Information for box attributes common to all objects

Examples

Place a picture in a patch (for the sheer beauty of it)... ...or make it functional by placing ubutton objects over it... Make a slide
show by changing pictures, or move a picture by changing its offset

See Also
Name Description
imovie Play a movie in a patcher window
lcd Draw graphics in a patcher window
matrixctrl Matrix switch control
panel Colored background area
pictctrl Picture-based control
pictslider Picture-based slider control
ubutton Send a bang with a transparent button
freebang
Send a bang when a patcher is freed

Description
Arguments
None.

Information for box attributes common to all objects

Output
bang: Sent automatically when the patcher is freed.

Examples

See Also
Name Description
active Send 1 when patcher window is active, 0 when inactive
button Blink and send a bang
closebang Send a bang on close
loadbang Send a bang when a patcher is loaded
loadmess Send a message when a patch is loaded
fromsymbol
Convert a symbol into numbers/messages

Description
fromsymbol will take the individual characters in a symbol and convert them from a symbol back to numbers/messages.

Arguments
None.

Messages
bang The word bang sent as a part of a symbol will be converted to a message. The
message bang will simply pass through to the output.
int value [int] Any integer will simply pass through to the output.
float value [float] Any float will simply pass through to the output.
anything any symbol [list] Any symbol will be converted to numbers/messages.

Attributes
Name Type g/s Description
separator symbol Define the separator character or symbol to be used when converting the symbol
def.:nothing to a message. The default separator is a space.

Information for box attributes common to all objects

Output
messages, lists, or numbers: A list of numbers or messages which correspond to the contents of the original symbol.

Examples

See Also
Name Description
regexp Use regular expressions to process input
sprintf Format a message of words and numbers
tosymbol Convert messages, numbers, or lists to a single symbol
zl Process lists in many ways
Max Comm Tutorial 2: Serial Max Comm Tutorial 2: Serial Communication
Communication
swap
Swap position of two numbers

Description
Swaps the values of its inlets, preserving right-to-left ordering. The first outlet type is determined by its argument. The second
outlet's type is always a float.

Arguments
Name Units Type Opt Description
initial int or float opt Sets an initial value for the number which is to be sent out the left outlet. If there
is no argument, the initial value is 0. If there is an int argument or no argument,
an int is sent out the left outlet. (The number sent out the right outlet is always a
float.)

Messages
bang In left inlet: Swaps and sends out the numbers currently stored in fswap.
int input [int] If there is a float argument, the numbers are converted to float. If there is an int
argument or no argument, the number received in the right inlet is stored as an
int. See the float entry for more details.
(inlet1) input [int] In right inlet: The number is stored to be sent out the left outlet when a number is
received in the left inlet.
float input [float] In left inlet: The number is sent out the right outlet, then the number in the right
inlet is sent out the left outlet.
(inlet1) input [float] In right inlet: The number is stored to be sent out the left outlet when a number is
received in the left inlet.

Information for box attributes common to all objects

Output
float: The number sent out the right outlet is always a float. The number sent out the left outlet is a float only if there is a float
argument.
int: When a number is received in the left inlet, the number in each inlet is sent out the opposite outlet. If there is an int
argument or no argument, an int is sent out the left outlet.

Examples

Numbers are sent out in reverse order from the order in which they were received

See Also
Name Description
join Combine items into a list
pack Create a list
Swap position of two numbers
unjoin Break a list into messages
unpack Break a list into individual messages
ftom
Convert frequency to a MIDI note number

Description
Converts frequency, given in Hertz, to a MIDI pitch or note number (0-127).

Arguments
Name Units Type Opt Description
format float opt If a float value is present, the ftom object outputs floating-point values. By default,
it outputs int values.

Messages
int frequency [int] A frequency value. The corresponding MIDI pitch value (from 0 to 127) is sent out
the outlet.
float frequency [float] A frequency value. The corresponding MIDI pitch value (from 0 to 127) is sent out
the outlet.
list list of frequencies [list] A list of frequency values. Corresponding MIDI pitch values (from 0 to 127) for
each list item are sent out the outlet.

Attributes
Name Type g/s Description
base float Sets the "base frequency" used when converting frequency values (e.g., A = 440.).
The default is 440.

Information for box attributes common to all objects

Output
float: The MIDI note value that corresponds to the input frequency. When an input frequency falls between two equal tempered
pitches, the value is rounded to the nearest int when ftom is used in its default int mode. When ftom is used in the optional float
mode, the fractional part of the float is included. The fractional part could be used to calculate an additional pitch offset for
applying MIDI pitch bend.
int: The MIDI note value that corresponds to the input frequency. When an input frequency falls between two equal tempered
pitches, the value is rounded to the nearest int when ftom is used in its default int mode. When ftom is used in the optional float
mode, the fractional part of the float is included. The fractional part could be used to calculate an additional pitch offset for
applying MIDI pitch bend.

Examples

Find the MIDI key number to play the same pitch as an MSP oscillator

See Also
Name Description
expr Evaluate a mathematical expression
mtof Convert a MIDI note number to frequency
funbuff
Store pairs of numbers

Description
Stores, manages, and recalls pairs of numbers.

Arguments
Name Units Type Opt Description
filename symbol opt The argument specifies the name of a file to be read into funbuff when the patch is
loaded. Changes to the contents of one funbuff will not affect the contents of
another funbuff object with the same name.

A file for funbuff can also be created using a text editor window, beginning the
text with the word funbuff, followed by a list of space-separated numbers which
specify alternating x and y values. A funbuff that has been saved as a file can be
viewed and edited as text by choosing Open as Text... from the File menu.
Numbers in the form of text can be pasted in from other sources such as the
editing window of a capture object, or even from another program such as a word
processor.

Messages
bang In left inlet: Prints information in the Max window concerning the current status
of the funbuff object's contents: how many elements it contains, the minimum
and maximum x and y values it contains, and its domain and range (the maximum
minus the minimum, for the x and y axes respectively).
int x-value [int] In left inlet: The number is the x value of an x,y pair. If a y value has been received
in the right inlet, the two numbers are stored together in funbuff. Otherwise, the
x value causes the corresponding y value stored in funbuff to be sent out the left
outlet.

If there is no stored x value which matches the number received, funbuff uses the
closest x value which is less than the number received, and sends out the
corresponding y value.
(inlet1) y-value [int] In right inlet: The number is a y value which will be paired with the next x value
received in the left inlet, and stored in funbuff.
float x or y value [float] In either inlet: Converted to int.
clear Erases the contents of funbuff.
delete x-value [int] In left inlet: The word delete, followed by two numbers, looks for such an x,y pair
y-value [int] in funbuff, and deletes it if it exists. If delete is followed by only one number,
only the x value is sought, and deleted if it is present.
copy Copies the current selection (made by using the select message) into the global
funbuff clipboard. The data stored on this clipboard can then be pasted into
another funbuff object using the paste message.
cut Copies the current selection (made by using the select message) into the global
funbuff clipboard and deletes it from the funbuff object. The data stored on this
clipboard can then be pasted into another funbuff object using the paste message.
embed flag [int] The word embed, followed by a non-zero number, causes the funbuff data to be
stored inside the patcher. The default setting is not to store the funbuff data
inside the patcher.
dump In left inlet: Sends all the stored pairs out the middle and left outlets in immediate
succession. The y values are sent out the middle outlet, and the x values are sent
out the left outlet, in alternation. The pairs are sent out in ascending order based
on the x value.
goto index [int] The word goto, followed by a number, sets a pointer to the x value (index)
specified by the number. A subsequent next message will return the y value at the
specified x.
find y-value [int] The word find, followed by a number, will output (out the left outlet) all x values
(indexes) whose y value is equal to the number indicated.
interp x-value [int] In left inlet: The word interp, followed by a number, uses that number as an x
value, measures its position between its two neighboring x values in the funbuff,
and then sends--out the left outlet--the y value that holds a corresponding
position between the two neighboring y values. If the received number is already
the x value in a stored x,y pair, the corresponding y value is sent out. If the
received number exceeds the minimum or maximum x values stored in funbuff,
the y value that's associated with the minimum or maximum x value is sent out. If
the funbuff is empty, 0 is sent out.
interptab value [int] In left inlet: The word interptab, followed by a number and the name of a named
tablename [symbol] table object functions similarly to the interp message (mentioned above), except
that it uses the data in the table as an interpolating function. This allows you to
easily perform non-linear interpolation between consecutive values in a funbuff.
next Finds the x value pointed to by the pointer (or, if the pointer points to a number
not yet stored as an x value, to the next greater x value), and sends the
corresponding y value out the left outlet. Also, funbuff calculates the difference
between that x value and the value previously pointed to by the pointer, sends the
difference out the middle outlet, and resets the goto pointer to the next greater x
value.
max Sends the maximum y value currently stored in the funbuff out the left outlet.
min Sends the minimum y value currently stored in the funbuff out the left outlet.
paste The word paste will copy the contents of the global funbuff clipboard into a
funbuff object. The contents of the clipboard are set using the select, copy and
cut messages. These messages provide a handy way of copying data between
different funbuff objects in any open patchers.
print Prints diagnostic information regarding funbuff 's current state in the Max
window.
select starting-index and range In left inlet: The word select, followed by an two integers representing a starting
[list] index and a range will select a region of the funbuff which can be edited using the
cut, copy and paste messages. For example select 2 3 will select the part of a
funbuff from index 2 through index 5.
set value-pair [list] In left inlet: The word set, followed by one or more space-separated pairs of
numbers, stores each pair as x,y pair.
read filename [symbol] Calls up the Open Document dialog box so that a file of x,y values can be read into
funbuff. If the word read is followed by a symbol, Max looks for a file with that
name (in the file search path) to load directly into the funbuff. The funbuff file
format is described on the next page.
undo The undo message is used to undo the results of the previous cut or paste
message.
write filename [symbol] Calls up the standard Save As dialog box, so that the contents of funbuff can be
saved as a separate file. If the word write is followed by a symbol, the contents of
the funbuff are saved immediately in a file, using the symbol as the filename.

Information for box attributes common to all objects

Output
bang: Out right outlet: When the pointer reaches the end of a funbuff, no numbers are sent out in response to a next message,
but a bang is sent out to notify that the end has been reached.
int: Out left outlet: When an x value is received in the left inlet, the corresponding y value is sent out. (Or, if there is no such x
value yet stored in funbuff, the y value corresponding to the next lesser x value is sent out.) When the word next is received in
the left inlet, funbuff sends out the y value that corresponds to the x value pointed to by its pointer (or, if there is no such x
value, the y value of the next greater x value).

Out middle outlet: When the word next is received in its left inlet, funbuff sends out the difference between the x value pointed
to by its pointer, and the x value previously pointed to, then resets the pointer to the next x value.

Examples

Pairs or lists are stored as x, y pairs an x value alone, or next, sends out a y value... Interpolating between points stored in
funbuff

See Also
Name Description
bline Generate ramps using bang
coll Store and edit a collection of data
Store pairs of numbers
itable Graphic display of a table
line Generate timed ramp
table Store and edit an array of numbers
function
Graphically edit a breakpoint function

Description
Draw or store a set of x, y points as floating-point numbers. The output the entire function is useful as an input for line~. You can
also get an interpolated y value for any x value.

Arguments
None.

Messages
bang Triggers a list output of the current breakpoints from the middle-left outlet
formatted for use by the line~ object. As an example, if the function contained
breakpoints at X = 1, Y = 0; X = 10, Y = 1; and X = 20, Y = 0, the output would be
0, 1 9 0 10. If the optional output mode is enabled, the output would be 0 0 1 9
0 10.

If there are any sustain points in the function, bang outputs a list of all the points
up to the sustain point. Additional points in the function, up to a subsequent
sustain point or the end point, whichever applies, can be output by sending the
next message. See the description of the next and sustain messages for additional
information.
int x-value [int] The value is taken as an X value and outputs a corresponding Y value out the left
outlet. The Y value is produced by linear floating-point interpolation of the
function. If the X value lies outside the first or last breakpoint, the Y value is 0.
float input [float] The value is taken as an X value and outputs a corresponding Y value out the left
outlet. The Y value is produced by linear floating-point interpolation of the
function. If the X value lies outside the first or last breakpoint, the Y value is 0.
list x-value [number] If the list contains two values, a new point is added to the function. The first value
y-value [number] is X, the second is Y.

If the list contains three values, an existing point in the function is modified. The
first value is the index (starting at 0) of a breakpoint to modify, the second is the
new X value for the breakpoint, and the third is the new Y value for the
breakpoint. (If the index number in the list refers to a breakpoint that does not
exist, the message is ignored.)
clear indices [list] The word clear by itself erases all existing breakpoints. The word clear can also be
followed by one or more breakpoint indices (starting at 0) to clear selected
breakpoints.
clearfix The word clearfix clears all fix states (sets them to 0).
clearsustain The word clearsustain clears all sustain states (sets them to 0).
dump receive-name [symbol] Outputs a series of two-item lists, containing the X and Y values for each of the
breakpoints, out the function object's middle-right outlet. An optional symbol
argument can be used to specify a receive objects as a destination.
fix index [number] The word fix, followed by a number specifying the index of a point and 0 or 1,
flag [int] prevents the user from changing the point if the second number is 1, and allows
the user to change the point if the second number is 0. By default, points are
moveable unless clickmove 0 has been sent to disable moving of all points.
getfix point-indices [list] The word getfix. with no arguments, will cause the function object to send a list
all fix points out the object's middle-right outlet. If an index is provided as an
argument, the fix state for that point will be output.
getsustain point-indices [list] The word getsustain. with no arguments, will cause the function object to send a
list all sustain points out the object's middle-right outlet. If an index is provided as
an argument, the sustain state for that point will be output.
listdump receive-name [symbol] Outputs a single list which contains all X and Y values for each of the breakpoints
out the function object's middle-right outlet.An optional symbol argument can be
used to specify a receive objects as a destination.
next The next message continues a list output from the sustain point where the output
of the last bang or next message ended. For instance, if the function contained
breakpoints at (a) X = 1, Y = 0; (b) X = 10, Y = 1; and (c) X = 20, Y = 0, and point
b was a sustain point, a bang message would output 0, 1 9 and a subsequent
next message would output 1, 0 10. After a next message reaches the end point,
a subsequent next message is equivalent to a bang message. next is also
equivalent to a bang when no bang has been sent that reached a sustain point, or
when a function contains no sustain points.
(mouse) You can use the mouse to draw points in a line segment function; the finished
function can then be sent to a line~ object for use as a control signal in MSP.
Clicking on empty space in the function adds a breakpoint, which you can begin to
move immediately by dragging (unless function has been sent the clickadd 0
message). Clicking on a breakpoint allows you to move the breakpoint by dragging
(unless function has been sent the clickmove 0 message). The X and Y values of
the breakpoint are displayed in the upper part of the objects box. Shift-clicking on
a breakpoint deletes that point from the function. Command-clicking on
Macintosh or Control-clicking on Windows on a breakpoint toggles the sustain
property of the point. Sustain points are outlined in white. Whenever an editing
operation with the mouse is completed, a bang is sent out the right outlet.
Points with a Y value of 0 are outlined circles; other points are solid. This allows
you to see at a glance whether a function starts or ends at Y = 0.
nth index [int] The word nth, followed by a number, uses the number as the index (starting at 0)
of a breakpoint, and outputs the Y value of the breakpoint out the left outlet. If no
breakpoint with the specified index exists, no output occurs.
set x-y-coordinate-pairs Given the number of points already defined within function 's graphic editor, a
[list] corresponding list of x-y-coordinate pairs will set the position of each point.
setdomain maximum [float] The word setdomain, followed by a float or int value, sets the maximum
displayed X value, then modifies the X values of all breakpoints so that they
remain in the same place given the new domain.
setrange minimum [number] The word setrange, followed by two float or int values, sets the minimum and
maximum [number] maximum display range for Y values, then modifies the Y values of all breakpoints
so that they remain in the same place given the new range.
sustain index [int] The word sustain, followed by number specifying the index of a point and zero or
flag [int] one, turns that point into a sustain point if the second number is 1, or into a
regular point if the second number is 0. By default, points are regular (non-
sustain). The behavior of sustain points is discussed in the description of the bang
message above. Command-clicking on Macintosh or Control-clicking on Windows
also toggle the sustain property of a point.

Attributes
Name Type g/s Description
autosustain int Toggles setting the sustain point to the one before last point. This feature requires
def.:0 that there are more than two points in the current function. The default is 0 (off).
bgcolor float Sets the display color for the background in RGBA format.
bordercolor float Sets the display color for the function object's border in RGBA format.
clickadd int Toggles a user's ability to create new breakpoints by clicking and dragging with the
def.:1 mouse. This feature is enabled by default.
clickmove int Toggles a user's ability to move existing breakpoints by dragging them with the
def.:1 mouse. This feature is enabled by default.
clicksustain int Click-to-sustain flag
def.:1
domain float Sets the maximum displayed X value.
def.:1000.
legend int Toggles the numerical display (legend) of the function object, displayed when a
def.:1 point is highlighted or updated.
linecolor float Sets the display color for lines in RGBA format.
mousereport int Output mouse information
def.:0
outputmode int Sets the function object's output mode.
def.:0 Normal: When the object receives a bang, it outputs a list of the current
breakpoints formatted for use by the line~ object.
List: When the object receives a bang, it sends its values in single list in which the
first Y value is followed by a 0, followed by any additional Y values and associated
times.
'Normal' = TEXT_HERE
'List' = TEXT_HERE
parameter_enable int Enable parameter mode.
pointcolor float Sets the color for points in the display in RGBA format.
range float Sets the minimum and maximum display ranges for Y values.
def.:0. 1.
sustaincolor float Sets the display color for indicating sustain in RGBA format.
textcolor float Sets the display color for text in RGBA format.
zoom_x float Sets the horizontal zoom for the function object's display. Zoom values are set
def.:0. 1. using a pair of floating point values in the range 0.0 - 1.0.
zoom_y float Sets the vertical zoom for the function object's display. Zoom values are set using
def.:0. 1. a pair of floating point values in the range 0.0 - 1.0.

Information about attributes available for Parameter-aware objects

Information for box attributes common to all objects

Menu Items
Name Description
Color Choosing the Color... menu item from the Object menu when the object is
selected opens a color picker, permitting adjustment to the appearance of the
function object.

Output
bang: Out right outlet: When a mouse editing operation is completed, a bang is sent out.
float: Out left outlet: The interpolated Y value is sent out in response to a float or int X value received in the inlet; or a stored Y
value is sent out in response to an nth message.
list: Out middle-left outlet: When bang is received, a float is sent out for the first stored Y value, followed by a list containing
pairs of numbers indicating each subsequent stored Y value and its transition time (the difference between X and the previous X).
This format is intended for input to the line~ object.

Out middle-right outlet: A series of two-item list s, containing the X and Y values of each of the function object's breakpoints, is
sent out when a dump message is received.

Examples
Send line segment information to line~, or look up (and interpolate) individual Y values

See Also
Name Description
line Generate timed ramp
funnel
Tag data with its inlet number

Description
Identifies the inlet of incoming data. It can be used to store values into a table or coll based on their source, or used to set a
destination with an object such as spray.

Arguments
Name Units Type Opt Description
inlets int opt The first argument sets the number of inlets in the funnel. If there is no argument
there will be two inlets.
offset int opt The second argument specifies an offset for the first inlet number. If no second
argument is present, the inlets are numbered beginning with 0.

Messages
bang In any inlet: The number of the inlet and the stored (most recently received)
number in that inlet are sent out as a two-item list.
int input [int] In any inlet: The number of the inlet and the received number are sent out as a
list.
float input [float] In any inlet: The number of the inlet and the received number are sent out as a
list.
list inputs [list] In any inlet: The number of the inlet is prepended to the list, and the new list is
sent out. In a list floats are not converted to ints. The list may contain ints, floats,
and symbols (provided that the first element of the list is not a symbol).
anything inputs [list] Functions the same as list.
offset offset [int] The word offset followed by a number will offset the numbering of inlets by the
number given.
set inputs [list] In any inlet: The word set followed by a list of numbers which correspond with
the number of inlets, will set the input list of numbers without sending them
through the outputs.

Information for box attributes common to all objects

Output
list: When a number or list is received in any inlet, funnel outputs a list consisting of the inlet number followed the input. funnel
can be useful in conjunction with other objects such as coll, funbuff and table.

Examples

Use funnel to tag incoming data, or to store data into a coll object
See Also
Name Description
listfunnel Index and output list elements
spray Distribute a value to a numbered outlet
gate
Pass input to an outlet

Description
Arguments
Name Units Type Opt Description
outlets int opt Specifies the number of outlets. If there is no argument, there is only one outlet.
initial-state int opt Specifies which outlet is initially open. The default is 0 (none).

Messages
bang Reports the current open outlet (0 if closed) out the left outlet.
int outlet-number [int] The number specifies an open outlet through which to pass all messages received
in the right inlet. A number in the left inlet does not trigger any output.
float outlet-number [float] Converted to int.

Information for box attributes common to all objects

Output
anything: Messages received in the right inlet are passed out the outlet specified by the number in the left inlet. If the number in
the left inlet is 0, or if no outlet number has been received yet, all messages are ignored. If the number in the left inlet is less than
0, messages are sent out the leftmost outlet. If it is greater than the number of existing outlets, messages are sent out the
rightmost outlet.

Examples

Message is passed out the specified outlet.... This one closes the door behind itself

See Also
Name Description
ggate Send input to one of two outlets
gswitch Select output from two inlets
route Select outlet based on input matching
router Route messages to multiple locations
send Send messages without patch cords
switch Accept messages from a specific inlet
Max Basic Tutorial 9: Mouse Max Basic Tutorial 9: Mouse Drawing
Drawing
Max Basic Tutorial 21: Max Basic Tutorial 21: Controlling Data Flow
Controlling Data Flow
gestalt
Retrieve system information

Description
Arguments
None.

Messages
bang bang message causes gestalt to repeat its previous output.
anything selector [symbol] Performs the same function as symbol.
symbol selector [symbol] The symbol message containing a Gestalt selector will return the appropriate
system specific information. Some sample selectors are "sysv" to return the system
version and "qtim" to return the quicktime version.

Information for box attributes common to all objects

Output
int: Out left outlet If there was no error in obtaining the response to a selector to the object, the response is sent out the left
outlet. Binary or hex display and/or the use of the bitwise and operator & may aid in interpreting the response.

Out right outlet: If there was an error in obtaining the response to a selector, an error code is sent out the right outlet. Refer to
Apple developer documentation for a complete list of error codes. If the input selector was undefined, -1 is sent out. If there was
no error, 0 is sent out.

Examples

gestalt can give you info about the system in use and info about hardware features

See Also
Name Description
screensize Output the monitor size
getattr
Query object attributes

Description
Provides a user interface to query attribute values from an object. You can also retrieve a list of all available attributes for the
attached object.

Arguments
Name Units Type Opt Description
attribute symbol opt The attribute to access

Messages
bang Queries the connected object and outputs the current value for the selected
attribute.
getattrlist Dumps all of the available attributes out the rightmost outlet. The list of attributes
is prefaced by the work "attrlist", and can be used to load a menu or verify input.

Attributes
Name Type g/s Description
attr symbol The attribute to be accessed
listen int When set to "1", outputs the current attribute value whenever it changes.
prefix int Adds the attribute name as a prefix to all output values.

Information for box attributes common to all objects

Examples

See Also
Name Description
attrui Inspect attributes
grab
Intercept the output of another object

Description
grab can send a message and extract the result from the receiving object.
Note: The grab object cannot be used to communicate from a send to a receive between Max for Live devices.

Arguments
Name Units Type Opt Description
number-of-outlets int opt The first argument sets the number of outlets, in addition to the right outlet. If
there is no argument, grab has 1 additional outlet.
receive-name symbol opt If a symbol is present as a second argument, the message received in the inlet is
sent to all receive objects named by the symbol, instead of being sent out the right
outlet. In this case the rightmost outlet, which would normally send out the
incoming message if no second argument were present, will not exist.

Messages
bang Performs the same function as anything.
int input [int] Performs the same function as anything.
float input [float] Performs the same function as anything.
list input [list] Performs the same function as anything.
anything input [list] The message is sent out the right outlet, or if a second argument is present the
message is sent to receive objects named by the second argument.
set input [symbol] If a second argument has been typed into grab specifying the name of a receive
object, then the word set, followed by a symbol, specifies the name of a (different)
receive object via which grab can grab messages from remote objects.

Information for box attributes common to all objects

Output
anything: Out right outlet: The right outlet should be connected only to the leftmost inlet of other objects. The message received
in the inlet is sent out to the left inlet of all objects connected to the right outlet. Whatever goes out their outlets, however, is then
intercepted by grab.

Out other outlets: Whatever would normally be sent out the outlets of the objects connected to the right outlet, is sent out the
grab object's outlets instead, in response to a message from grab. Whatever would be sent out the leftmost outlet of the other
objects is sent out the leftmost outlet of grab, and so on. Note: Only the output that is sent out the outlets of other objects can be
intercepted by grab. Other types of output, such as transmission of MIDI messages or printing in the Max window, cannot be
intercepted by grab. Also, grab does not intercept the output of timing objects such as seq, metro, and clocker.

Connecting the right outlet of grab to the inlet of a patcher object, however, will not grab the output of the subpatch. It will
simply grab the output of the inlet object inside the subpatch, which is exactly the same as its input. However, grab can
communicate with remote objects via a receive object named as the second argument to grab.

If a second argument is present, the message received in the inlet is sent directly to receive objects named by the argument
instead of being sent out the right outlet. Any such receive objects should be connected only to the leftmost inlet of other objects.
The rightmost outlet, which would otherwise be used to grab the output of other objects, does not appear if the second argument
is used.

Note that if grab is connected to other objects remotely via numerous receive objects of the same name, the order in which grab
communicates with those other objects is undefined, so the order in which their output will be sent out of the grab object's other
outlets is unpredictable.

Examples
Get an object's output by 'grabbing' it before it comes out the outlet... grab can communicate with any receive object specified by
a set message

See Also
Name Description
preset Store and recall settings
table Store and edit an array of numbers
>
Compare numbers for greater than condition

Description
Compares two values to see if one is greater than a second. Outputs a 1 if the number is greater than or equal to the comparison-
number or 0 if it is greater.

Arguments
Name Units Type Opt Description
initial- number opt Sets the initial value, to be compared with a number received in the left inlet. A
comparison-value float argument forces a float comparison.

Messages
bang In left inlet: Performs the comparison with the numbers currently stored. If there
is no argument, > initially holds 0 for comparison.
int input [int] In left inlet: If the number is greater than the number in the right inlet, > outputs
1. Otherwise, > outputs 0.
(inlet1) comparison-value [int] In right inlet: The number is stored to be compared with a number received in the
left inlet.
float input [float] Converted to int before comparison, unless > has a float argument.
set set-input [int] The word set followed by a number will set the input number to the object without
causing output.

Information for box attributes common to all objects

Output
int: 1 if the number in the left inlet is greater than the number in the right inlet. 0 if the number in the left inlet is less than or
equal to the number in the right inlet.

Examples

The number on the left is greater... The number on the left is not greater

See Also
Name Description
!= Compare numbers for not-equal-to condition
< Compare numbers for less than condition
<= Compare numbers as less than or equal to
== Compare numbers for equal-to condition
>= Compare numbers for greater than or equal to condition
Max Basic Tutorial 19: Timing Max Basic Tutorial 19: Timing
>=
Compare numbers for greater than or equal to condition

Description
Compares two values to see if one is greater than or equal to a second. Outputs a 1 if the number is greater than or equal to the
comparison-number or 0 if it is greater.

Arguments
Name Units Type Opt Description
comparison-value number opt Sets the initial value, to be compared with a number received in the left inlet. A
float argument forces a float comparison.

Messages
bang In left inlet: Performs the comparison with the numbers currently stored. If there
is no argument, >= initially holds 0 for comparison.
int input [int] In left inlet: If the number is greater than or equal to the number in the right inlet,
>= outputs 1. Otherwise, >= outputs 0.
(inlet1) comparison-value [int] In right inlet: The number is stored to be compared with a number received in the
left inlet.
float input [float] Converted to int before comparison, unless >= has a float argument.
set set-input [int] The word set followed by a number will set the input number to the object without
causing output.

Information for box attributes common to all objects

Output
int: 1 if the number in the left inlet is greater than or equal to the number in the right inlet. 0 if the number in the left inlet is less
than the number in the right inlet.

Examples

Is greater than.... or equal to.... Is not greater than or equal to

See Also
Name Description
!= Compare numbers for not-equal-to condition
< Compare numbers for less than condition
<= Compare numbers as less than or equal to
== Compare numbers for equal-to condition
Compare numbers for greater than or equal to condition
Max Basic Tutorial 19: Timing Max Basic Tutorial 19: Timing
gswitch
Select output from two inlets

Description
Arguments
None.

Messages
bang In left inlet: Causes the connection to be made to the other inlet.
int inlet [int] In left inlet: The number specifies which one of the other inlets is to be open. 0
specifies the middle inlet, any number other than 0 specifies the right inlet. The
gswitch icon shows the open inlet.
float inlet [float] In left inlet: Converted to int.
(mouse) Clicking on gswitch causes the connection to be made to the other inlet.

Attributes
Name Type g/s Description
int int Specifies which one of the other two inlets is to be open. The default is 0 (middle
def.:0 inlet).
parameter_enable int Parameter Mode Enable

Information about attributes available for Parameter-aware objects

Information for box attributes common to all objects

Output
anything: If the number in the left inlet is 0, all messages received in the middle inlet are passed out the outlet, and messages
received in the right inlet are ignored. If the number in the left inlet is not 0, messages received in the middle inlet are ignored,
and all messages received in the right inlet are passed out the outlet.

Examples

Specify one of two inlets Any comparison can be used as a criterion

See Also
Name Description
gate Pass input to an outlet
ggate Send input to one of two outlets
pictctrl Picture-based control
receive Receive messages without patch cords
route
Select outlet based on input matching
router Route messages to multiple locations
switch Accept messages from a specific inlet
ggate
Send input to one of two outlets

Description
Switches the right inlet between two output pathways.

Arguments
None.

Messages
bang Causes the connection to be made to the other outlet. Clicking on the graphic
display with the mouse has the same effect.
int outlet [int] The number specifies which one of the two outlets is to be open. 0 specifies the left
outlet, any number other than 0 specifies the right outlet. The graphical icon shows
the open outlet.
float outlet [float] In left inlet: Converted to int.
(mouse) Clicking on gswitch2 causes the connection to be made to the other outlet.

Attributes
Name Type g/s Description
int int Specifies which one of the two outlets is to be open. The default is 0 (left outlet).
def.:0
parameter_enable int Parameter Mode Enable

Information about attributes available for Parameter-aware objects

Information for box attributes common to all objects

Output
anything: Messages received in the right inlet are passed out one of the two outlets. If the number in the left inlet is 0, incoming
messages are sent out the left outlet. If the number in the left inlet is not 0, messages are sent out the right outlet.

Examples

Specify one of two outlets... Any comparison can be used as a criterion

See Also
Name Description
gate Pass input to an outlet
gswitch Select output from two inlets
onebang Gate bangs using a bang
pictctrl Picture-based control
route Select outlet based on input matching
router Route messages to multiple locations
send Send messages without patch cords
switch Accept messages from a specific inlet
Max MIDI Tutorial 1: Basic MIDI Max MIDI Tutorial 1: Basic MIDI
hi
Human Interface (gaming) device input

Description
Provides input from human interface peripherals (i.e. Trackpad, Keyboard, and others).

Arguments
Name Units Type Opt Description
device symbol opt An argument can be used to specify the object for focus on the hi object.

Messages
bang bang message will output the current event queue.
int index [int] An incoming int causes the object to focus on the device in the device list with that
index.
anything device [list] Sending the name of any device to the hi object will set the object to focus on the
specified device.
delta element [int] The word delta, followed by an integer that represents an element of the device
will cause the hi object to report an event from the specified element only if it is
different then the last value that was reported.
clear The message clear will reset all values set using the ignore and delta messages to
their default values.
ignore element [int] The word ignore, followed by an integer that represents an element of the device,
disables event reporting from the specified element.
info The info message causes device information to be output to the Max console.
menu The menu message causes a device list to be output from the right outlet in a
format fit for a umenu object.
poll output-time [float] The word poll, followed by a number, sets the time in milliseconds between
outputs of the event queue. The message poll 0 disables automatic polling.

Information for box attributes common to all objects

Output
list: The object collects data from the selected device and will output all collected data when a bang or a timing trigger from to a
poll message is received. Data is output as a two-element integer list; he first element represents the element of the device to
which the data applies, and the second element represents the data value.

Examples
Affect the pitch and duration of notes

See Also
Name Description
key Report keyboard presses
keyup Report key information on release
Max Comm Tutorial 1: Human- Max Comm Tutorial 1: Human-Interface Devices
Interface Devices
hint
Display hint text

Description
When you mouse over a hint, you'll see a message appear on the screen below the area defined by the hint. The hint object has a
number of messages you can use to change its appearance.

Arguments
None.

Messages
int enable [int] 0 will disable any hinting while a non-zero number will enable it.
float enable [float] Converted to int.
(mouse) When the cursor moves within the hint object's rectangle, its text message will
appear in a colored area beneath the rectangle after the specified delay.
set message [symbol] The word set, followed by any message, will replace the message stored in hint.
This message will be displayed when the mouse is positioned over the hint object
after an interval of time specified by the delay message.

Attributes
Name Type g/s Description
delay int Sets the delay in milliseconds until the hint appears. A value of 0 sets a default
def.:0 delay time, usually about 500 ms.
enabled int Toggles enabling display of hint text.
def.:1

Information for box attributes common to all objects

Output
message: The message stored in the hint object.

Examples

Provide optional hints to UI objects

See Also
Name Description
comment Explanatory note or label
umenu Create and fill a pop-up menu
histo
Create a histogram of numbers received

Description
Records and outputs histogram data of the numbers it receives.

Arguments
Name Units Type Opt Description
size int opt histo takes an optional argument to set the size of the histogram. The default size
is 128 (0-127).

Messages
bang Using the number most recently received in the left inlet, histo reports out the
right outlet how many times that number has been received, and sends the
number itself out the left outlet. If no number has been previously received in the
left inlet, 0 is sent out both outlets.
int count [int] In left inlet: histo keeps count of how many times it has received a number
between 0 and 127 in the left inlet. When a number is received, histo includes it in
the count, sends the number of times that number has been received out the right
outlet, and passes the number itself out the left outlet. Numbers outside the range
0-127 are ignored.
(inlet1) count [int] In right inlet: Has the same effect as a number in the left inlet, except that the
number is not counted by histo.
clear Erases the memory of histo, to begin a new histogram.

Information for box attributes common to all objects

Output
int: Out left outlet: The number received in the inlet.

Out right outlet: The count of the number of times that number has been received.

Examples

Store a histogram of the numbers received display it in a table

See Also
Name Description
anal Make a histogram of number pairs
itable Graphic display of a table
prob Create a weighted transition table
table Store and edit an array of numbers
hover
Report object scripting names

Description
Sends out the scripting names of any object over which the cursor is hovering.

Arguments
None.

Information for box attributes common to all objects

Output
symbol: Out left outlet: When the mouse enters the space over an object with a scripting name, hover outputs the scripting name
of the object out the left outlet.
Out second outlet: When the mouse enters the space over an object without a scripting name, hover outputs the symbol none out
the second outlet.
Out third outlet: When the mouse leaves the space over an object with a scripting name, hover outputs the scripting name of the
object out the third outlet
Out right outlet: When the mouse leaves the space over an object without a scripting name, hover outputs the symbol none out
the right outlet.

Examples

See Also
Name Description
thispatcher Send messages to a patcher
if
Conditional statement in if/then/else form

Description
Evaluates input according to a conditional statement specified in an if-then-else form.

Arguments
Name Units Type Opt Description
if symbol The arguments for the if object start with a conditional statement that uses the
same syntax as expr. The word then follows the conditional statement, which is
then followed by a message expression. After the message expression, there is an
optional else and a second message expression.
if evaluates the conditional expression, and if the result is non-zero, evaluates the
message expression after the word then. Otherwise, it evaluates the second
message expression after the word else if an else message is provided.
then, else symbol Message expressions are similar to what you type into a message box.
$i1, $f1, $s1 symbol You use $i1, $f1, or $s1 instead of $1 for replaceable arguments. The number of
inlets is determined by how many different changeable arguments are typed in.
The maximum number of inlets is 9.
send symbol No commas or semicolons are allowed. Messages can be sent to remote receive
objects by preceding the message expression with send, followed by the name of
the receive object.
out2 symbol The keyword out2 in a message expression creates a second, right outlet for the if
object. If out2 precedes a message expression, the result of the expression is sent
out the right outlet instead of the left outlet.

Messages
bang In left inlet: Evaluates the conditional statement using the values currently stored.
int input [int] The number in each inlet will be stored in place of the $i or $f argument
associated with it, and the expression will be evaluated.
(inlet1) input [int] Replace the $i1 value
(inlet2) input [int] Replace the $i2 value
(inlet3) input [int] Replace the $i3 value
(inlet4) input [int] Replace the $i4 value
(inlet5) input [int] Replace the $i5 value
(inlet6) input [int] Replace the $i6 value
(inlet7) input [int] Replace the $i7 value
(inlet8) input [int] Replace the $i8 value
(inlet9) input [int] Replace the $i9 value
float input [float] The number in each inlet will be stored in place of the $i or $f argument
associated with it, and the expression will be evaluated.
(inlet1) input [float] Replace the $f1 value
(inlet2) input [float] Replace the $f2 value
(inlet3) input [float] Replace the $f3 value
(inlet4) input [float] Replace the $f4 value
(inlet5) input [float] Replace the $f5 value
(inlet6) input [float] Replace the $f6 value
(inlet7) input [float] Replace the $f7 value
(inlet8) input [float] Replace the $f8 value
(inlet9) input [float] Replace the $f9 value
set set-input [list] The word set, followed by one or more numbers, treats those numbers as if each
had come in a different inlet, replacing the stored value with the new value, but
the conditional statement is not evaluated and nothing is sent out the outlet. If
there are fewer numbers in the message than there are inlets, the stored value in
each remaining inlet is left unchanged.
symbol input [symbol] A symbol will be stored in place of the $s argument associated with it. If received
in the first inlet, the expression will be evaluated.

Information for box attributes common to all objects

Output
anything: The message after the then or else portion of the arguments is sent out the outlet. If the word out2 is present as an
argument, there will be two outlets, and messages following out2 will be sent out the right outlet. If the word send is present as
an argument, the word that follows it is the name of a receive object, and the message that follows it will be sent to receive
objects with that name.

Examples

Complex comparisons and results can be described in a single object

See Also
Name Description
!= Compare numbers for not-equal-to condition
< Compare numbers for less than condition
<= Compare numbers as less than or equal to
== Compare numbers for equal-to condition
> Compare numbers for greater than condition
>= Compare numbers for greater than or equal to condition
expr Evaluate a mathematical expression
select Output bangs based on input matching
Max Basic Tutorial 22: Designing Max Basic Tutorial 22: Designing Equations
Equations
imovie
Play a movie in a patcher window

Description
Plays a movie in a user-interface object within the patcher window.

Arguments
None.

Messages
bang Same as resume.
int location [int] Sets the current time location of the movie. If the movie is playing, it will play
from the newly set location. 0 is always the beginning. The end time varies from
one movie to another. (The length message reports the end time location out the
left outlet.)
(drag) When a QuickTIme movie file is dragged from the Max 5 File Browser to a imovie
object, the file will be loaded.
active flag [int] The word active, followed by a non-zero number, makes the movie active (the
default). Followed by a 0, active makes the movie inactive. An inactive movie will
not play or change location.
dispose filename [symbol] Removes all movies from the imovie object's memory. If the word dispose is
followed by the name of a loaded movie, only the named movie will be removed.
clear Has the same effect as dispose with no arguments.
duration Reports the duration of the movie (in milliseconds) from the left outlet.
getduration Reports the end time position of the movie (in QuickTime Time Units) from the
left outlet.
getrate Reports the current rate multiplied by 65536 out the right outlet. Thus, normal
speed is reported as 65536, half speed is reported as 32768, double speed
backward is reported as -131072, etc. If the movie is not playing, the rate is
reported as 0, and if no movie has yet been loaded nothing is sent out.
gettime Reports the current time location of the movie.
length The length message's functionality is equivalent to the getduration message.
loadintoram flag (0 or non-zero) [int] The word loadintoram, followed by a non-zero number, attempts to load the
entire movie into memory, if possible. The default is 0.
next time-units [int] The word next, followed by a number, moves the time location ahead by that
amount. If no number is supplied, next moves the time ahead by 5. (The actual
time meaning of these units varies from movie to movie.)
nextmovie Stops the movie if it is playing, and switches to the movie that was loaded just
prior to the current movie. (The movies are stored in reverse order from the order
in which they were loaded.) If there is no prior movie, nextmovie wraps around
back to the most recently loaded movie. Note that the title of the movie window is
not automatically changed, even though the "current movie" has been changed by
nextmovie.
matrix transform [list] The word matrix, followed by nine floating point numbers, reloads the current
movie into RAM after performing a transformation matrix operation on the image.
This transformation is the same one used for the mapping in QuickTime of points
from one coordinate space (i.e, the original image) into another coordinate space
(a scaled, rotated, or translated version of the original image).

The transform matrix operation consists of nine matrix elements


mute flag [int] The word mute, followed by a non-zero number, turns off the movie's sound (if it
has any). Followed by a 0, mute turns on the movie's sound (the default).
loop flag [int] The word loop, followed by a number in the range 0-2, controls looping for the
current film on. The options are:
0: looping off (default) 1: looping on 2: palindrome mode (forward and then
backward)
loopend endpoint [int] Sets the ending point of a loop. The default value the time value that represents
the end of the movie.
looppoints start [int] The word looppoints, followed by two numbers, sets the beginning and end
end [int] points of a loop. the default values are 0 (i.e., the start of the film) for the start
point and the end of the film for the endpoint.
loopset start [int] See the looppoints entry.
end [int]
loopstart startpoint [int] Sets the beginning point of a loop. The default value is 0 (the start of the movie).
(mouse) Double-clicking on the imovie object will make the movie window active.
palindrome flag [int] The word palindrome, followed by a non-zero number, sets the movie to play in
palindrome mode (forward and then backward). Looping must be turned on.
palindrome 0 (the default) disables palindrome mode.
pause Pause movie playback
prev time-units [int] The word prev, followed by a number, moves the time location backward by that
amount. If no number is supplied, prev moves the time backward by 5.
rate speed [list] The word rate, followed by one or more integers or floats, sets the playing speed
of the movie. If rate is followed by one integer, that number is taken to be a whole
number playing speed. If rate is followed by two numbers, the first number is
taken to be the numerator and the second the denominator of a fractional speed. 1
is the normal playing speed, 0 means the movie is stopped, and a negative rate
plays backwards. rate 1 2 would play the movie at half speed. Immediately after
you send a non-zero rate message, the movie will begin playing, so you may wish
to precede any rate messages with an integer to locate to the desired starting
position.
read filename [symbol] The word read, followed by a symbol, looks for a QuickTime movie file with that
name in Max's file search path, and opens it if it exists, displaying the movie's first
frame in a movie window. If the filename contains any spaces or special
characters, the name should be enclosed in double quotes or each special character
should be preceded by a backslash (\). The word read by itself puts up a standard
Open Document dialog box and reads in any movie file you select. The read
message will open at least 26 different types of files that can be opened by
QuickTime, these include movie files such as MPEG, audio files including AIFF
and MP3, and graphics files including GIF and JPEG.
readany filename [symbol] The readany message opens any type of file, using QuickTime routines to try to
interpret it as a movie or other supported media file.
quality interval [int] The word quality, followed by a number, sets the minimum interval, in
milliseconds, between movie redraws. The default is 0 (i.e., no minimum).
passive flag [int] The word passive, followed by a non-zero number, sets the passive mode. In
passive mode, starting a movie will not cause the frame to change unless a bang
message is received. passive0 (the default) sets the movie object to respond to
normal start messages.
start beginning-point [int] Sets the movie's rate to 1 and begins playing from the beginning. If the word start
is followed by the name of a specific loaded movie, that movie becomes the current
movie before starting.
startat location [list] The word startat, followed by a number, set the current time location of the
movie and begins playing from that point.
stop Stops the movie.
rd filename [symbol] Same as read.
rect x [int] The word rect, followed by four numbers, specifies the size of the rectangle in
y [int] which the movie is displayed within the movie window. The first two numbers
width [int] specify the position of the rectangle within the movie window, in relative
height [int] coordinates, and the second two numbers specify the width and height, in pixels,
of the rectangle.
resume Begins playing the movie from its current location, at the most recently specified
rate.
switch filename [symbol] The word switch, followed by a symbol, makes the named movie the active one
without changing the transport state (See the start message).
reload The word reload will reload the current movie into memory (can be used to
refresh; for example, if a movie is playing and the stop message is sent followed
by reload, the movie will reload into memory and be set to play from the
beginning as a newly loaded movie).
time frame [int] The word time, followed by a number that specifies a QuickTime frame number,
goes to the time location specified by the number. When no argument is present,
the time message's functionality is equivalent to the gettime message.
timescale Reports the timescale of the movie (the number of QuickTime Time Units per
second) from the left outlet.
vol volume [number] The word vol, followed by a number in the range 1-255, sets the movie's sound
volume. Optionally, the volume can be set by using the word vol, followed by a
floating-point value in the range 0. - 1.0.

Attributes
Name Type g/s Description
autofit int Sets the movie to fit automatically within the size of the imovie window.
def.:0
border int Toggles the drawing of border around the imovie object. The default is 1 (draw
def.:1 border).
moviedim int (get) Displays the original dimensions of the movie in pixels.
name symbol Specifies the name of the file that the imovie object will display. The symbol used
as a filename must either be the name of a file in Max's current search path, or an
absolute pathname for the file (e.g.
"MyDisk:/Documents/movies/krakatoa.mov"). The file name can be specified
using the object's Inspector. The word name by itself puts up a standard Open
Document dialog box.

Information for box attributes common to all objects

Output
int: Out left outlet: The end time of the movie is sent out in response to the length message; the current time in the movie is
sent out in response to the time message; 0 is sent out in response to the start message.

Out middle outlet: The horizontal position of the mouse, relative to the left edge of the movie, is sent out when the mouse is
clicked or dragged inside the movie.

Out right outlet: The vertical position of the mouse, relative to the top edge of the movie, is sent out when the mouse is clicked or
dragged inside the movie.

Examples
A movie can be displayed within a patch, and mouse motion can be detected within it

See Also
Name Description
lcd Draw graphics in a patcher window
movie Play a QuickTime movie in a window
playbar Movie/SoundFiles controller
Max Basic Tutorial 12: Movie Max Basic Tutorial 12: Movie Playback
Playback
incdec
Increment and decrement a value

Description
Increment or Decrement a value. When connected to a number box, Click the upper half of the object to increment, click the lower
half to decrement.

Arguments
None.

Messages
bang bang message causes the incdec object to output the currently stored value.
int input [int] A number sent to the incdec object's inlet sets the value that will be incremented
or decremented by clicking on the top or bottom of half of the object. The number
is not sent out the outlet. incdec is designed to be used with user interface objects
such as the number box, dial, and the various sliders.
float input [float] A floating-point number sent to the incdec object's inlet sets the value that will be
incremented or decremented by clicking on the top or bottom of half of the object.
The number is not sent out the outlet. incdec is designed to be used with user
interface objects such as the number box, dial, and the various sliders.
dec The dec message can be used to decrement and output the stored value.
inc The inc message can be used to increment and output the stored value.
(mouse) A mouse click increments or decrements the stored value (depending on which
arrow is clicked) and sends it out the outlet.
set input [int] The word set followed by an integer value functions identically to the int message,
and is provided for convenience.

Attributes
Name Type g/s Description
bgcolor float Sets the background color.
bordercolor float Sets the border color.
fgcolor float Sets the foreground color.
increment float Sets the step size for increment/decrement.
def.:1.
parameter_enable int Parameter Mode Enable

Information about attributes available for Parameter-aware objects

Information for box attributes common to all objects

Output
int: When you click on the top half of an incdec object, it sends out a value that is one greater than the last value received at its
inlet or sent out its outlet, whichever happened most recently. Holding the mouse button down continues to increment the output,
gradually increasing in rate of output.

The same is true for the bottom half of the incdec object , except that the values are decremented.

Examples
incdec works well in combination with number box and slider

See Also
Name Description
number Display and output a number
umenu Create and fill a pop-up menu
slider Move a slider to output values
inlet
Receive messages from outside a patcher

Description
Receive messages from outside the patcher wherever it is embedded. Each inlet object in a patcher will show up as an inlet at the
top of an object box when the patch is used inside another patcher (as an object or a subpatch). Messages sent into such an inlet
will be received by the inlet object in the subpatch.

Arguments
None.

Messages
(mouse) Double-clicking on an inlet object will open the parent patch or bring it to front.

Attributes
Name Type g/s Description
comment object Sets the mouse-over Assistance message for the inlet. This value can only be set
using the Comment setting in the inlet object's Inspector.

Information for box attributes common to all objects

Output
anything: In a subpatch inlet sends out whatever messages it receives through patch cords from the patch that contains it.

Examples

Inlets of the subpatch... correspond to the inlet objects in the subpatch

See Also
Name Description
bpatcher Embed a subpatch with a visible UI
outlet Send messages out of a patcher
pcontrol Open and close subwindows
receive Receive messages without patch cords
send Send messages without patch cords
Max Basic Tutorial 14: Max Basic Tutorial 14: Encapsulation
Encapsulation
int
Store an integer value

Description
int can store and output any given integer number.

Arguments
Name Units Type Opt Description
initial-value number opt Sets an initial value to be stored in int. If there is no argument, the initial value is
0. An int argument by itself, without the word int, is another way of creating and
initializing an int object. Float values are converted to integers.

Messages
bang In left inlet: Sends the stored value out the outlet.
int input [int] In left inlet: The number replaces the currently stored value and is sent out the
outlet.
(inlet1) set-input [int] In right inlet: The number replaces the stored value without triggering output.
float input [float] Converted to int.
send receive-object-name [list] In left inlet: The word send, followed by the name of a receive object, sends the
value stored in int to all receive objects with that name, without sending it out the
outlet of the int .
set set-input [int] In left inlet: The word set, followed by a number, replaces the stored value
without triggering output.

Information for box attributes common to all objects

Output
int: A number is stored in (and output from) int as a long (32-bit) integer.

Examples

Output the stored value... Replace the stored value and output it... Initial value is given

See Also
Name Description
float Store a decimal number
pv Share data within a patch hierarchy
value Share a number with other objects
Max Basic Tutorial 16: Remote Max Basic Tutorial 16: Remote Messaging
Messaging
itable
Graphic display of a table

Description
Provides visual display of the table contents in your patcher window.

Arguments
Name Units Type Opt Description
tablename symbol The argument gives a name to the itable. Max looks for a file of the same name to
load. If two or more table or itable objects share the same names, they also share
the same values.

Messages
bang In left inlet: Same as a quantile message with a random number between 0 and
32,768 as an argument.
int index [int] In left inlet: The number specifies an address in the itable. The value stored at
that address is sent out the left outlet. However, if a value has been received in the
right inlet, itable stores that value in the specified address, rather than sending
out a number.

In right inlet: The number specifies a value to be stored in itable. The next address
number received in the left inlet causes the value to be stored at that address.
(inlet1) input [int] In right inlet: The number specifies a value to be stored in itable. The next address
number received in the left inlet causes the value to be stored at that address.
float index [float] Converted to int.
list index [int] In left inlet: The second number is stored in itable, at the address (index)
value [int] specified by the first number.
clear In left inlet: Sets all values in the table to 0.
const input [int] In left inlet: The word const, followed by a number, stores that number at all
addresses in the table.
dump In left inlet: Sends all the numbers stored in the table out the left outlet in
immediate succession, beginning with address 0.
fquantile input [float] In left inlet: The word fquantile, followed by a number between zero and one,
multiplies the number by the sum of all the numbers in the table. Then, table
sends out the address at which the sum of the all values up to that address is
greater than or equal to the result.
getbits address [int] Gets the value of one or more specific bits of a number stored in the table, and
start [int] sends that value out the left outlet. The first argument is the address to query; the
bits [int] second argument is the starting bit location in the number stored at that address
(the bit locations are numbered 0 to 31, from the least significant bit to the most
significant bit); and the third argument specifies how many bits to the right of the
starting bit location should be sent out. The specified bits are sent out the outlet as
a single decimal integer.
goto index [int] In left inlet: The word goto, followed by a number, sets a pointer to the address
specified by the number. The pointer is set at the beginning of the table initially.
inv value [int] In left inlet: The word inv, followed by a number, finds the first value which is
greater than or equal to that number, and sends the address of that value out the
left outlet.
handtool flag [list] The word handtool, followed by a zero or one, toggles setting the itable object to
use the hand tool. It is equivalent to setting the tool attribute.
max Retrieve the maximum stored value
min Retrieve the minimum stored value
(mouse) The values stored in table can be entered and edited graphically with the mouse.
length Output the table size
linetool flag [list] The word linetool, followed by a zero or one, toggles setting the itable object to
use the line tool. It is equivalent to setting the tool attribute.
load In left inlet: Puts the object in load mode. In load mode, every number received in
the left inlet gets stored in the table, beginning at address 0 and continuing until
the table is filled (or until the table is taken out of load mode by a normal
message). If more numbers are received than will fit in the size of the table, excess
numbers are ignored.
next In left inlet: Sends the value stored in the address pointed at by the goto pointer
out the left outlet, then sets the pointer to the next address. If the pointer is
currently at the last address in the itable object, it wraps around to the first
address.
normal In left inlet: Undoes a prior load message; takes the itable object out of load mode
and reverts it to normal operation.
quantile number [int] In left inlet: The word quantile, followed by a number, multiplies the number by
the sum of all the numbers in the itable object. This result is then divided by 2^15
(32,768). Then, table sends out the address at which the sum of all values up to
that address is greater than or equal to the result.
penciltool flag [list] The word penciltool, followed by a zero or one, toggles setting the itable object to
use the pencil tool. It is equivalent to setting the tool attribute.
prev In left inlet: Causes the same output as the word next, but the pointer is then
decremented rather than incremented. If the pointer is currently at the first
address in the itable object, it wraps around to the last address.
selecttool flag [list] The word selecttool, followed by a zero or one, toggles setting the itable object to
use the select tool. It is equivalent to setting the tool attribute.
send receive-name [symbol] The word send, followed by the name of a receive object, followed by an address
address [int] number, sends the value stored at that address to all receive objects with that
name, without sending the value out the itable objects outlet.
set start [int] In left inlet: The word set, followed by a list of numbers, stores values in certain
values [list] addresses. The first number after the word set specifies an address. The next
number is the value to be stored in that address, and each number after that is
stored in a successive address.
setbits address [int] In left inlet: Changes the value of one or more specific bits of a number stored in
start [int] the itable object. The word setbits is followed by four number arguments. The
count [int] first argument is the address being referred to; the second argument is the starting
value [int] bit location in the number stored at that address (the bit locations are numbered 0
to 31, from the least significant bit to the most significant bit); the third argument
specifies how many bits to the right of the starting bit location should be modified,
and the fourth argument is the value (stated in decimal or hexadecimal form) to
which those bits should be set.
For example, the message setbits 47 5 3 6 will look at address 47 in the itable
object, start at bit location 5 (the sixth bit from the right), and replace the 3 bits
starting at that location with the bits 110 (the binary equivalent of the decimal
integer 6). Suppose that address 47 of the itable object stores the number 87. The
binary form of 87 is 1 010 111, so replacing the 3 bits starting at bit location 5 with
110 would change the number to 1 110 111, which is the binary form of the decimal
integer 119. The new number stored at address 47 in the itable object will
therefore be 119.
sum In left inlet: Sends the sum of all the values in the itable object out the left outlet.
read filename [symbol] In left inlet: The word read, followed by a name, opens and reads data values
from a file in Text or Max binary format. Without an argument, read opens a
standard Open Document dialog for choosing a file to read values from. If the file
contains valid data, the entire contents of the existing table are replaced with the
data.
refer name [symbol] In left inlet: The word refer, followed by the name of another table, sets the
receiving itable object to read its data values from a named table object.
write In left inlet: Opens a standard save file dialog for choosing a name to write data
values from the itable object. The file can be saved in Text or Max binary format.

Attributes
Name Type g/s Description
autohint int Toggles display of the mouse position when positioned over the table.
def.:1
bgcolor float Sets the table background color in RGBA format.
def.:0.93 0.93 0.93
1.
bgcolor2 float Sets the outer background (text area) color in RGBA format.
def.:1. 1. 1. 1.
bordercolor float Sets the table border color in RGBA format.
def.:0. 0. 0. 1.
embed int Toggles the ability to embed the table and save its data as part of the main patch.
def.:1 The default behavior is 1 (save the subpatch).
legend int Toggles the display of the table legend.
def.:1
linecolor float Sets the color used in line mode in RGBA format.
def.:0. 0. 0. 0.3
name symbol Specifies the name of a table. You can also specify the name of an itable object
using an argument. Max looks for an itable object of the same name which has
been saved as a separate file. If two or more table objects share the same names,
they also share the same values.

For information about using named objects in Max for Live, click here.
notename int Toggles Y axis display using MIDI note names.
def.:0
parameter_enable int Parameter Mode Enable
pointcolor float Sets the table points color in RGBA format.
def.:0. 0. 0. 1.
range int Specifies the range of values which can be displayed on the y axis of the editing
window. A newly created table has a range of 128, from 0 to 127.
signed int Toggles the ability to store and display signed integer values. A newly created table
def.:0 with signed values has a range of 128, from -128 to 127.
size int Specifies the number of values stored in the table. The default is 128 values,
indexed with numbers from 0 to 127.
textcolor float Sets the table text color in RGBA format.
def.:0. 0. 0. 1.
tool int Sets the tool used when graphically interacting with the object. The options are:
def.:0
0: Pencil tool
1: Line tool
2: Select tool
3: Move tool
'Pencil' = TEXT_HERE
'Select' = TEXT_HERE
'Line' = TEXT_HERE

Information about attributes available for Parameter-aware objects

Information for box attributes common to all objects


Examples

See Also
Name Description
capture Store values to view or edit
coll Store and edit a collection of data
funbuff Store pairs of numbers
histo Create a histogram of numbers received
multislider Display data as sliders or a scrolling display
table Store and edit an array of numbers
text Format messages as a text file
Max Basic Tutorial 17: Data Max Basic Tutorial 17: Data Structures And Probability
Structures And Probability
iter
Break a list into individual messages

Description
Unpacks and outputs list contents one element at a time.

Arguments
None.

Messages
bang Sends the number or list most recently received, in sequential order.
int input [int] The number is sent out the outlet.
float input [float] The number is sent out the outlet.
list input [list] The numbers in the list are sent out the outlet in sequential order.
anything input [list] See the list entry.

Information for box attributes common to all objects

Output
int: The numbers received in the inlet are sent out one at a time.

Examples

Numbers in a list pass through iter one at a time

See Also
Name Description
cycle Round-robin messages to outlets
thresh Combine messages when received close together
unjoin Break a list into messages
unpack Break a list into individual messages
zl Process lists in many ways
Max Data Tutorial 2: Data Scaling Max Data Tutorial 2: Data Scaling
itoa
Convert integers to ASCII characters

Description
Converts a stream or list of up to 256 integers into a symbol.

Arguments
None.

Messages
bang In left inlet: a bang message can be used to trigger the output of the currently
stored string of ascii characters as a symbol.
int input [int] In left inlet: The integer is interpreted as an ASCII character which is stored
internally and sent out the outlet as a symbol.

In middle inlet: The integer is interpreted as an ASCII character which is


appended to the internally stored character string. No output is triggered.

In right inlet: The integer is interpreted as an ASCII character which is stored


internally, replacing the previously stored character string, but not output.
float input [float] Converted to int.
list input [list] In left inlet: Each value in list of integers sent to the left inlet is interpreted as an
ASCII character and stored internally as an ASCII character string, replacing the
previously stored character string, and output as a symbol.

In middle inlet: A list of integers sent to the middle inlet will be converted to
ASCII characters and appended to the current internally-stored character string,
without causing output.

In right inlet: A list of integers sent to the right inlet will be converted to ASCII
characters and stored internally as an ASCII character string, replacing the
previously stored character string, without triggering output .
clear input [list] In left inlet: The clear message is used to clear the contents of the internally-
stored string of ascii characters.

Information for box attributes common to all objects

Output
symbol: The ASCII character string converted from the input is sent out as a symbol.

Examples

Collect typed keys into a symbol (output with return key).


See Also
Name Description
atoi Convert ASCII characters to integers
key Report keyboard presses
keyup Report key information on release
message Send any message
regexp Use regular expressions to process input
spell Convert input to ASCII codes
sprintf Format a message of words and numbers
Max Basic Tutorial 8: Keyboard Max Basic Tutorial 8: Keyboard and Mouse Input
and Mouse Input
Max Comm Tutorial 2: Serial Max Comm Tutorial 2: Serial Communication
Communication
Common Box Attributes
Common Box Attributes

Description
Below is a list of attributes shared by all objects. If you want to change one of these attributes for an object based on the object
box, you need to place the word sendbox in front of the attribute name, or use the object's Inspector.

Attributes
Name Type g/s Description
annotation symbol Sets the text that will be displayed in the Clue window when the user moves the
mouse over the object.
background int Adds or removes the object from the patcher's background layer. background 1
def.:0 adds the object to the background layer, background 0 removes it. Objects in the
background layer are shown behind all objects in the default foreground layer.
color float Sets the color for the object box outline.
fontface int Sets the type style used by the object. The options are:
def.:0
plain
bold
italic
bold italic
'regular' = TEXT_HERE
'bold' = TEXT_HERE
'italic' = TEXT_HERE
'bold italic' = TEXT_HERE
fontname symbol Sets the object's font.
fontsize float Sets the object's font size (in points).
'8' = TEXT_HERE
'9' = TEXT_HERE
'10' = TEXT_HERE
'11' = TEXT_HERE
'12' = TEXT_HERE
'13' = TEXT_HERE
'14' = TEXT_HERE
'16' = TEXT_HERE
'18' = TEXT_HERE
'20' = TEXT_HERE
'24' = TEXT_HERE
'30' = TEXT_HERE
'36' = TEXT_HERE
'48' = TEXT_HERE
'64' = TEXT_HERE
'72' = TEXT_HERE
hidden int Toggles whether an object is hidden when the patcher is locked.
def.:0
hint symbol Sets the text that will be displayed in as a pop-up hint when the user moves the
mouse over the object in a locked patcher.
ignoreclick int Toggles whether an object ignores mouse clicks in a locked patcher.
def.:0
patching_rect float Sets the position and size of the object in the patcher window.
def.:0. 0. 100. 0.
position float (set) Sets the object's x and y position in both patching and presentation modes (if the
object belongs to its patcher's presentation), leaving its size unchanged.
presentation int Sets whether an object belongs to the patcher's presentation.
def.:0
presentation_rect float Sets the x and y position and width and height of the object in the patcher's
def.:0. 0. 0. 0. presentation, leaving its patching position unchanged.
rect float (set) Sets the x and y position and width and height of the object in both patching and
presentation modes (if the object belongs to its patcher's presentation).
size float (set) Sets the object's width and height in both patching and presentation modes (if the
object belongs to its patcher's presentation), leaving its position unchanged.
textcolor float Sets the color for the object's text in RGBA format.
varname symbol Sets the patcher's scripting name, which can be used to address the object by name
in pattr, scripting messages to thispatcher, and the js object.
jit.cellblock
Two-dimensional storage and viewing

Description
Provides storage, viewing and editing of two-dimensional data. The format is similar to the "grid" display tools found in many
other development environments. The current cell location, format, display and contents within jit.cellblock can be set with the
mouse or by using Max messages.

Arguments
None.

Messages
bang Sends the contents out the object's left outlet, and sends a message through the
third outlet in the form set value-list.
list column [int] Selects a cell within the cellblock. The message list col-number row-number is
row [int] equivalent to the message select col-number row-number.
append input [list] The word append, followed by a data element or a list of elements, will add the
specified valid Max data to the contents of the currently selected cell.
cell column [int] The cell message allows you to control the appearance of a single cell within the
row [int] cellblock. Using the cell message will override changes for both row and col
setting [symbol] message.
value [list]
clear option [list] The clear message removes data from the cellblock. The message clear <col-
number row-number> clears the contents of the specified cell. clear all will clear
the entire contents of the cellblock. The message clear current will clear the
contents of the currently selected cell(s). The clear message with no arguments is
equivalent to the message clear current.
col column [int] The col message allows you to control the appearance of a single column within
setting [symbol] the cellblock. Using the col message to override color settings will override any
value [list] color changes made with the row message. Using the cell message will, however,
override color changes for both col and row messages.
deref Disconnects a jit.cellblock object from any attached coll objects.
dump Sends a listing of the contents of all non-empty cells out the object's left outlet,
one line per cell. Each output line takes the form col-number row-number cell-
contents.
jit_deref The message jit_deref will dereference the currently referenced jit.matrix object.
jit_matrix name [symbol] The message jit_deref will cause the jit.cellblock object's display/edit to directly
reference the received jit.matrix rather than maintaining its own data structure.
mode operational-mode [list] Set operational modes
plane input [int] The word plane followed by an integer that specifies a numbered plane in a
jit.matrix object, will display that plane. The special message plane -1 will
display all four planes of an RGBA jit.matrix object simultaneously.
prepend input [list] Adds the specified valid Max data to the beginning of the currently selected cell
contents.
read filename [symbol] Opens and reads the contents of a cellblock file from disk if a filename is specified.
No attempts are made to verify the contents. If no filename is specified, a file
dialog box will be displayed to allow selection of a saved cellblock file.
refer name [symbol] The word refer, followed by the name of a coll, object, displays the contents of the
named coll object's internal list. Changes to the data in the jit.cellblock will
change the contents of the attached coll object.
refresh Causes the jit.cellblock object to be redrawn.
select column-number [int] The select message, followed by a column number and row number, will select the
row-number [int] requested coll using the current selmode. The contents of the selected cell(s) are
output from the object's left outlet, and the outputs a message in the form set
value out the third outlet.
set input [list] Replaces a cell's data with the data specified. Two forms are supported:
set current value replaces the currently selected cell's contents.
set col-number row-number values replaces the specified cell's contents.
row row [int] The row message allows you to control the appearance of a single row within the
setting [symbol] cellblock.
value [list]
rowblend foreground [int] The word rowblend, followed by two numbers in the range 0-100 specifying
background [int] foreground and background blend percentages. blends the foreground and
background colors for the cellblock object.
text input [list] Replaces the value of the currently selected cell with the incoming text values. This
is provided as a convenient way of receiving the output of a textedit object.
send name [symbol] The word send, followed by the name of a receive object, will transmit cellblock
option [list] values without using connected patch cords; it is the equivalent of sending the
output through a send object.

send receive-object col-number row-number will send the data in the specified cell
to the specified received object. send receive-object all sends all non-empty cell
contents to the specified receive object as a series of lists in the form cell-data-
type value.
sync messages [list] Receives input in the jit.cellblock object's right inlet from another jit.cellblock
object, so that two cellblocks can maintain location and selection synchronization.
Synchronization allows for multiple jit.cellblock objects to react as if connected.
One use of synchronization is used to force external cellblock objects to act as
header rows and columns for a main jit.cellblock. For more information on
setting synchronization, see the mode message.
write filename [symbol] Opens a file and writes the contents of a cellblock file to disk. If a filename is
specified, that file is created and written. If no filename is specified, a file dialog
box will be displayed to allow selection of a pathname and file.
writeagain If a file has been written, the writeagain message will allow it to be rewritten
without further user interaction.

Attributes
Name Type g/s Description
automouse int Enables/disables scrolling or selecting cells by clicking and dragging with the
def.:1 mouse. The default is 1 (enabled).
bblend int Specifies the percentage of background blending for the jit.cellblock object's
def.:0 display.In cases where there are both column and row background color overrides,
this message will allow you to "blend" the colors. Column colors have a higher
priority than row colors; if you have a row and column color that affect a cell, only
the column color will normally be displayed. The bblend message allows you to
make the column color transparant using a percentage value, thereby allowing the
row color to be displayed. This message applies the color transparency to all
column colors without discrimination.
bgcolor float Sets the default background color of the jit.cellblock object in RGBA format.
border int Toggles drawing a border edge around the jit.cellblock.
def.:1
bordercolor float Sets the default border color of the jit.cellblock object in RGBA format.
colhead int Toggles the behavior of the first column. If the header option is selected, the first
def.:0 column will change color to the rgba setting, and will not be directly editable in
selmode 5.
cols int Sets the number of columns that are visible within the jit.cellblock. If the number
def.:10 of columns is greater than can be displayed, scrollbars will be shown.
colwidth int Sets the default column width of the individual cells. Changing these settings may
def.:66 change whether the scrollbars are displayed.
datadirty int Enables or disables the patcher-dirty flag. The default is 0 (disabled). When
def.:0 enabled, the jit.cellblock object will dirty the patch whenever its cell data changes.
fblend int Specifies the percentage of foreground blending for the jit.cellblock object's
def.:0 display.In cases where there are both column and row foreground color overrides,
this message will allow you to "blend" the colors. Column colors have a higher
priority than row colors; if you have a row and column color that affect a cell, only
the column color will normally be displayed. The fblend message allows you to
make the column color transparent using a percentage value, thereby allowing the
row color to be displayed. This message applies the color transparency to all
column colors without discrimination.
fgcolor float Sets the default foreground color of the jit.cellblock object in RGBA format.
grid int Toggles drawing a border edge around each individual cell.
def.:1
gridlinecolor float Sets the default grid line color of the jit.cellblock object in RGBA format.
hcellcolor float Sets the default selected cell color of the jit.cellblock object in RGBA format.
headercolor float Sets the default header color of the jit.cellblock object in RGBA format.
hscroll int Toggles horizontal scroll bar behavior. When set to 0, this attribute will override
def.:1 the jit.cellblock objects automatic handling of scrollbar display when there is
more information to show than the current settings can manage.
hsync int Toggles synchronizing horizontal movement with another jit.cellblock object
def.:1 whose third outlet is connected to the right-most inlet of the jit.cellblock object.
interval int Sets the interval, in milliseconds, at which the display of the contents of a coll or
def.:250 jit.matrix object is updated.
just int Sets the default text justification of all cells - left (0), center (1) or right (2).
def.:0 'Left' = TEXT_HERE
'Center' = TEXT_HERE
'Right' = TEXT_HERE
outmode int Sets the output mode of the cellblock. The output mode settings are:
def.:0
0. separate values: Each cell is sent separately, and each data item within the cell
is sent as a separate value.

1. as one list: If more than one cell is selected, all cell contents are formatted into a
single list and output as a single cell output.

2. as one symbol: If more than one cell is selected, or if a cell has more than one
value (e.g. a list), all values are combined into a single, space-separated symbol for
output.

'Individual cells' = TEXT_HERE


'As one list' = TEXT_HERE
'As one symbol' = TEXT_HERE
precision int Sets the default floating point precision for all cells. This does not alter the actual
def.:2 contents of the cell - it only changes the displayed precision of those contents.
readonly int Sets the read-only mode of the jit.cellblock object. The mode settings are:
def.:0
-1: Eliminate any readonly setting. This option removes the cell/col/row from the
structure, preventing any intrusion of the cell/col/row setting on the overall
cellblock setting.
0: readonly off
1: readonly on
rowhead int Toggles the behavior of the first row. If the header option is selected, the first row
def.:0 will change color to the rgba setting, and will not be directly editable in selmode 5.
rowheight int The word rowheight, followed by a number, sets the default row height of the
def.:18 individual cells. Changing these settings may change whether the scrollbars are
displayed.
rows int Sets the number of columns and rows that are visible within the jit.cellblock. If
def.:10 the number of rows is greater than can be displayed, scrollbars will be shown.
savemode int Toggles the ability save the jit.cellblock object's cell contents as part of the main
def.:0 patcher. The default behavior is 0 (save the data as a separate file).
sccolor float Sets the default text background color of the scroller in RGBA format.
selmode int Sets the selection mode of the cellblock. The selection mode settings are:
def.:1
0. no selection

1. select a single cell

2. select an entire column

3. select an entire row

4. select a single cell unless a column or row header is selected, in which case the
entire column or row is selected.

5. in-place editing. A single cell is selected and values can be typed directly into
the cell.

'No Selection' = TEXT_HERE


'One Cell' = TEXT_HERE
'Column' = TEXT_HERE
'Row' = TEXT_HERE
'Header Select' = TEXT_HERE
'Inline Edit' = TEXT_HERE
selsync int Toggles synchronizing selection with another jit.cellblock object whose third
def.:1 outlet is connected to the right-most inlet of the jit.cellblock object.
sgcolor float Sets the default text color of the scroller gutter in RGBA format.
stcolor float Sets the default text color of the scroller handle (thumb) in RGBA format.
textcolor float Sets the default text color of the jit.cellblock object in RGBA format.
vscroll int Toggles vertical scroll bar behavior. When set to 0, this attribute will override the
def.:1 jit.cellblock objects automatic handling of scrollbar display when there is more
information to show than the current settings can manage.
vsync int Toggles synchronizing vertical movement with another jit.cellblock object whose
def.:1 third outlet is connected to the right-most inlet of the jit.cellblock object.

Information for box attributes common to all objects

Menu Items
Name Description
Color Choosing the Color... menu item from the Object menu when the object is
selected opens a color picker, permitting adjustment to the appearance of the
jit.cellblock object.

Output
list: Out left outlet: A list containing the currently selected column number, row number and the contents of the cell. The form of
the output will be dependent on the mode outmode setting, which will determine if the contents will be provided individually, as
a single list or as a single symbol.
list: Out the middle outlet: The Max message set, followed by the cell contents, is provided as a "helper" output for routing the
cell contents to either a textedit or message object.
list: Out the right outlet: Synchronization messages are sent out the right outlet, meant as a source for the right inlet of other
jit.cellblock objects. These messages can also be used to determine the current state of movement within the cellblock - for
instance, the sync click message notifies that a cell has been click-selected, while the sync select message notifies that a cell has
been selected (either by clicking, or programmatically).

Examples

jit.cellblock displays data on a two-dimensional grid

See Also
Name Description
coll Store and edit a collection of data
maximum Output the highest value
minimum Output the smallest value
Max Data Tutorial 4: Cellblock Max Data Tutorial 4: Cellblock
join
Combine items into a list

Description
Takes separate untyped items and combines them into an output list.

Arguments
Name Units Type Opt Description
inlets int Specifies the number of inlets. If there is no argument, there will be two inlets, and
the two list items will be set to (int) 0 initially.

Messages
bang In left inlet: Causes join to send out a list composed of the currently stored items.
int input [int] The number is stored in the join object as an item in a list with its position in the
list corresponding to the inlet in which it was received. If the inlet is a 'trigger'
input, the entire list is sent out the outlet.
float input [float] The number is stored in the join object as an item in a list with its position in the
list corresponding to the inlet in which it was received. If the inlet is a 'trigger'
input, the entire list is sent out the outlet.
list values [list] The list is stored in the join object as an array of items in a list with its position in
the list corresponding to the inlet in which it was received. If the inlet is a 'trigger'
input, the entire list is sent out the outlet.
anything values [list] The message with its arguments is stored in the join object as an array of items in
a list with its position in the list corresponding to the inlet in which it was
received. If the inlet is a 'trigger' input, the entire list is sent out the outlet.
set values [list] The list is stored in the join object as an array of items in a list with its position in
the list corresponding to the inlet in which it was received.

Attributes
Name Type g/s Description
triggers int Define a list of inputs that will automatically trigger output (i.e. adding an input to
this list will make the inlet "hot"). A value of -1 will cause the object to trigger
output for any inlet.

Information for box attributes common to all objects

Examples

See Also
Name Description
pack Create a list
pak Output a list when any element changes
unjoin Break a list into messages
unpack Break a list into individual messages
js
Execute Javascript

Description
Exposes the Javascript language and some Max specific extensions. The js object can be instantiated with a javascript filename or
with numerical arguments to specify the number of outlets and inlets respectively. The default number of outlets and inlets are
both 1.

Arguments
Name Units Type Opt Description
filename symbol opt Specifies the name of a text file to be used as the Javascript source. If no argument
is specified, it will not initially have any Javascript associated with it. You can still
open a text window and edit and save the Javascript source, but unless you
recreate the object with the saved source filename as an argument, the file will not
be used when a patch containing the js object is loaded.
inlets-outlets list opt If no filename is present as an argument, the number of inlets and outlets is
specified. If one int argument is present, the number of desired outlets is specified.
If two int arguments are present, the first number specifies the number of outlets
and the second number specifies the number of inlets.
jsarguments list opt Following the optional filename or number of outlets and inlets, any symbols or
numbers can be entered that will be assigned to the Javascript variable
jsarguments. jsarguments[0] is the filename entered, and jsarguments[1] is the
first typed-in argument following the filename. The Javascript expression
jsarguments.length will be one more than the number of typed-in arguments

Messages
bang Invokes the function named bang if defined.
int user-defined [int] Invokes the function named msg_int if defined.
float user-defined [float] Invokes the function named msg_float if defined.
list user-defined [list] Performs the same as anything.
anything user-defined [list] Invokes the function with the message name, assigning the message arguments to
the arguments to the function. For example, if the object has a function named xyz
defined, the message xyz 1 2 3 would invoke the xyz function with arguments 1 2
and 3.
autowatch flag [int] The message autowatch, followed by a 1, turns on file watching for the Javascript
source file. When file watching is on, the file is recompiled automatically when it
is modified. This allows you to use an external editor for your Javascript file.
When you save the file, the js object will notice. autowatch 0 turns off file
watching.
compile filename [symbol] Recompiles the current file.
delprop propertyname [symbol] The word delprop, followed by a name, deletes the named property.
editfontsize font-size [int] Changes the font-size of the text used in the editing window which contains the
object's Javascript source file.
getprop property [symbol] The word getprop, followed by a name, outputs the value of the property name
stored in the object out the left outlet.
loadbang Invokes the function named loadbang if defined. This message is sent when the
file is loaded.
open Opens the text window where the object's Javascript source file can be edited.
setprop property [symbol] The word setprop, followed by name and one or more names or numbers, sets the
values [list] named property to what follows the name. For example, after sending setprop xyz
1 2 3 to a js object. the xyz property would have a value of the list 1 2 3.
statemessage messages [list] Allows for the testing of messages passed to functions within the Javascript source
file.
wclose Closes the text window where the object's Javascript source file is edited.

Attributes
Name Type g/s Description
parameter_enable int Parameter Mode Enable

Information about attributes available for Parameter-aware objects

Information for box attributes common to all objects

methodnote
Output
anything: Numbers, lists, or symbols are sent out the js object's outlets when the Javascript code executing within the js object
invokes the outlet function.

Examples

Two js objects instantiated with different arguments the Javascript code creates the objects with different numbers of outlets
based on the arguments

See Also
Name Description
jstrigger Execute Javascript instructions sequentially
jsui Create user interfaces with Javascript
mxj Execute Java in Max
Max JS Tutorial 1: Basic JavaScript Max JS Tutorial 1: Basic JavaScript
Max JS Tutorial 2: JavaScript Max JS Tutorial 2: JavaScript Scripting
Scripting
Max JS Tutorial 3: JavaScript Max JS Tutorial 3: JavaScript Tasks, Arguments, and Globals
Tasks, Arguments, and Globals
Tutorial 45: Introduction to using Tutorial 45: Introduction to using Jitter within JavaScript
Jitter within JavaScript
Tutorial 46: Manipulating Matrix Tutorial 46: Manipulating Matrix Data using JavaScript
Data using JavaScript
Tutorial 47: Using Jitter Object Tutorial 47: Using Jitter Object Callbacks in JavaScript
Callbacks in JavaScript
jstrigger
Execute Javascript instructions sequentially

Description
The jstrigger object is similar to the trigger object, except that typed-in arguments within parentheses are passed to the
Javascript evaluator. For more information on the Max implementation of Javascript, refer to the Javascript in Max manual. For
complete information about Javascript itself, consult a reference book such as Javascript: The Definitive Guide by David Flanagan,
published by O'Reilly.

Arguments
Name Units Type Opt Description
sequential- numbers, The arguments to the jstrigger object may be either constants or expressions.
Javascript- symbols, or Constants are numbers or symbols. For each constant, an outlet will be created,
instructions expressions and the constant value will be sent out the corresponding outlet when the object
receives a message in its left inlet. For example, jstrigger with the arguments
ready set 74 would send 74 out the right outlet, followed by set out the middle
outlet, followed by ready out the left outlet.

Expressions are Javascript expressions contained within parentheses. You can


include more than one Javascript statement can be contained within the
parentheses, but you must separate the statements by semicolons (;). A semicolon
after the last statements is not required, and the word return is not required
either. To return a list, you can either create an array object or place items in
square brackets separated by commas. Javascript allows you to enter expressions
between the commas. See the Examples section.

For each expression, an outlet will be created, and the value of the expression will
be sent out the corresponding outlet when the jstrigger object receives a message
in its left inlet.

Note that any use of semicolons or commas in an object box require a preceding
backslash (\) character, otherwise you will see the following error message in the
Max window and the object will not be created:

* error: object box has comma or semicolon

In addition, it is strongly recommended to use single quotes (') rather than double
quotes to define string literals. The use of double quotes can produce unexpected
results in jstrigger when the object is saved and recreated in a patcher.

Messages
bang The most recently stored values for each argument are assigned to the a array.
Then the expressions in the object are evaluated, right to left, and the value of
each expression or constant is sent out the outlet corresponding to each
expression.
int input [int] Contextual/User-specified according to Javascript arguments.
float input [float] Contextual/User-specified according to Javascript arguments.
list input [list] Contextual/User-specified according to Javascript arguments.
anything input [list] Contextual/User-specified according to Javascript arguments.

Information for box attributes common to all objects

Output
anything: When the jstrigger object receives a message in its inlet, the expressions are evaluated from right to left and their
results are sent out the corresponding outlets from right to left.

Examples

See Also
Name Description
bangbang Output a bang from many outlets
js Execute Javascript
jsui Create user interfaces with Javascript
jsui
Create user interfaces with Javascript

Description
Provides an environment to make user interface elements using Javascript. This provides all of the programming tools available in
the js object, but also exposes the mgraphics and sketch drawing routines for visual output.

Arguments
None.

Messages
bang Invokes the function named bang if defined.
int user-defined [int] Invokes the function named msg_int if defined.
float user-defined [float] Invokes the function named msg_float if defined.
list user-defined [list] Performs the same as anything.
anything user-defined [list] Invokes the function with the message name, assigning the message arguments to
the arguments to the function. For example, if the object has a function named xyz
defined, the message xyz 1 2 3 would invoke the xyz function with arguments 1 2
and 3.
(drag) When a file is dragged from the File Browser to a jsui object, the file is loaded and
executed.
autowatch flag [int] The word autowatch, followed by a 1, turns on file watching for the Javascript
source file. When file watching is on, the file is recompiled automatically when it
is modified. This allows you to use an external editor for your Javascript file.
When you save the file, the jsui object will notice. autowatch 0 turns off file
watching.
compile filename [symbol] Recompiles the current file. If followed by a symbol, will load, compile, and set the
currently loaded Javascript file to be the Javascript file specified by the symbol
argument
delprop property [symbol] The word delprop, followed by a name, deletes the named property.
editfontsize size [int] Changes the font-size of the text used in the editing window which contains the
object's Javascript source file.
getprop property [symbol] The word getprop, followed by a name, outputs the value of the property name
stored in the object out the left outlet.
jsargs arguments [list] Sets the current Javascript arguments to any following message arguments.
jsfile filename [symbol] The word jsfile, followed by a symbol , loads, compiles, and sets the currently
loaded Javascript file to be the Javascript file specified by the symbol argument.
loadbang Call the loadbang function
(mouse) Double-clicking on a js object opens a text window where the object's Javascript
source file can be edited. When the text window is saved, the text is compiled as
the object's script.
open Opens the text window where the object's Javascript source file can be edited.
setprop property and settings The word setprop, followed by name and one or more names or numbers, sets the
[list] named property to what follows the name. For example, after sending setprop xyz
1 2 3 to a js object. the xyz property would have a value of the list 1 2 3.
size width [int] The word size, followed by two int arguments, sets the width and height of the
height [int] jsui object.
statemessage messages [list] Allows for the testing of messages passed to functions within the Javascript source
file.
wclose Closes the text window where the object's Javascript source file is edited.
Attributes
Name Type g/s Description
border int Toggles the drawing of a border around the jsui object. The default is 1 (draw
def.:1 border).
filename symbol The word filename, followed by a symbol that specifies a pathname, designates
def.:none the Javascript file to be loaded.
jsarguments atom Specifies any arguments to be passed to the Javascript code contained in the jsui
def.: object.
nofsaa int Toggle full screen anti-aliasing
def.:0
parameter_enable int Parameter mode enable

Information about attributes available for Parameter-aware objects

Information for box attributes common to all objects

Output
anything: Numbers, lists, or symbols are sent out the jsui object's outlets when the Javascript code executing within the jsui
object invokes the outlet function.

Examples

A simple dial with logic and drawing defined in Javascript

See Also
Name Description
js Execute Javascript
jstrigger Execute Javascript instructions sequentially
mxj Execute Java in Max
Max JS Tutorial 3: JavaScript Max JS Tutorial 3: JavaScript Tasks, Arguments, and Globals
Tasks, Arguments, and Globals
jweb
Website data in a Max UI external

Description
The jweb object uses OS-specific technologies (WebKit on the Macintosh, WebBrowser ActiveX Control on Windows systems) to
view renderable data in a Max box.

Arguments
None.

Messages
(drag) When a file is dragged from the Max 5 File Browser to a jweb object, the file will
be loaded.
back The word back reloads the previous page of data, functioning like the 'Back'
button in a conventional web browser.
forward When a sequence of multiple pages has been loaded, and the object has received
the back message, the word forward will advance to the following page in the
object's page history. forward functions like the 'Forward' button in a conventional
web browser.
gethistory The word gethistory, will output a list of all URLs loaded by the object since its
instantiation, in the reverse order of access, with additional information. The
output format is: history URL (symbol) page title (symbol) number of page loads
(int) time stamp of last load (int) . After the last history entry is output, the
message history done will be sent from the outlet.
read url [symbol] The word read, followed by a symbol that specifies a URL or a file pathname, will
read the webpage or file and attempt to render its contents. Upon successful load
of a page, two messages are sent from the object's outlet: url, followed the final
URL which was loaded based on the provided argument; and title, followed by the
title of the loaded page as a symbol.
readfile file path [symbol] The word readfile, followed by a symbol that specifies a file pathname, will read
the file and attempt to render its contents. The word readfile with no argument
opens a file dialog to choose a file. Upon successful load of a page, two messages
are sent from the object's outlet: url, followed the final URL which was loaded
based on the provided argument; and title, followed by the title of the loaded page
as a symbol.
reload The word reload causes the browser to refresh the current page, functioning like
the 'Reload' button in a conventional web browser.
writehistory file name [symbol] The word writehistory, followed by a symbol the specifies the name of a file, will
write a history of the object's use since its instantiation as an.html-format file. The
word writehistory with no arguments opens a file dialog to choose a file.

Attributes
Name Type g/s Description
autosize int Caches the right and bottom margins of the jweb object, using them to resize the
def.:0 object's box as the containing view is resized.
res_report int Toggles the printing of data about resources loaded when referencing a webpage
def.:0 or file. The listing of resources takes the form:
total_resources loaded_resources failed_resources .
scrollbars int Enables the display of horizontal/vertical scrollbars, as required by the size of the
def.:0 webpage in comparison with the jweb object's window. Note the scrollbars can
only be enabled or disabled previous to the loading of a new webpage/file.
url symbol Displays the current URL being displayed.
def.:
Information for box attributes common to all objects

Examples

See Also
Name Description
js Execute Javascript
Max JS Tutorial 1: Basic JavaScript Max JS Tutorial 1: Basic JavaScript
Max JS Tutorial 2: JavaScript Max JS Tutorial 2: JavaScript Scripting
Scripting
Max JS Tutorial 3: JavaScript Max JS Tutorial 3: JavaScript Tasks, Arguments, and Globals
Tasks, Arguments, and Globals
key
Report keyboard presses

Description
Tracks and outputs the key-codes, ASCII values, and modifier-key values of key presses on the computer keyboard.

Arguments
None.

Messages
(keyboard) The input to key comes directly from the computer keyboard. There are no inlets.

Information for box attributes common to all objects

Output
int: Output is sent each time a key is depressed on the computer keyboard. For multi-key combinations (such as option-E
followed by E on a Mac US keyboard), only the last key depressed will produce output.
Out left outlet: The Unicode value of the depressed key, in UTF-16. This outlet provides the ASCII value of the pressed key (i.e., it
outputs the text character rather than the code for the key that was depressed).
Out second outlet: The platform-specific key code of the typed key. The codes are specific to individual physical keyboards as well
operating system. The values are derived from Apple's key-code definitions (e.g., a=0, s=1, d=2, f=3). This outlet is useful in
situations where you want to identify the position of the key rather than the key which was pressed (for example, when
implementing a musical keyboard using the computer keyboard). The values reported for a given key position will be fixed
regardless of the language chosen, and regardless of the modifiers pressed (e.g., the value reported when the key to the right of
the left shift key is pressed will be 6 whether an English or a German keyboard layout is chosen.
Out third outlet: The output value is a set of bits representing the state of various modifier keys when the key was depressed. The
value can be sent through the & object to create toggles set by each modifier key. The numerical output of the right outlet is listed
along with the argument to the & object that will create a toggle:
Out left outlet: The ASCII value of the depressed key.

Out middle outlet: The key code of the depressed key.

Out right outlet: The output values can be sent through the & object to create toggles set by each modifier key. The numerical
output of the right outlet is listed along with the argument to the & object that will create a toggle:

key events: Outputs 128. Toggle = & 128 (reports 0 on Windows if a mouse button is down, always reports 0 on Macintosh)
Windows Control key: Outputs 384. Toggle = & 256 (system uses this so it is not reported)
Macintosh Command key: Outputs 384. Toggle = & 256 (system uses this so it is not reported)
Shift key: Outputs 640. Toggle = & 512
Caps Lock key (on): Outputs 1152. Toggle = & 1024
Windows Alt key: Outputs 2176. Toggle = & 2048 (on Windows the system uses this so it is not reported)
Macintosh Option key: Outputs 2176. Toggle = & 2048
Windows R. Mouse Button: Outputs 4224. Toggle = & 4096
Macintosh Control key: Outputs 4224. Toggle = & 4096
Out fourth outlet: keyboard-independent key code as described here.

Examples
Keys typed on the computer keyboard can be used to trigger messages

See Also
Name Description
atoi Convert ASCII characters to integers
hi Human Interface (gaming) device input
itoa Convert integers to ASCII characters
keyup Report key information on release
modifiers Report modifier key presses
numkey Interpret numbers typed on the keyboard
spell Convert input to ASCII codes
sprintf Format a message of words and numbers
Max Basic Tutorial 8: Keyboard Max Basic Tutorial 8: Keyboard and Mouse Input
and Mouse Input
keyup
Report key information on release

Description
Tracks and outputs the key-codes, ASCII values, and modifier-key values of key releases on the computer keyboard.

Arguments
None.

Messages
(keyboard) The input to keyup comes directly from the computer keyboard. There are no
inlets.

Information for box attributes common to all objects

Output
int: Output is sent each time a key is released on the computer keyboard. For multi-key combinations (such as option-E followed
by E on a Mac US keyboard), only the last key release will produce output.
Out left outlet: The Unicode value of the released key, in UTF-16. This outlet provides the ASCII value of the released key (i.e., it
outputs the text character rather than the code for the key that was released).
Out second outlet: The platform-specific key code of the released key. The codes are specific to individual physical keyboards as
well operating system. The values are derived from Apple's key-code definitions (e.g., a=0, s=1, d=2, f=3). This outlet is useful in
situations where you want to identify the position of the key rather than the key which was released (for example, when
implementing a musical keyboard using the computer keyboard). The values reported for a given key position will be fixed
regardless of the language chosen, and regardless of the modifiers (e.g., the value reported when the key to the right of the left
shift key is pressed will be 6 whether an English or a German keyboard layout is chosen.
Out third outlet: The output value is a set of bits representing the state of various modifier keys when the key was released. The
value can be sent through the & object to create toggles set by each modifier key. The numerical output of the right outlet is listed
along with the argument to the & object that will create a toggle:
Out left outlet: The ASCII value of the released key.

Out middle outlet: The key code of the released key.

Out right outlet: The output values can be sent through the & object to create toggles set by each modifier key. The numerical
output of the right outlet is listed along with the argument to the & object that will create a toggle:

key events: Outputs 128. Toggle = & 128 (reports 0 on Windows if a mouse button is down, always reports 0 on Macintosh)
Windows Control key: Outputs 384. Toggle = & 256 (system uses this so it is not reported)
Macintosh Command key: Outputs 384. Toggle = & 256 (system uses this so it is not reported)
Shift key: Outputs 640. Toggle = & 512
Caps Lock key (on): Outputs 1152. Toggle = & 1024
Windows Alt key: Outputs 2176. Toggle = & 2048 (on Windows the system uses this so it is not reported)
Macintosh Option key: Outputs 2176. Toggle = & 2048
Windows R. Mouse Button: Outputs 4224. Toggle = & 4096
Macintosh Control key: Outputs 4224. Toggle = & 4096
Out fourth outlet: keyboard-independent key code as described here.

Examples
ASCII value is sent when key is released... Used with key to measure how long a key is down

See Also
Name Description
atoi Convert ASCII characters to integers
hi Human Interface (gaming) device input
itoa Convert integers to ASCII characters
key Report keyboard presses
mousestate Report the mouse information
numkey Interpret numbers typed on the keyboard
spell Convert input to ASCII codes
sprintf Format a message of words and numbers
Max Basic Tutorial 8: Keyboard Max Basic Tutorial 8: Keyboard and Mouse Input
and Mouse Input
kslider
Output numbers from an onscreen keyboard

Description
Outputs and displays note and velocity information using an on-screen keyboard.

Arguments
None.

Messages
bang In left inlet: Sends out the pitch and velocity values currently stored in kslider.
int pitch [int] The number received in the inlet is displayed graphically by kslider if it falls
within its displayed range. The current velocity value (from 1 to 127) that kslider
holds is sent out its right outlet, followed by the received number out the left
outlet.
(inlet1) velocity [int] In right inlet: The number received in the right inlet sets the output key velocity
without triggering output.
float pitch [float] Converted to int.
(inlet1) velocity [float] Converted to int.
chord value-pairs [list] In left inlet: The word chord, followed by a list of MIDI note name and velocity
pairs, can be used to play chords on the kslider in polyphonic mode (set by the
mode 1 message). The chord message sends note-offs for currently held notes,
followed by note-on commands for the specified note and velocity pairs. When the
kslider object's state is saved by a preset object in polyphonic mode, the preset
object will store chord messages.
clear In left inlet: The clear message will clear any currently highlighted notes on the
keyboard, but will not trigger any output.
flush In left inlet: When the kslider object is in polyphonic mode (set by the mode 1
message), the flush message will send note-offs to currently held notes and clear
the kslider object's display.
(mouse) The kslider object sends out numbers when you click or drag on it with the mouse.
The velocity value is determined by the vertical position of the mouse within each
key. Higher vertical positions produce higher velocities, to a maximum of 127.
If the kslider object is in polyphonic mode, you need to click on a key twice: once
to send a note-on, and once again for a note-off.
Clicking on the very rightmost edge of the kslider sends out the note of the key C
that would be just to the right of the keys that are visible.
set pitch [int] In left inlet: The word set, followed by a number, changes the value displayed by
velocity [int] kslider, without triggering output.
size size-flag [int] This is a legacy message - the size of the kslider object can be set by clicking on
the object's resize handle and dragging.
In left inlet: The word size, followed by a zero or one, sets the size of the keyboard
display. size 0 (default) sets the large keyboard, and size 1 selects the small
keyboard.

Attributes
Name Type g/s Description
blackkeycolor float Sets the color for the upper level of keys (otherwise known as the black keys) in
RGBA format.
bordercolor float Sets the key outline color in RGBA format.
hkeycolor float Sets the selected key color in RGBA format.
mode int Sets the kslider object's mode of operation.
def.:0 Monophonic: (the default) Only one key can be selected and displayed at one
time.
Polyphonic: The kslider object keeps track of note-ons and note-offs, so it
mirrors which notes are currently held down on your MIDI keyboard. A key is
turned off by sending the kslider object a key on message with a velocity of 0.
'Monophonic' = TEXT_HERE
'Polyphonic' = TEXT_HERE
offset int Sets an offset value in octaves for the kslider object.
def.:36
parameter_enable int Parameter Mode Enable
range int Sets the number of keys in the keyboard display.
def.:48
whitekeycolor float Sets the color for the lower level of keys (otherwise known as the white keys) in
RGBA format.

Information about attributes available for Parameter-aware objects

Information for box attributes common to all objects

Menu Items
Name Description
Color Choosing the Color... menu item from the Object menu when the object is
selected opens a color picker, permitting adjustment to the appearance of the
kslider object.

Output
int: kslider sends its current velocity value out its right outlet, followed by the (displayable) pitch value out its left outlet, when a
number is received in its inlet or you click or drag on the object.

Examples

Produce output by clicking on the keyboard... or use to display incoming pitches

See Also
Name Description
makenote Generate a note-on/note-off pair
notein Receive MIDI note messages
noteout Transmit MIDI note messages
nslider Output numbers from a notation display
pictslider Picture-based slider control
rslider Display or change a range of numbers
slider Move a slider to output values
lcd
Draw graphics in a patcher window

Description
Arguments
None.

Messages
anything arguments [list] anything refers to the backwards-compatible capitalized messages.
ascii ascii value [int] The word ascii, followed by a number between 0 and 255, writes the character
corresponding to that ASCII value at the current pen position, then moves the pen
position to the right of that character. Numbers that exceed the 0-255 range are
restricted to that range with a modulus operation.
clear arguments [list] Erase the contents of the lcd display
brgb red [int] Set the background color
green [int]
blue [int]
clearpicts The word clearpicts, followed by a symbol, deletes all of an lcd object's named
pictures from memory so that they can no longer be drawn. To remove the images
from the lcd object's display, the command should be followed by a clear message.
color color-id [int] Max color palette selections are specified by a nmber in the range 0 - 255. Values
exceeding 255 are restricted range-restricted using a modulus operation.
backsprite any symbol [list] The word backsprite, followed by a symbol, sets the named sprite's drawing order
so that it is drawn first (and displayed last). This command can be used to alter
the order in which sprites are drawn. (Normally, sprites are drawn in the order
they are recorded.)
deletepict any symbol [list] The word deletepict, followed by a symbol, deletes the named the picture from
memory so that it can no longer be drawn. To remove the image from the lcd
object's display, the command should be followed by a clear message.
deletesprite any symbol [list] The word deletesprite, followed by a symbol, deletes the named sprite.
drawpict arguments [list] The word drawpict, followed by a symbol, draws the named picture. Optionally
there may follow four numbers specifying a destination rectangle in which the
picture is scaled and drawn, and source rectangle that specifies the area of the
picture to use in the operation. These rectangles are specified as left, top, width,
and height values in pixels. The destination rectangle is relative to the top left
corner of the lcd display area. The source rectangle is relative to the top, left
corner of the picture. If not present, these rectangles are both set to be the same
size as the picture.
clearsprites Deletes all of an lcd object's named sprites.
closesprite any symbol [list] The word closesprite, followed by a symbol argument that names the sprite, turns
off sprite command collection and associates the defined region with the symbol.
After the closesprite message, drawing commands function normally again.
drawsprite any symbol [list] The word drawsprite, followed by a symbol, draws the named sprite. Optionally
this may be followed by a pair of numbers that specify a horizontal and vertical
offset for drawing the sprite.
font font-id [list] The font message specifies a font ID using the font number mapping that Max 6
font-size () [list] uses generally and a font size to select a font used when drawing text in response
to a write or ascii message.
framearc left () [int] Same as paintarc except that only the unfilled outline of the arc is drawn.
top () [int]
right () [int]
bottom () [int]
start-angle [degrees]
degrees-arc [degrees]
red [int]
green [int]
blue [int]
frameoval left () [int] Same as paintoval except that only the unfilled outline of the oval is drawn.
top () [int]
right () [int]
bottom () [int]
red [int]
green [int]
blue [int]
framepoly x/y int pairs [list] Same as paintpoly except that only the unfilled outline of the polygon is drawn.
framerect left () [int] Same as paintrect except that only the unfilled outline of the rectangle is drawn.
top () [int]
right () [int]
bottom () [int]
red [int]
green [int]
blue [int]
frameroundrect left () [int] Same as paintroundrect except that only the unfilled outline of the rounded
top () [int] rectangle is drawn.
right () [int]
bottom () [int]
horizontal-roundness
() [int]
vertical-roundness ()
[int]
red [int]
green [int]
blue [int]
frgb red () [int] Set the foreground (pen) color
green () [int]
blue () [int]
frontsprite any symbol [list] The word frontsprite, followed by a symbol, sets the named sprite's drawing
order so that it is drawn last (and displayed first). This command can be used to
alter the order in which sprites are drawn. (Normally, sprites are drawn in the
order they are recorded.)
hidesprite any symbol [list] Disable the drawing of a named sprite
getpenloc local-coordinates [list] The word getpenloc outputs a message consisting of the word penloc followed by
two numbers, out the lcd object's right outlet. The numbers represent local
coordinates relative to the top-left corner of the lcd display area. The first number
is the number of pixels to the right of that corner, and the second number is the
number of pixels down from that corner.
getsize Ouputs a message from the right outlet consisting of the word size and two
numbers which report the width and height in pixels of the lcd display area.
move x position [int] Moves the pen position a certain number of pixels down from, and to the right of,
y position [int] its current position. The word move must be followed by two int arguments for
horizontal and vertical offset, in pixels, relative to the current pen position.
Negative arguments may be used to move the pen position up or to the left.
line x position [int] The word line, followed by two int arguments for horizontal and vertical offset, in
y position [int] pixels, relative to the current pen position, draws a line from the current pen
position to a point determined by the specified offset, and that point becomes the
new pen position. Positive arguments draw the line to the right or down; negative
arguments draw up or to the left.
moveto x position [int] Sets the pen position at which the next graphic instruction will be drawn. The
y position [int] moveto message must include two int arguments for horizontal and vertical offset,
in pixels, relative to the upper left corner of the lcd display area.
lineto x endpoint [int] The word lineto, followed by two int arguments for horizontal and vertical ending
y endpoint [int] point, draws a line from the current pen position to the position specified by the
arguments.
linesegment x start () [int] The word linesegment, followed by four int arguments that specify the endpoints
y start () [int] of a line segment, draw a line. The numbers represent the horizontal and vertical
x end () [int] offset of the beginning endpoint, and the horizontal and vertical offset of the
y end () [int] finishing endpoint, in pixels, relative to the top left corner of the lcd display area.
A color may optionally be specified using a single number that selects a color from
Max's color palette (similar to the color message), or by using three additional
numbers that describe an RGB value (similar to the frgb message).
(mouse) You can draw freehand in lcd with the mouse (provided this feature has not been
turned off with a local 0 message). The mouse will draw with the current pen and
color characteristics, and the mouse location will be sent out the outlet.
oprgb red [int] The word oprgb, followed by three numbers between 0 and 255, specify an RGB
green [int] value used as the opcolor for penmodes that support it.
blue [int] If the penmode is set to 32, the alpha channel value is derived by averaging the
three RGB values and mapping the average to the range 0. - 1.0 (e.g., an oprgb
value of 128 128 128 would have an alpha value of .5 when the penmode is set to
32).
paintarc left () [int] The word paintarc, followed by six int arguments that specify the left, top, right,
top () [int] and bottom extremities of an oval across which the arc will be drawn, the start
right () [int] angle (0 is the top) and degrees of arc, paints an arc.
bottom () [int]
start-angle [degrees]
degrees-arc [degrees]
red [int]
green [int]
blue [int]
paintoval left () [int] The word paintoval, followed by four int arguments specifying the left, top, right,
top () [int] and bottom extremities of an oval, paints an oval. These extremities are specified
right () [int] in pixels, relative to the top left corner of the lcd display area. A color may
bottom () [int] optionally be specified using a single number that selects a color from Max's color
red [int] palette (similar to the color message), or by using three additional numbers that
green [int] describe an RGB value (similar to the frgb message).
blue [int]
paintpoly x/y int pairs [list] The word paintpoly may be followed by as many as 254 int arguments that would
specify a series of x/y pairs that define a polygon to be painted in lcd. These x/y
pairs are specified in pixels, relative to the top left corner of the lcd display area.
paintrect left () [int] Left, top, right and bottom positions for the rectangle are specified in pixels,
top () [int] relative to the top left corner of the lcd display area when painting a filled
right () [int] rectangle. A color may optionally be specified using a single number that selects a
bottom () [int] color from Max's color palette (similar to the color message), or by using three
red [int] additional numbers that describe an RGB value (similar to the frgb message).
green [int]
blue [int]
paintroundrect left () [int] The word paintroundrect, followed by six int arguments specifying the left, top,
top () [int] right, and bottom positions of a rectangle and the amount of horizontal and
right () [int] vertical roundness in pixels, paints a rounded rectangle. The edge positions are
bottom () [int] specified in pixels, relative to the top left corner of the lcd display area. A color
horizontal-roundness may optionally be specified using a single number that selects a color from Max's
() [int] color palette (similar to the color message), or by using three additional numbers
vertical-roundness () that describe an RGB value (similar to the frgb message).
[int]
red [int]
green [int]
blue [int]
penmode transfer-mode [list] The word penmode, followed by a number in the range 0-7, sets the transfer
mode for subsequent drawing operations. The following are transfer mode
constants;

Copy 0
Or 1
Xor 2
Bic 3
NotCopy 4
NotOr 5
NotXor 6
NotBic 7
pensize horizontal-thickness The word pensize, followed by two equal int arguments specifying horizontal and
() [int] vertical thickness in pixels (e.g., 4 4), sets the current pensize. The horizontal and
vertical-thickness () vertical thicknesses must be equal.
[int]
scrollrect left () [int] The word scrollrect, followed by six int arguments that specify the left, top, right,
top () [int] and bottom positions of a rectangle to be scrolled and the number of pixels to
right () [int] scroll in the x and y direction, scrolls a rectangle within the lcd object's display
bottom () [int] area.
x-offset () [int]
y-offset () [int]
setpixel x coordinate [int] The word setpixel, followed by two numbers which specify a location in local
y coordinate [int] coordinates relative to the top-left corner of the lcd display area and a list of three
red [int] integers in the range 0-255 which specify a color in RGB format, will set the pixel
green [int] at the designated location to the selected color.
blue [int]
size horizontal-size () [int] The word size, followed by two integers, changes the lcd object window size. The
Maximum size is 8192 x 8192.
vertical-size () [int]
readpict filename [list] The word readpict followed by a symbol which specifies a filename, looks for a
QuickTime graphic file (a .pct file openable on Windows using the QuickTime
Picture Viewer for Windows) with that name in Max's file search path, and reads
the picture file from disk into RAM. This named picture can then be drawn in lcd
with the drawpict and tilepict messages. In response to the readpict message, the
object sends a message out the right outlet of the lcd object consisting of the word
pict followed by a symbol which specifies the name of the picture file and two
numbers which specify the file's width and height. If the read is unsuccessful, the
error message pict <pictname> error will be sent out the right outlet.
recordsprite Initiates the recording of drawing commands which will be stored in a named
sprite. While recording, drawing commands will have no effect on the contents of
the lcd object's window.
reset arguments [list] The erase message erases the current display and resets the colors, pen, and pen
position to their default states. It is equivalent to the message

clear, pensize 1, penmode 0, frgb 0 0 0, brgb 255 255 255, moveto 0 0


textface text-styles [list] The word textface, followed by one or more names specifying text style(s), sets
the font style(s) to be used when rendering text. Text style names are normal,
bold, and italic.
tilepict arguments [list] The word tilepict, followed by a picture name argument, fills a rectangle by tiling
a picture. Optionally there may follow, four numbers that specify a destination
rectangle in which the picture is tiled and four numbers that specify a source
rectangle that specifies the area of the picture to use in the operation. These
rectangles are specified as left, top, width, and height values in pixels. The
destination rectangle is relative to the top left corner of the lcd display area. The
source rectangle is relative to the top, left corner of the picture. If not present, the
destination rectangle is set to the same size of lcd, and the source rectangle is set
to be the same size as the picture.
write any symbol [list] The word write, followed by any symbol, writes that symbol beginning at the
current pen position, and moves the pen position to the end of the text.
writepict filename [symbol] The word writepict, followed by an optional filename argument, writes the
current contents of the lcd display area to a PNG file.

Attributes
Name Type g/s Description
bgtransparent int Toggles background transparency. The message bgtransparent 1 sets the
def.:0 background of the lcd object to transparent. When set to 1, the background of the
object remains transparent until you clear it using the clear message. When the
attribute value is set to 0 (the default) the background is initially white, consistent
with earlier versions of Max.
border int The word border, followed by a zero or one, toggles the drawing of a border
def.:1 around the lcd object's window, which is on by default. A message of border 0
turns this feature off.
enablesprites int Toggles the drawing of sprites. The message enablesprites 0 turns this feature off
def.:0 (the default). When sprites are enabled, lcd consumes more memory.
idle int Toggles the reporting of idle mouse position over an lcd object. The coordinates of
def.:0 the mouse position are sent out the middle outlet as a two-item list as the mouse
moves. The numbers represent local coordinates relative to the top-left corner of
the lcd display area. The first number is the number of pixels to the right of that
corner, and the second number is the number of pixels down from that corner.
idle 0 turns off this feature, which is off by default.
local int Toggles drawing in the lcd with the mouse. The message local 1 turns the feature
def.:1 on (the default). In either case, lcd will still report the location of the mouse as it is
dragged within the object's rectangle.

Information for box attributes common to all objects

Output
int: Out 3rd outlet: A 1 is sent out the third outlet if the mouse button is currently being held down. A 0 is sent, otherwise.
list: Out 1st outlet: When you draw in the lcd with the mouse button held down, the coordinates of the mouse position are sent
out the outlet as a two-item list as the mouse moves. The numbers represent local coordinates relative to the top-left corner of
lcd. The first number is the number of pixels to the right of that corner, and the second number is the number of pixels down
from that corner.
list: Out 2nd outlet: If the idle attribute is set to one, the coordinates of the mouse position are sent out the second outlet as a
two-item list as the mouse moves. The numbers represent local coordinates relative to the top-left corner of the lcd display area.
The first number is the number of pixels to the right of that corner, and the second number is the number of pixels down from
that corner.
penloc: Out 4th outlet: In response to the getpenloc message, lcd outputs a message consisting of the word penloc followed by
two numbers representing the pen location in local coordinates relative to the top-left corner of the lcd display area. The first
number is the number of pixels to the right of that corner, and the second number is the number of pixels down from that
corner.
update: Out 4th outlet: The word update is output whenever lcd receives an update message from Max telling it to redraw itself.
This is only done when lcd is in onscreen mode

Examples
Draw an angular snake diagram using lcd

See Also
Name Description
mousestate Report the mouse information
panel Colored background area
Max Basic Tutorial 9: Mouse Max Basic Tutorial 9: Mouse Drawing
Drawing
led
Display on/off status

Description
Arguments
None.

Messages
bang Flashes led on and off quickly, and outputs 0.

Clicking on an led toggles it back and forth between bright and dark, outputting 1
and 0.
int input [int] If the number is 0, led shows its darkened state, and outputs 0. If the number is
not 0, led shows its brightened state and outputs 1.
float input [float] Converted to int.
(mouse) Clicking on an led object toggles it back and forth between bright and dark,
outputting 1 and 0.
pict color [int] In left inlet: the word pict, followed by an integer, changes the color used by led.
set on/off-flag (0 or non-zero) The word set, followed by a non-zero number causes led to show its brightened
[int] state, but causes no output; set 0 shows the led object in a darkened state, but
causes no output.
toggle Switches the led from dark to bright and sends 1 out the outlet; or vice-versa,
from bright to dark, sending 0 out the outlet.

Attributes
Name Type g/s Description
bgcolor float Sets the background color of the led object in RGBA format.
blinktime int Specifies the duration (in milliseconds) that the led object will flash when it is
def.:150 clicked upon or receives a bang message.
offcolor float Sets the inactive (off) color of the LED in RGBA format.
oncolor float Sets the active (on) color of the LED in RGBA format.
parameter_enable int Parameter Mode Enable

Information about attributes available for Parameter-aware objects

Information for box attributes common to all objects

Menu Items
Name Description
Color Choosing the Color... menu item from the Object menu when the object is
selected opens a color picker, permitting adjustment to the appearance of the led
object.

Output
int: The output is 1 when led is bright, 0 when it is dark. A bang in the inlet flashes led on and off and sends 0 out the outlet.

Examples
Displays an on/off state, announces activity with a flash, or can be used as a toggle

See Also
Name Description
button Blink and send a bang
pictctrl Picture-based control
togedge Report zero/non-zero transitions
toggle Switch between off and on (0/1)
<
Compare numbers for less than condition

Description
Compares two values to see if one is less than a second. Outputs a 1 if the number is less than the comparison-number or 0 if it is
greater.

Arguments
Name Units Type Opt Description
initial- number opt Sets the initial value, to be compared with a number received in the left inlet. A
comparison-value float argument forces a float comparison.

Messages
bang In left inlet: Performs the comparison with the numbers currently stored. If there
is no argument, < initially holds 0 for comparison.
int input [int] In left inlet: If the number is less than the number in the right inlet, < outputs 1.
Otherwise, < outputs 0.
(inlet1) comparison-value [int] In right inlet: The number is stored to be compared with a number received in the
left inlet.
float input [float] Converted to int before comparison, unless < has a float argument.
set set-input [int] The word set followed by a number will set the input value without causing
output.

Information for box attributes common to all objects

Output
int: 1 if the number in the left inlet is less than the number in the right inlet. 0 if the number in the left inlet is greater than or
equal to the number in the right inlet.

Examples

Number on left is less than number on right... Number on left is not less than number on right

See Also
Name Description
!= Compare numbers for not-equal-to condition
<= Compare numbers as less than or equal to
== Compare numbers for equal-to condition
> Compare numbers for greater than condition
>= Compare numbers for greater than or equal to condition
Max Basic Tutorial 19: Timing Max Basic Tutorial 19: Timing
<=
Compare numbers as less than or equal to

Description
Compares two values to see if one is less than or equal to a second. Outputs a 1 if the number is less than or equal to the
comparison-number or 0 if it is greater.

Arguments
Name Units Type Opt Description
intitial-value number opt Sets the initial value to be compared with a number received in the left inlet. A
float argument forces a float comparison.

Messages
bang In left inlet: Performs the comparison with the numbers currently stored. If there
is no argument, <= initially holds 0 for comparison.
int input [int] In left inlet: If the number is less than or equal to the number in the right inlet,
<= outputs 1. Otherwise, <= outputs 0.
(inlet1) comparison-value [int] In right inlet: The number is stored to be compared with a number received in the
left inlet.
float input [float] Converted to int before comparison, unless <= has a float argument.
set set-input [int] The word set followed by a number will set the input number to the object without
causing output.

Information for box attributes common to all objects

Output
int: 1 if the number in the left inlet is less than or equal to the number in the right inlet. 0 if the number in the left inlet is
greater than the number in the right inlet.

Examples

Is less than... or equal to... Is not less than or equal to

See Also
Name Description
!= Compare numbers for not-equal-to condition
< Compare numbers for less than condition
Compare numbers as less than or equal to
== Compare numbers for equal-to condition
>= Compare numbers for greater than or equal to condition
Max Basic Tutorial 19: Timing Max Basic Tutorial 19: Timing
line
Generate timed ramp

Description
Generate ramps and line segments from one value to another within a specified amount of time.

Arguments
Name Units Type Opt Description
initial number opt Sets the initial value to be stored in line and the output type for the object
(floating-point or integer). If there is no argument, the initial value is 0 and the
output type is int.
grain number opt Sets an initial value for the grain: the time interval at which numbers are sent out.
If the grain is not specified, line outputs a number every 20 milliseconds. The
minimum grain allowed is 1 millisecond; any number less than 1 will be set to 20.

Messages
int input [int] In left inlet: The number is the target value, to be arrived at in the time specified
by the number in the middle inlet. If no time has been specified since the last
target value, the time is considered 0 and line immediately outputs the target
value.

Note: the output type for the line object is set by using the first argument to the
object (see Arguments).

In middle inlet: The number is the time, in milliseconds, in which to arrive at the
target value.

In right inlet: The number is the interval (in milliseconds) at which intermediary
numbers are regularly sent out.
float input [float] Performs the same function as int but with floats only if the object-argument is a
float.
list input [list] The first number specifies a target value, and the second number specifies a total
amount of time (in milliseconds). In that amount of time, numbers are output
regularly in a line from the currently stored value to the target value.
clock setclock object name [symbol] The word clock, followed by the name of an existing setclock object, sets the line
object to be controlled by that setclock object rather than by Maxs internal
millisecond clock. The word clock by itself sets the line object back to using Maxs
regular millisecond clock.
set input [float] In left inlet: The word set, followed by a number, makes that number the new
starting value from which to proceed to the next received target value. The set
message also stops line if it is in the process of sending out numbers.
stop In left inlet: Stops line from sending out numbers, until a new target value is
received.

Information for box attributes common to all objects

Output
bang: Out right outlet: When line has arrived at its target value, bang is sent out.

Note: In practice, the target value is arrived at in just under the amount of time specified (time minus grain).
int: Out left outlet: Numbers are sent out at regular intervals, describing a straight line toward a target value. If a new target
value and time are specified before the line is completed, the new line starts from the most recent output value, in order to avoid
discontinuities.
If a value is received in the left inlet without an accompanying time value, it is sent out immediately (time is considered 0).

Examples

Output values in a straight line... and bang when finished

See Also
Name Description
bline Generate ramps using bang
funbuff Store pairs of numbers
setclock Create and control an alternative clock
uzi Send many bang messages
Max Basic Tutorial 11: Procedural Max Basic Tutorial 11: Procedural Drawing
Drawing
linedrive
Scale numbers exponentially

Description
Scales number from one range to another with an exponential curve. Both the input and output ranges are expressed as single
arguments representing the maximum value. The minimum values are the negative values of the ranges (argument * -1).

Arguments
Name Units Type Opt Description
input number The first argument is the maximum input value. The range used is from (argument
* -1) to (argument).
output number The second argument is the maximum output value. The range used is from
(argument * -1) to (argument).
curve number The third argument specifies the nature of the scaling curve. The third argument
must be greater than 1. The larger the value, the more steeply exponential the
curve is. An appropriate value for this argument is 1.06.
delay ms int opt The fourth argument is the initial delay time in milliseconds. This value is
appended to out, and can be changed via the right inlet.

Messages
int input [int] In left inlet: The number is converted according to the following expression
y = b e^{-a log c} e^{x log c}
where x is the input, y is the output, a, b, and c are the three typed-in arguments,
and e is the base of the natural logarithm (approximately 2.718282). The output is
a two-item list containing y followed by the delay time most recently received in
the right inlet.
(inlet1) delay [int] In right inlet: Sets the current delay time appended to the scaled output. A
connected line~ object will ramp to the new target value over this time interval.
float input-to-conversion [float] In left inlet: The number is converted according to the following expression
y = b e^{-a log c} e^{x log c}
where x is the input, y is the output, a, b, and c are the three typed-in arguments,
and e is the base of the natural logarithm (approximately 2.718282). The output is
a two-item list containing y followed by the delay time most recently received in
the right inlet.

Information for box attributes common to all objects

Output
list: When an int or float is received in the left inlet, a list is sent out containing a scaled version of the input (see the formula
above) and the current delay time.

Examples
Use linedrive for exponential value scaling

See Also
Name Description
expr Evaluate a mathematical expression
scale Map values to an output range
listfunnel
Index and output list elements

Description
Outputs the elements of an incoming list in the format:
[index] [element]
for each element of the list.

Arguments
Name Units Type Opt Description
offset int opt An integer argument is used to specify an offset for the first index value. If no
argument is present, the list elements are numbered beginning with the default
index of 0.

Messages
int input [int] The low index value and the received number are sent out as a two-element list.
float input [float] The low index value and the received number are sent out as a two-element list.
list input [list] Each element of the list is indexed and this index is prepended to the list element
and sent out the outlet as a two-element list. The input list may contain ints,
floats, and symbols (provided that the first element of the list is not a symbol).
anything input [list] Performs the same as list.
offset offset [int] The word offset followed by an integer argument is used to specify an offset for
the first index value.

Information for box attributes common to all objects

Output
list: When a list is received in the inlet, listfunnel outputs a two-element list for each element of the input list, consisting of the
elements index followed the list element. listfunnel is designed for conveniently replacing a combination of unpack and funnel
objects.

Examples

Use listfunnel not only for convenience, but also for variable-length lists.

See Also
Name Description
funnel Tag data with its inlet number
spray Distribute a value to a numbered outlet
loadbang
Send a bang when a patcher is loaded

Description
Outputs a bang automatically when the file is opened or when the patch is part of another file that is opened.

Arguments
None.

Messages
bang Sending a bang message to a loadbang object causes it to output a bang message.
(mouse) Double-clicking on a loadbang object causes it to output a bang message.
loadbang Same as bang.

Information for box attributes common to all objects

Output
bang: Sent automatically when the patch is loaded. You can also cause loadbang to send out a bang by double-clicking on it in a
locked patcher, or by sending a loadbang message to a thispatcher object in the same patcher. Holding down the Shift and
Command keys on Macintosh or Shift and Control keys on Windows while a patch is loading prevents loadbang objects in that
patch from sending any output.

Examples

Set initial values when a patch is loaded... or start a process automatically

See Also
Name Description
active Send 1 when patcher window is active, 0 when inactive
button Blink and send a bang
closebang Send a bang on close
freebang Send a bang when a patcher is freed
loadmess Send a message when a patch is loaded
thispatcher Send messages to a patcher
Max Basic Tutorial 13: Movie Max Basic Tutorial 13: Movie Sequencing
Sequencing
loadmess
Send a message when a patch is loaded

Description
Outputs a message automatically when the file is opened, or when the patch is part of another file that is opened.

Arguments
Name Units Type Opt Description
message symbol Any arguments you type into a loadmess object are treated as a message to be
sent when output is triggered.

Messages
bang Sending a bang message to a loadmess object causes it to output its typed
message.
(mouse) Double-clicking on a loadmess object causes it to output its typed message.
set message [list] The word set followed by any message will set the message held by loadmess
without any output. (Can be used for output in conjunction with bang.)

Attributes
Name Type g/s Description
defer int When enabled, the output of the loadmess object is deferred.
def.:0

Information for box attributes common to all objects

Output
symbol: The loadmess object's typed message is sent automatically when the patch is loaded. As with the loadbang object, you
can also cause loadmess to send out its message by double-clicking on it in a locked patcher, or by sending a loadbang message
to a thispatcher object in the same patcher. Holding down the Shift and Command keys on Macintosh or Shift and Control keys
on Windows while a patch is loading prevents loadmess objects in that patch from sending any output.

Examples

The same thing as loadbang and a message box for extremely lazy people...

See Also
Name Description
active Send 1 when patcher window is active, 0 when inactive
button Blink and send a bang
closebang Send a bang on close
freebang Send a bang when a patcher is freed
loadbang Send a bang when a patcher is loaded
thispatcher Send messages to a patcher
&&
Perform a logical AND

Description
Compares one number to another and outputs a 1 if the two numbers are both non-zero or a 0 if either number is 0.

Arguments
Name Units Type Opt Description
comparison-value int opt Sets an initial value to be stored by &&. A number in the right inlet changes the
value set by the argument.

Messages
bang In left inlet: Performs the operation with the numbers currently stored. If there is
no argument, && initially holds 0.
int input [int] If the number in both inlets is not 0, then the output is 1. If the number in one or
both of the inlets is 0, then the output is 0. A number in the left inlet triggers the
output.
(inlet1) comparison-value [int] In right inlet: The number is compared to the number in the left inlet to determine
output but only a number in the left inlet will trigger output.
float input [float] Converted to int.
set set-input [int] The word set followed by a number will set the input value without causing
output.

Information for box attributes common to all objects

Output
int: If the number in the left inlet and the number in the right inlet (or specified by the argument) are both not 0, then the
output is 1. Otherwise, the output is 0.

Examples

Both numbers are not 0... Used to combine comparisons

See Also
Name Description
& Bitwise intersection of two numbers
| Bitwise union of two numbers
|| Perform a logical OR
Max Basic Tutorial 19: Timing Max Basic Tutorial 19: Timing
||
Perform a logical OR

Description
Compares one number to another and outputs a 1 if the either number is non-zero or a 0 if both number are 0.

Arguments
Name Units Type Opt Description
comparison-value int opt Sets an initial value to be stored by ||. A number in the right inlet changes the
value set by the argument.

Messages
bang In left inlet: Performs the operation with the numbers currently stored. If there is
no argument, || initially holds 0.
int input [int] If the number in either inlet is not 0, then the output is 1. If the number in both
of the inlets is 0, then the output is 0. A number in the left inlet triggers the
output.
(inlet1) comparison-value [int] In right inlet: The number is compared to the number in the left inlet to determine
output but only a number in the left inlet will trigger output.
float input [float] Converted to int.
set set-input [int] The word set followed by a number will set the input value without causing
output.

Information for box attributes common to all objects

Output
int: If either the number in the left inlet or the number in the right inlet (or specified by the argument) is not 0, then the output
is 1. Otherwise, the output is 0.

Examples

One of the numbers is not 0... Used to combine comparisons

See Also
Name Description
& Bitwise intersection of two numbers
&& Perform a logical AND
| Bitwise union of two numbers
Max Basic Tutorial 19: Timing Max Basic Tutorial 19: Timing
makenote
Generate a note-on/note-off pair

Description
Outputs a MIDI note-on message paired with a velocity value followed by a note-off message after a specified amount of time.
This allows for generative MIDI output without having to manage note-off generation.

Arguments
Name Units Type Opt Description
velocity number opt Sets an initial velocity value (int or float) to be paired with incoming pitch
numbers. If there is no argument, the initial velocity is 0.
duration number opt Sets an initial note duration (time before a note-off is sent out), in any of Max's
time units. A simple int or float will set the duration in milliseconds. If the second
argument is not present, the note-off follows the note-on immediately.
channel number opt Sets an initial MIDI channel number. If a third argument is used, the makenote
object will have an additional fourth inlet (which specifies MIDI channel number)
and an additional third outlet (which specifies MIDI output channel).

Messages
int input [int] In first inlet: The number is treated as a pitch value for a MIDI note-on message.
It is paired with a velocity value and the numbers are sent out the outlets. After a
certain time, a note-off message (a note-on with a velocity of 0) is sent out for that
pitch.

In second inlet: The number is stored as a velocity to be paired with pitch


numbers received in the left inlet.

In third inlet: The number is stored as the duration that makenote waits before a
note-off message is sent out.
In fourth inlet: The number specifies a MIDI output channel. The fourth inlet will
only be present if the makenote object is initialized with three arguments.
float input [float] In first inlet: The number is treated as a pitch value for a MIDI note-on message.
It is paired with a velocity value and the numbers are sent out the outlets. After a
certain time, a note-off message (a note-on with a velocity of 0) is sent out for that
pitch.

In second inlet: The number is stored as a velocity to be paired with pitch


numbers received in the left inlet.

In third inlet: The number is stored as the duration that makenote waits before a
note-off message is sent out.
In fourth inlet: The number specifies a MIDI output channel. The fourth inlet will
only be present if the makenote object is initialized with three arguments.
list input [list] In left inlet: The second number is treated as the velocity and is sent out the right
outlet. The first number is treated as the pitch and is sent out the left outlet. A
corresponding note-off message is sent out later.
If the makenote object is instantiated with three arguments, a four-item list can
be used which contains an additional fourth element specifying the MIDI channel
number, which is sent out the rightmost outlet of the object.
anything input [list] Performs the same function as list.
clear Erases all notes currently held by makenote, without sending note-offs.
clock clock-name [symbol] The word clock, followed by the name of an existing setclock object, sets the
makenote object to be controlled by that setclock object rather than by Maxs
internal millisecond clock. The word clock by itself sets the makenote object back
to using Maxs regular millisecond clock.
stop Causes makenote to send out immediate note-offs for all pitches it currently
holds.

Attributes
Name Type g/s Description
duration atom The duration that makenote waits before a note-off message is sent out.
repeatmode int Sets behavior when a note is retriggered. The modes are:

repeatmode 0 (default): There is no pre-specified behavior when when you repeat


a pitch before the note-off for that pitch has been sent.
repeatmode 1: If a note is still playing when you retrigger it, the makenote object
will send a note-off (velocity 0) message to stop the first note and then send a new
note-on message.
repeatmode 2: If a note is still playing when you retrigger it, the makenote object
will cancel the scheduled output of the first note - only the last played note will
send note-off (velocity 0) message.
'Poly' = TEXT_HERE
'Re-trigger' = TEXT_HERE
'Stop Last' = TEXT_HERE

Information for box attributes common to all objects

Output
int: Out left outlet: The number received in the left inlet is sent out immediately, paired with a velocity value out the other outlet.
After a certain duration, the same number is sent out paired with a velocity of 0.

Out right outlet: The number in the middle inlet is sent out as a velocity value in conjunction with a pitch value out the left outlet.
After a certain duration, 0 is sent out paired with the same pitch.

Examples

Supply note-offs for note-ons generated within Max

See Also
Name Description
flush Output MIDI note-offs for held notes
midiout Transmit raw MIDI data
noteout Transmit MIDI note messages
nslider Output numbers from a notation display
stripnote Filter out note-off messages
transport Control a master clock
xnoteout Format MIDI note messages with release velocity
Max MIDI Tutorial 2: MIDI Note Max MIDI Tutorial 2: MIDI Note Management
Management
match
Watch for a message match, then output the message

Description
Watches an incoming stream of ints, floats, symbols, lists, or messages, and outputs the stream after it has met the specification of
its arguments.

Arguments
Name Units Type Opt Description
match-list list The arguments specify numbers to look for, in the proper order. The word nn can
be used as a wild card that will match any number.

Messages
int input [int] If the numbers match the arguments, in the proper order, they are sent out as a
list.
float input [float] If the numbers match the arguments, in the proper order, they are sent out as a
list.
list input [list] If the input-list matches the arguments, in the proper order, they are sent out as a
list.
anything input [list] Performs the same as list.
clear Causes match to forget all numbers it has received up to that time.
set match-list [list] The word set, followed by a list of numbers, specifies a new series of numbers
match will look for.

Information for box attributes common to all objects

Output
list: The numbers received in the inlet are compared with the arguments. If the numbers are the same, and in the same order,
they are sent out the outlet as a list.

Examples

Numbers must be the same, and in the same order

See Also
Name Description
iter Break a list into individual messages
join Combine items into a list
pack Create a list
select Output bangs based on input matching
matrixctrl
Matrix switch control

Description
Provides a user interface control containing a group of cells in a grid. Cell states can either be on/off or incremental steps. This
object is especially useful for controlling the matrix~ object.

Arguments
None.

Messages
bang bang causes matrixctrl to dump its current state in lists of three values for each
cell pair, in the format

horizontal-coordinate vertical-coordinate value


list values [list] A list of ints sets cells in the matrixctrl object using the format <horizontal-
coordinate vertical-coordinate value>. Multiple triplets of values can be used to set
more than one cell. Coordinates for the cells start at 0 in the upper-left hand
corner and the values for each cell start at 0 and go up to the value range minus
one, set by the object's inspector. Substituting the symbols inc and dec in place of
the value will increment or decrement that cell coordinate by a value of one.
Changing the cell state with a list causes the list to be output from matrixctrl.
cellpicture filename [symbol] This is a legacy message - it has been superseded by the cellpict attribute.
clear The word clear will set the value of all cells to 0.
bkgndpicture filename [symbol] This is a legacy message - it has been superseded by the bkgndpict attribute.
enablecell coordinates [list] The word enablecell, followed by a list of number pairs which specify the
horizontal and vertical coordinates of a cell or cells, will set any designated cell or
cells which have been disabled using the disablecell message to respond to mouse
clicks again. The enablecell message expects at least one pair of numbers, but
more may be added to enable multiple cells (e.g., enable 1 1 1 2 2 2).
disable coordinates [list] Performs the same as disablecell.
disablecell coordinates [list] The word disablecell, followed by a list of number pairs which specify the
horizontal and vertical coordinates of a cell or cells, sets the designated cell or cells
so that they do not respond to mouse clicks. The disablecell message expects at
least one pair of numbers, but more may be added to disable multiple cells (e.g.,
disable 0 0 3 4 9 12). Although disabled cells will ignore mouse clicks, their
values can be set using messages.
getcolumn column [int] The word getcolumn, followed by a number, sends the values of the cells in the
column designated by the number out its right outlet.
getrow row [int] The word getrow, followed by a number, sends the values of the cells in the row
designated by the number out its right outlet.
(mouse) A mouse click on a cell will increase its value by one. Values in matrixctrl will
wrap back to 0 once they have reached their maximum possible state. Dragging
across several cells will set their values to that of the first cell clicked. Dragging
across cells while holding down the Shift key will allow you to drag in straight
horizontal or vertical lines only.
set input [list] The word set, followed by a list as described above, changes the state of
matrixctrl without echoing the values to the output.
readanycell filename [list] The word readanycell followed by the name of a file will read any type of file into
the matrixctrl object and attempt to interpret it as a cell image.
readanybkgnd filename [list] The word readanybkgnd followed by the name of a file will read any type of file
into the matrixctrl object and attempt to interpret it as a background image.
Attributes
Name Type g/s Description
active int Toggles matrixctrl to ignore or respond to mouse clicks, respectively. By default,
def.:1 matrixctrl responds to mouse clicks.
autosize int Toggles automatically resizing to rows and columns for the matrixctrl object's
def.:0 display area when a cell picture is added.
bkgndpict symbol Designates the graphics file that the matrixctrl object will use for the matrix
def.:<default> background image. By convention, the matrixctrl object uses images saved in
Portable Network Graphics (.png) format. If you are using Max on Windows and
want to to work with images other than PNG or PICT files, we recommend that
you install QuickTime and choose a complete install of all optional components.
The symbol used as a filename must either be the name of a file in Max's current
search path, or an absolute pathname for the file (e.g. "MyDisk:/Documents/UI
Pictures/CoolBkgnd.png"). The word bkgndpicture by itself puts up a standard
Open Document dialog box.
cellpict symbol Designates the graphics file that the matrixctrl object will use for each cell. By
def.:<default> convention, the matrixctrl object uses images saved in Portable Network Graphics
(.png) format. If you are using Max on Windows and want to to work with images
other than PNG or PICT files, we recommend that you install QuickTime and
choose a complete install of all optional components. The symbol used as a
filename must either be the name of a file in Max's current search path, or an
absolute pathname for the file (e.g. "MyDisk:/Documents/UI
Pictures/Cell.png").
clickedimage int Specifies that the graphics file used by the matrixctrl object contains an additional
def.:1 image to be displayed when a cell is clicked.
clickvalue int Toggles the click value mode. If the clickvalue message is followed by a zero or a
def.:-1 positive number, clicking on a cell sets its value to the given number. If clickvalue
is followed by a negative number, the matrixctrl object reverts to its default
behavior in which clicking a cell increments its value. The clickvalue message
allows the use of the matrixctrl object to create grid editors by creating graphics
files which contain a sequence of images, each of which is assigned to a different
value; as you click through the sequence of images, the cell image will change to
reflect velocity, note, etc.
columns int Sets the number of columns in the matrixctrl object's display.
def.:8
dialmode int Toggles causing the object to behave like a matrix of dials where a cell will need to
def.:0 be clicked and dragged on to change its value. dialmode 0 will allow cells within
the matrix to react to a simple click.
dialtracking int Sets whether or not the matrixctrl object will use vertical mouse tracking while it
def.:0 is in dialmode.
horizontalmargin int Sets a horizontal margin (in pixels) between the outermost cells and the edge of
def.:1 the matrixctrl object's bounding box.
horizontalspacing int Sets the horizontal distance (in pixels) between adjacent cells in the matrixctrl
def.:0 object.
imagemask int Specifies that the matrixctrl cell graphics file has additional rows of images for
def.:0 use as image masks. This attribute is present for legacy support - it has been
superseded by the use of alpha channels in images.
inactiveimage int Specifies that the matrixctrl cell graphics file has additional rows of images for
def.:1 use in an inactive state (set with an active 0 message).
invisiblebkgnd int Specifies that the matrixctrl will be drawn without a background image, and its
def.:0 cells will be superimposed over any underlying Max objects. invisiblebkgnd 0
disables this feature.
one/column int One Non-Zero Cell Per Column
def.:0
one/matrix int Toggles only allowing one cell in the entire object to have a non-zero state. Setting
def.:0 any other cell in the matrix to a non-zero state causes any other non-zero cells to
change to the zero state. one/matrix 0 removes this constraint.
one/row int Toggles only allowing one cell per row to have a non-zero state. Setting any cell in
def.:0 a row to a non-zero state causes any other non-zero cells to change to the zero
state. one/row 0 removes this constraint.
parameter_enable int Parameter Mode Enable
range int Sets the number of possible states each cell can have. It must be set to a value of
def.:2 at least 2 (for states 0 and 1).
rows int Sets the number of rows in the matrixctrl object's display.
def.:4
scale int Toggles scaling graphics when the matrixctrl object's display area is resized.
def.:1
verticalmargin int Sets a vertical margin (in pixels) between the outermost cells and the edge of the
def.:1 matrixctrl object's bounding box.
verticalspacing int Sets the vertical distance (in pixels) between adjacent cells in the matrixctrl
def.:0 object.

Information about attributes available for Parameter-aware objects

Information for box attributes common to all objects

Picture File Format


Specifications: The background pictures the matrixctrl object uses are, by convention, saved in Portable Network Graphics (.png)
format. If you are using Max on Windows and want to to work with images other than PNG or PICT files, we recommend that
you install QuickTime and choose a complete install of all optional components. The symbol used as a filename must either be
the name of a file in Max's current search path, or an absolute pathname for the file (e.g. "MyDisk:/Documents/UI
Pictures/Cell.png"). If the matrixctrl is larger than the chosen picture, copies of the picture will be added to fill the object.

Cell picture files must be in the following format:

The picture is made up of a grid of images. All images have the same width and height. Each column of images represents one cell
state. The picture must have at least two columns, since cells must have at least two states.

The first row of images is used for the idle (or "not clicked") appearance of the cells. The first row of images is mandatory; all
subsequent rows are optional. The second row are images for the clicked appearance; these images will be used to draw the cell
when it is clicked. The appearance of the cell reverts to its idle image when the mouse is released. The third row of images are
used when the matrixctrl is in its inactive state, i.e. when it has received an active 0 message.

Image masks can be used to create cells with non-rectangular outlines. These masks are in the lower rows of the picture file. If
you wish to use masks for any of the cell images, you must provide masks for all of them--each row of images will have a
corresponding row of masks. Like all masks for Max's picture-based controls, black pixels create areas of the corresponding
image that will be drawn, and while pixels create invisible areas.

Output
list: When a cell changes state in response to a mouse click, a list is sent out the matrixctrl object's left outlet. The list contains
the column, row, and value (state) of the clicked control. Individual cells can also be set by sending lists to the object's left inlet.
Rows and columns are numbered starting with zero, at the upper-left corner of the matrix.

The numbers received in the inlet are compared with the arguments. If the numbers are the same, and in the same order, they
are sent out the outlet as a list.

Examples
matrixctrl can be used to control multiple gates and switches at once

See Also
Name Description
dial Output numbers using an onscreen dial
kslider Output numbers from an onscreen keyboard
pictctrl Picture-based control
pictslider Picture-based slider control
router Route messages to multiple locations
rslider Display or change a range of numbers
slider Move a slider to output values
ubutton Send a bang with a transparent button
Max Basic Tutorial 21: Max Basic Tutorial 21: Controlling Data Flow
Controlling Data Flow
Tutorial 26: MIDI Control of Tutorial 26: MIDI Control of Video
Video
maximum
Output the highest value

Description
Watches an input stream for any number which is greater than its most recently set maximum, sets that new number as the
maximum, and outputs it.

Arguments
Name Units Type Opt Description
initial int or float opt Sets an initial value to be compared with numbers received in the left inlet. If the
argument contains a decimal point, all numbers are compared as floats, and the
output is a float. If there is no argument, the initial value is 0.

Messages
bang In left inlet: Sends the most recent output out the outlet again.
int input [int] In left inlet: If the number is greater than the value currently stored in maximum,
it is sent out the outlet. Otherwise, the stored value is sent out.
(inlet1) input [int] In right inlet: The number is stored for comparison with subsequent numbers
received in the left inlet.
float input [float] Converted to int, unless there is a float argument, in which case all numbers are
compared as floats.
(inlet1) input [float] Converted to int, unless there is a float argument, in which case all numbers are
compared as floats.
list input [list] In left inlet: The numbers in the list are all compared to each other, and the
greatest value is sent out the outlet. The value stored in maximum is replaced by
the next greatest value in the list.The maximum object accepts lists of up to 256
elements.

Information for box attributes common to all objects

Output
float: The number received in the left inlet is compared with the value currently held by maximum (or numbers received as a list
are compared with each other), and the greatest of the numbers is sent out the outlet. Floats are output only if there is an
argument with a decimal point.
int: The number received in the left inlet is compared with the value currently held by maximum (or numbers received as a list
are compared with each other), and the greatest of the numbers is sent out the outlet.

Examples

The output is the greater of two numbers, or the greatest in a list of numbers

See Also
Name Description
minimum Output the smallest value
past Notify when a threshold is passed
peak Output larger numbers
> Compare numbers for greater than condition
mean
Calculate a running average

Description
Calculates the mean (average) of all the numbers it has received and outputs it.

Arguments
None.

Messages
bang Sends out the previous output (the stored average value).
int input [int] The number is added to the sum of all numbers received up to that point, and the
mean is sent out.
float input [float] The number is added to the sum of all numbers received up to that point, and the
mean is sent out.
list input [list] The numbers in the list are added together, the sum is divided by the number of
items in the list, and the mean is sent out. All previously received numbers are
cleared from memory.
clear Resets the stored and calculated contents of the object to zero.

Information for box attributes common to all objects

Output
float: Out left outlet: The mean (average) value of all numbers received up to that point, or of all the numbers received together in
a list.

Out right outlet: How many numbers have been included in the averaging process.
int: Out left outlet: The mean (average) value of all numbers received up to that point, or of all the numbers received together in a
list.

Out right outlet: How many numbers have been included in the averaging process.

Examples

Find the average value of many numbers

See Also
Name Description
accum Store, add to, and multiply a number
anal Make a histogram of number pairs
bag Store a collection of numbers
histo Create a histogram of numbers received
prob Create a weighted transition table
menubar
Put up a custom menu bar

Description
The menubar object provides control over the menu bar. It allows your patch to put up its own menus, and add items to standard
File and Edit menus. When a menu item is chosen, the item number is sent out the outlet corresponding to the menu containing
the item.

Arguments
Name Units Type Opt Description
display and behavior int opt The argument sets the number of menus in the object's menu bar. If present, it
must be at least 5 (one additional menu). The four default menus, which are
always present, are File, Edit, Windows., and Help. On Macintosh, the Standard
System Menu with the Apple icon and the Max application menu will appear to the
left of the other menus.

Messages
int show-menus-flag (0 or A non-zero number displays the menubar object's menus, 0 restores the previous
non-zero) [int] contents of the menu bar (either the Max menus or the menus of another
menubar object).
about text of first menu item This is a script message (see above) used to modify standard menus, and is the
[list] first item to appear in a script. It takes the following arguments:
Text of the first menu item (i.e. About My Program).

On the Macintosh the About item appears as the first item in the application menu
(Max menu). On Windows, it appears as the first item in the Help menu. The
message apple may be used optionally for compatibility with older Macintosh
versions of Max.
append menu number, item This is a script message (see above) used to append new menu items. It takes the
number, text [list] following arguments:
Menu number
Item number
Text of item
metacharacters (Optional.)

The append message appends an item to an additional menu previously defined


with a menutitle message.
You can alter the appearance of a menu item by including metacharacters in the
item text (see the item listing below for more information).
apple text of first menu item This is a script message (see above) used to modify standard menus, and, when
[list] used, is the first item to appear in a script. It takes the following arguments:
Text of the first menu item (i.e. About My Program).

On the Macintosh the About item appears as the first item in the application menu
(Max menu). On Windows, it appears as the first item in the Help menu. This
message may be used optionally for compatibility with older Macintosh versions of
Max.
(mouse) Double-clicking on the menubar object in a locked patcher will open a text editor
window where you can insert a script to configure the menubar's appearance and
behavior.
checkitem checkitem [list] Followed by a menu number, an item number, and a code 0 or 1, checkitem puts
a check before the specified item if the code is 1, otherwise it removes the check.
closeitem This is a script message (see above) used to modify standard menus. It causes a
Close item to appear in the File menu, for closing the active window.
edit item number, text [list] This is a script message (see above) used to modify standard menus. It takes the
following arguments:
Item number to output
Text of item to add to edit menu

The edit message inserts items into the standard Edit menu after the Clear item
and before the Overdrive and Resume items (which are moved into the Edit menu
when menubar is activated). A blank line separates the custom inserted items
from the default items. Each item has a number associated with it which is sent
out the third outlet of menubar when the item is chosen. The order in which your
additional items appear in the Edit menu is determined by their order in the
script, not by the (arbitrary) number associated with each item.
enableitem menu-number, item- Followed by a menu number, an item number, and a code 0 or 1, enableitem
number, and enables the specified item if the code is 1, otherwise it disables (and grays out) the
enable/disable-flag (0 or item.
1) [list]
end This is a script message (see above) used to complete a script definition. The
builds the menus and reports any errors encountered.
file item number, text [list] This is a script message (see above) used to modify standard menus. It takes the
following arguments:
Item number to output
Text of item to add to file menu

The file message inserts items at the top of the standard File menu (before the
Midi Setup... menu item). Each item has a number associated with it which is
sent out the when the item is chosen. The order in which your additional items
appear in the File menu is determined by their order in the script, not by the
(arbitrary) number associated with each item.
item menu number, item This is a script message (see above) used to create new menus and menu items. It
number, text [list] takes the following arguments:
Menu number
Item number
Text of item
metacharacters (Optional.)

The item message adds an item to an additional menu previously defined with a
menutitle message. The order in which your items appear in the menu is
determined by their order in the script, not by the (arbitrary) number associated
with each item. The item number argument only specifies the number which is
sent out the menubar objects outlet when the user chooses this item. Its a good
idea to start your item numbers at 1 and list the items in the order you want them
to appear in a menu.
You can alter the appearance of a menu item by including metacharacters in the
item text. For more on metacharacters, consult the Apple QuickTime Developer
documentation found at:
developer.apple.com
A few of the recognized meta-characters are:
/ : followed by a character, assigns that character as a Command-key equivalent
< : followed by B, I, O, S, or U, specifies a font style (such as O for outline)
! : followed by a character, marks the menu item with that character
(: disables the menu item

Thus, these special characters cannot appear as part of the actual item text. For
example, the text On/Off will appear as Onff_O, not as On/Off.
markitem menu-number, item- (Macintosh only) Followed by a menu number, an item number, and an ASCII
number, and ASCII-code character code, markitem places the character next to the specified item. Common
[list] mark character ASCII codes are 18 for the check mark and 19 for the diamond
mark. You may also wish to use the em dash (209) or bullet (165).
menutitle item number, name of This is a script message (see above) used to create new menus and menu items. It
menu [list] takes the following arguments:
Menu number (must be at least 5 and must not exceed the number of outlets
specified in the argument to the menubar object.
Name of menu

The menutitle message adds a new menu before the Window menu. The first
additional menu is number 5. The menu number determines both the order of the
additional menu in the menu bar and the outlet it uses when the user chooses its
items. A menutitle message must appear in the script before any item messages
that refer to its menu number.
newitem menu item number [int] This is a script message (see above) used to modify standard menus. It takes the
following arguments:
Item number to output.

The newitem message followed by a non-zero number directs Max to send the
specified number out the menubar objects File menu outlet when the user
chooses the New command from the File menu, instead of opening a new patcher
window. The message newitem 0 (or the absence of any newitem message)
causes the New command to behave normally.
open menu item number [int] This is a script message (see above) used to modify standard menus. It takes the
following arguments:
Item number to output.

The open message followed by a non-zero number directs Max to send the
specified number out the menubar objects File menu outlet when the user
chooses the Open... command from the File menu, instead of displaying the
Open Document dialog box. The message open 0 (or the absence of any open
message) causes the Open... command to behave normally.
saveas menu item number [int] This is a script message (see above) used to modify standard menus. It takes the
following arguments:
Item number to output.

The saveas message followed by a non-zero number directs Max to send the
specified number out the menubar objects File menu outlet when the user
chooses Save or Save As... from the File menu, instead of performing the
standard Save actions. The number sent out the outlet when Save is chosen will
be 1 less than the number sent when Save As... is chosen. The message saveas 0
(or the absence of any saveas message) causes the Save and Save As...
commands to behave normally.

Information for box attributes common to all objects

Examples
An implementation of the example menubar script

See Also
Name Description
umenu Create and fill a pop-up menu
message
Send any message

Description
message displays and sends any given message with the capability to handle specified arguments.

Arguments
Name Units Type Opt Description
message list The initial contents of the message box are typed in when the patcher window is
unlocked. Any message can be contained in a message box. Certain characters
have special meaning.
changeable-arg symbol A dollar sign ($), followed immediately by a number in the range 1-9, is a
changeable argument. This argument's value can be replaced by the corresponding
item in a list received in the inlet. (Example: $2 stores the second item in a list as
its value before sending out the contents of the message box .) The value of a
changeable argument is initially 0.
comma symbol A comma (,) divides a message into separate messages which will be sent out in
order. (Example: 3, 4, 5 sends out 3, then 4, then 5.)
backslash symbol A backslash (\) is used to negate (escape) the traits of a special character. When a
backslash immediately precedes a dollar sign, comma, or semicolon, the character
is treated as a normal character. (Example: Notes played were C\, E\, and G.)

Messages
bang In left inlet: Sends out the contents of the message box. A mouse click on the
message box has the same effect.

In right inlet: Sets the contents of the message box to 'bang' without triggering
output.
int input [int] In left inlet: The number replaces the value stored in the argument $1, if such an
argument exists, then sends out the contents of the message box.

In right inlet: Sets the contents of the message box without triggering output.
float input [float] In left inlet: The number replaces the value stored in the argument $1, if such an
argument exists, then sends out the contents of the message box.

In right inlet: Sets the contents of the message box without triggering output.
list input [list] Each item in the list replaces the value of its corresponding $ argument, if such an
argument exists, then sends out the contents of the message box.

In right inlet: Sets the contents of the message box without triggering output.
anything message [list] See the list listing
append message [list] The word append followed by any message will set the message box to display
that message after any text which it already contains without triggering output.
(mouse) A mouse click on a message box sends its contents out the object's outlet.
prepend message [list] The word prepend followed by any message will set the message box to display
that message before any text which it already contains without triggering output.
set message [list] The word set, followed by a message, sets the contents of the message box to that
new message, without triggering output. The word set by itself clears the contents
of the message box .
symbol input [symbol] In left inlet: The symbol replaces the value stored in the argument $1, if such an
argument exists, then sends out the contents of the message box.
In right inlet: Sets the contents of the message box without triggering output.

Attributes
Name Type g/s Description
bgcolor float Background Color
bgcolor2 float Sets the second (lower) gradient color of the message box in RGBA format. This
attribute is enabled for editing in the Inspector by setting the gradient attribute
value to 1.
gradient int Enables the use of a second gradient color applied to the lower portion of the
message box . The default is 0 (off), although all message box objects show a
slight amount of gradient shading. When the use of a second gradient color is
enabled, the bgcolor2 (lower gradient color) attribute is enabled for editing in the
Inspector.

Information for box attributes common to all objects

Menu Items
Name Description
Color Choosing the Color... menu item from the Object menu when the object is
selected opens a color picker, permitting adjustment to the appearance of the
message box.

Output
anything: The contents of the message box are sent out the outlet. If a semicolon is present, the rest of the message (or up to
the next semicolon) is sent to the specified receive object, rather than out the outlet.

Examples

Send a simple message, or construct a message of any degree of complexity

See Also
Name Description
append Append arguments to the end of a message
atoi Convert ASCII characters to integers
comment Explanatory note or label
itoa Convert integers to ASCII characters
jit.cellblock Two-dimensional storage and viewing
prepend Add a message in front of input
receive Receive messages without patch cords
Max Basic Tutorial 1: Hello Max Basic Tutorial 1: Hello
Max Basic Tutorial 2: Bang! Max Basic Tutorial 2: Bang!
metro
Output a bang message at regular intervals

Description
Acts as a metronome which outputs bang s at a regular, specified interval. This object uses the Max time format syntax, so the
interval that the metro object uses can be either fixed or tempo-relative.

Arguments
Name Units Type Opt Description
interval ms number opt The optional first argument sets an initial value for the time interval at which
metro sends its output. This time interval can be either a number which specifies
time in milliseconds (e.g. metro 100) or notevalue (e.g. metro 4n).

Note: While the metro object lets you specify time in any of Max's standard time
formats, the interval attribute argument should be used when specifying time in
any other time unit besides milliseconds or notevalues (e.g. metro @interval
11025 samples).

If there is no argument, the initial time interval is 5 milliseconds.

Messages
bang In left inlet: starts the metro object.
int input [int] In left inlet: Any number other than 0 starts the metro object. At regular intervals,
metro sends a bang out the outlet. 0 stops metro.

In right inlet: The number is the time interval, in milliseconds, at which metro
sends out a bang. A new number in the right inlet does not take effect until the
next output is sent.
float input [float] Performs the same function as int.
list input [list] In right inlet: A list may be used to specify time in one of the Max time formats.
anything interval [list] Same as list.
clock name [symbol] The word clock, followed by the name of an existing setclock object, sets the
metro object to be controlled by that setclock object rather than by Maxs internal
millisecond clock. The word clock by itself sets the metro object back to using
Maxs regular millisecond clock.
stop In left inlet: Stops metro.

Attributes
Name Type g/s Description
active int Turns the metro on and off.
autostart int If turned on (non-zero) the metro will begin running automatically at the time
specified with the autostarttime attribute.
autostarttime atom If the autostart attribute is enabled (non-zero) the metro will begin running
automatically at the time specified with the this attribute. The autostart operates
as a timepoint object that is internal to metro.
defer float Turn this on to send output in the low-priority queue.
interval atom Sets the The time interval at which metro sends out a bang. Time can be specified
in any of the time formats used in Max.
quantize atom Send output only on the specified time-boundary if appropriate. This is achieved
by making internal adjustments to the times used for sending output. The
quantization can be specified in the following time formats: bars.beats.units, ticks
or note values.
If the applicable time is a 'fixed' unit (for example: ms, seconds, hz, samples, etc.)
then this attribute will have no effect.
transport symbol This attribute names a master time transport. If the time is specified using a
'relative' unit (for example: ticks, bars.beats.units, or notevalues), then the named
transport is used to determine delay times based on tempo, time-signature, and
other related information.

Information for box attributes common to all objects

Output
bang: bang is sent immediately when metro is started, and at regular intervals thereafter.

Examples

Repeatedly send a message or trigger a process

See Also
Name Description
clocker Report elapsed time, at regular intervals
counter Keep count based on bang messages
cpuclock Retrieve the CPU time
delay Delay a bang
setclock Create and control an alternative clock
tempo Output numbers at a metronomic tempo
transport Control a master clock
uzi Send many bang messages
Max Basic Tutorial 4: Metro and Max Basic Tutorial 4: Metro and Toggle
Toggle
midiflush
Send MIDI note-offs for hanging note-ons

Description
Analyzes a raw MIDI stream (from midiin or seq), counting the number of note-ons received for each note and MIDI channel.
When it is sent a bang, MIDI note-off messages are sent for any notes which have not been turned off.

Arguments
None.

Messages
bang When midiflush receives a bang, it outputs MIDI note-off messages for all note-
ons which have not been matched by note-offs since the object was created (or the
last bang message was sent).
int input [int] Raw MIDI data from a source such as seq or midiin will be passed through
unchanged, while the object observes which note-on messages on each channel
have not received matching note-off messages.
clear Erases any note-ons held by midiflush, without sending any note-offs.

Information for box attributes common to all objects

Output
int: midiflush passes all its input through to its output, and sends MIDI note-off messages (as a series of numbers) for all note-
ons which have not been matched by note-offs at its input.

Examples

When midiflush receives a bang, it supplies note-offs for any held note-ons

See Also
Name Description
flush Output MIDI note-offs for held notes
midiin Output raw MIDI data
midiinfo Fill a pop-up menu with MIDI device names
midiout Transmit raw MIDI data
Max MIDI Tutorial 2: MIDI Note Max MIDI Tutorial 2: MIDI Note Management
Management
Max MIDI Tutorial 4: MIDI Basic Max MIDI Tutorial 4: MIDI Basic Sequencing
Sequencing
midiformat
Prepare data in the form of a MIDI message

Description
Numbers received in the inlets are used as data for MIDI messages. The data is formatted into a complete MIDI message (with the
status byte determined by the inlet) and sent out the outlet as individual bytes.

Arguments
Name Units Type Opt Description
initial-MIDI-channel- int opt Sets an initial value for the channel number of the MIDI messages. Numbers
number greater than 16 are wrapped around to stay between 1 and 16. If there is no
argument, the channel number is initially set to 1.
initial-MIDI-channel- float opt Converted to int.
number

Messages

Information for box attributes common to all objects

Output
int: MIDI messages are sent out as individual bytes, for recording by the seq object or for transmission by the midiout object.

Examples

Numbers are formatted into MIDI messages and sent out as individual bytes

See Also
Name Description
borax Report note-on and note-off information
midiinfo Fill a pop-up menu with MIDI device names
midiout Transmit raw MIDI data
midiparse Interpret raw MIDI data
Max MIDI Tutorial 3: MIDI Parsing Max MIDI Tutorial 3: MIDI Parsing
midiin
Output raw MIDI data

Description
Listens to a specified MIDI port and output the raw MIDI data received.

Arguments
Name Units Type Opt Description
port symbol opt Specifies the port (a-z) from which to receive incoming MIDI messages. If there is
no argument, midiin receives from port a (or the first input port listed in the
MIDI Setup dialog.)

Messages
anything port [list] Performs the same functions as port.
(mouse) Double-clicking on a midiin object shows a pop-up menu for choosing a MIDI port
or device.
(MIDI) The midiin object receives all MIDI messages from a MIDI input device.
port port [symbol] The word port, followed by a letter a- z or the name of a MIDI input port or
device, sets the port from which the object receives incoming MIDI messages. The
word port is optional and may be omitted.

Information for box attributes common to all objects

Output
int: All MIDI messages received from the specified port are sent out the outlet, byte-by-byte. Note that midiin does not "clean
up" any use of running status in the incoming MIDI stream.

Examples

MIDI messages received in a port are output by a midiin object

See Also
Name Description
midiout Transmit raw MIDI data
midiparse Interpret raw MIDI data
midiinfo Fill a pop-up menu with MIDI device names
notein Receive MIDI note messages
rtin Receive MIDI real time messages
sysexin Receive MIDI system exclusive messages
xnotein Interpret MIDI note messages with release velocity
xbendin Interpret extra precision MIDI pitch bend values
Max MIDI Tutorial 1: Basic MIDI Max MIDI Tutorial 1: Basic MIDI
midiinfo
Fill a pop-up menu with MIDI device names

Description
Outputs a series of messages which will set up a pop-up menu to a list of MIDI output devices when a bang is received. A number
in midiinfo 's right inlet creates a list of MIDI input devices.

Arguments
None.

Messages
bang In left inlet: Same as int, but doesn't send a set message after setting the umenu
items. The equivalent message to bang for retrieving input device names is -1 in
the right inlet.
int index [int] In left inlet: Causes midiinfo to send out a series of messages containing the
names of the current MIDI output devices. Those messages can be used to set the
individual items of a pop-up umenu object connected to the midiinfo object's
outlet. The number received in the midiinfo object's left inlet is then sent in a set
message to set the currently displayed umenu item. In right inlet: Causes
midiinfo to send out a series of messages containing the names of the current
MIDI input devices. Those messages can be used to set the individual items of a
pop-up umenu object connected to the midiinfo object's outlet. The number
received in the midiinfo object's right inlet is then sent in a set message to set the
currently displayed umenu item, unless the number is less than zero, in which
case no set message is sent.
controllers index [int] In left inlet: Causes midiinfo to send out a series of messages containing the
names of all MIDI controllers (devices that transmit MIDI) in the current MIDI
setup. Those messages can be used to set the individual items of a pop-up umenu
object connected to the midiinfo object's outlet. The word controllers may be
followed by a number, which sets the pop-up umenu to that item number after
the menu items have been created.

Information for box attributes common to all objects

Output
append: Immediately after sending the clear message, midiinfo sends an append message for each MIDI input or output device
name, to set the items of a connected umenu object. The device names will be sent out in the order in which they appear in Max's
MIDI Setup dialog.
clear: midiinfo first sends a clear message out its outlet to clear all the receiving umenu object's items.
set: If the incoming message to midiinfo is an integer greater than or equal to zero, a set message is sent after the append
messages, to set the currently displayed menu item.

Examples

Get output device names for MIDI output objects... and for MIDI input objects
See Also
Name Description
midiin Output raw MIDI data
midiout Transmit raw MIDI data
umenu Create and fill a pop-up menu
Max MIDI Tutorial 1: Basic MIDI Max MIDI Tutorial 1: Basic MIDI
midiout
Transmit raw MIDI data

Description
Transmits raw MIDI data to a specified port.

Arguments
Name Units Type Opt Description
port symbol opt Specifies the port (a-z) for transmitting MIDI data. If there is no argument,
midiout transmits out port a (or the first output port listed in the MIDI Setup
dialog.)
device symbol opt The name of a MIDI output device may be used as the first argument to specify the
port.

Messages
int byte [int] The number is transmitted as a byte of a MIDI message to the specified port.
float message [float] Converted to int.
list bytes [list] The numbers are transmitted sequentially as individual bytes of a MIDI message
to the specified port.
anything port [list] Performs the same function as port.
(mouse) Double-clicking on a midiout object shows a pop-up menu for choosing a MIDI
port or device.
port port [symbol] The word port, followed by a letter a-z or the name of a MIDI output port or
device, specifies the port used to transmit the MIDI messages. The word port is
optional and may be omitted.

Information for box attributes common to all objects

Output
(MIDI): There are no outlets. The output is a byte of a MIDI message transmitted directly to the object's MIDI output port.

Examples

MIDI bytes received in the inlet are transmitted out the specified port

See Also
Name Description
midiformat Prepare data in the form of a MIDI message
midiin Output raw MIDI data
midiinfo Fill a pop-up menu with MIDI device names
noteout Transmit MIDI note messages
sxformat Prepare MIDI system exclusive messages
xbendout Format extra precision MIDI pitch bend messages
xnoteout Format MIDI note messages with release velocity
Max MIDI Tutorial 1: Basic MIDI Max MIDI Tutorial 1: Basic MIDI
midiparse
Interpret raw MIDI data

Description
Separates raw MIDI bytes into standard message types. This object works particularly well formatting the output of the midiin
and seq objects.

Arguments
None.

Messages
bang Clears the midiparse object's memory of any partial MIDI message received up to
that point.
int byte [int] Numbers received in the inlet are treated as bytes of a MIDI message (usually
from a seq or midiin object). The status byte determines the outlet which will be
used to output the data bytes.
float byte [float] Converted to int.

Information for box attributes common to all objects

Output
int: Out 4th outlet: The number is a program change.

Out 5th outlet: The number is an aftertouch (channel pressure) value.

Out 6th outlet: The number is a pitch bend value.

Out rightmost outlet: The number is the MIDI channel number.


list: Out leftmost outlet: A note-on message. The first number is a pitch value and the second number is a velocity value.

Out 2nd outlet: A polyphonic key pressure message. The first number is an aftertouch (pressure) value and the second number is
a pitch value (key number).

Out 3rd outlet: A control message. The first number is a control value and the second number is a controller number.

Examples

Interpret the meaning of MIDI messages and filter different types of data

See Also
Name Description
borax Report note-on and note-off information
midiformat Prepare data in the form of a MIDI message
midiselect Select and interpret raw MIDI data
midiin Output raw MIDI data
midiinfo Fill a pop-up menu with MIDI device names
Max MIDI Tutorial 3: MIDI Parsing Max MIDI Tutorial 3: MIDI Parsing
minimum
Output the smallest value

Description
Watches an input stream for any number which is smaller than its most recently set minimum, sets that new number as the
minimum, and outputs it.

Arguments
Name Units Type Opt Description
initial int or float opt Sets an initial value to be compared with numbers received in the left inlet. If the
argument contains a decimal point, all numbers are compared as floats, and the
output is a float. If there is no argument, the initial value is 0.

Messages
bang In left inlet: Sends the most recent output out the outlet again.
int input [int] In left inlet: If the number is less than the value currently stored in minimum, it
is sent out the outlet. Otherwise, the stored value is sent out.
(inlet1) value [int] In right inlet: The number is stored for comparison with subsequent numbers
received in the left inlet.
float input [float] In left inlet: Converted to int, unless there is a float argument, in which case all
numbers are compared as floats.
(inlet1) comparison-value [float] In right inlet: Converted to int, unless there is a float argument, in which case all
numbers are compared as floats.
list input [list] In left inlet: The numbers in the list are all compared to each other, and the
smallest value is sent out the outlet. The value stored in minimum is replaced by
the next smallest value in the list. The minimum object accepts lists of up to 256
elements.

Information for box attributes common to all objects

Output
float: Floats are output only if there is an argument with a decimal point.
int: The number received in the left inlet is compared with the value currently held by minimum (or numbers received as a list
are compared with each other), and the smallest of the numbers is sent out the outlet.

Examples

The output is the lesser of two numbers, or the smallest in a list of numbers

See Also
Name Description
maximum Output the highest value
trough Output a number if it is less than previous numbers
< Compare numbers for less than condition
-
Subtract two numbers, output the result

Description
Arguments
Name Units Type Opt Description
initial number opt Sets the initial value to be subtracted from a number received in the left inlet. A
float argument causes the numbers to be subtracted as floats.

Messages
bang In left inlet: Performs the subtraction with the numbers currently stored. If there
is no argument, - initially holds 0.
int input [int] The number in the right inlet is subtracted from the number, and the result is sent
out the outlet.
(inlet1) value [int] The number is stored, to be subtracted from, by a number received in the left inlet.
float input [float] Converted to int, unless - has a float argument.
set input [int] Sets the number to be subtracted without causing output (bang will output it).
list input [list] In left inlet: The first number is subtracted from the second number, and the
result is sent out the outlet.

Information for box attributes common to all objects

Output
float: Only if there is an argument with a decimal point.
int: The difference between the two numbers received in the inlets.

Examples

Subtracted as ints... Floats are truncated before subtraction... unless there is a float argument

See Also
Name Description
!- Subtraction object (inlets reversed)
expr Evaluate a mathematical expression
Max Basic Tutorial 6: Simple Max Basic Tutorial 6: Simple Math in Max
Math in Max
modifiers
Report modifier key presses

Description
Polls and reports the state of the keyboard's modifier keys.

Arguments
Name Units Type Opt Description
rate ms int opt Specifies a polling rate in milliseconds. The default value is 0 (no polling).

Messages
bang Sends out a report of the current modifier key states.
(keyboard) The keyboard input to modifiers comes directly from the computer keyboard.
interval rate [int] The word interval followed by a number, specifies the rate, in milliseconds, used
when polling the state of the modifier keys. A value of zero disables polling.

Information for box attributes common to all objects

Output
int: Output is sent whenever a modifier key is pressed down on the computer keyboard. Modifier key states are reported as 0
(not pressed) or 1 (pressed).

Out left outlet: The on/off state of the Shift key.

Out second outlet: The on/off state of the Caps Lock key.

Out third outlet: the on/off state of the Option key on Macintosh or the Alt key on Windows.

Out fourth outlet: the on/off state of the Control key.

Out fifth outlet: the on/off state of the Command key on Macintosh or the Control key on Windows.

Note: The fourth and fifth outlets both report the on/off state of the Control key on Windows, since the Command key on
Macintosh is equivalent to the Control key on Windows. For cross-platform uses, Windows users should use the fifth outlet of the
modifiers object for reporting the Control key state. The fourth outlet also reports the Control key on Windows so that (older)
Macintosh patches that use this key can be opened on Windows systems. The Macintosh Control key normally corresponds to the
right-hand mouse button on Windows. See the section on file and key mappings in the Max Tutorials for a complete discussion of
cross-platform keyboard issues.

Examples

Modifier keys typed on the computer keyboard can be used to trigger messages
See Also
Name Description
key Report keyboard presses
keyup Report key information on release
Report modifier key presses
numkey Interpret numbers typed on the keyboard
Max Basic Tutorial 8: Keyboard Max Basic Tutorial 8: Keyboard and Mouse Input
and Mouse Input
%
Divide two numbers, output the remainder

Description
% takes two numbers, divides one by the other and outputs the remainder of the division.

Arguments
Name Units Type Opt Description
initial-value int opt Sets an initial value for the divisor. If there is no argument, the divisor is set to 1
initially.

Messages
bang In left inlet: Performs the operation with the numbers currently stored.
int input [int] In left inlet: The number is divided by the number in the right inlet, and the
remainder is sent out the outlet.
(inlet1) divisor [int] In right inlet: The number is stored as the divisor (the number to be divided into
the number in the left inlet) for calculating the remainder.
float input [float] Converted to int.
set set-input [int] Sets the number to be divided without causing output (bang will output it).
list number-divided and divisor In left inlet: The first number is divided by the second number, and the remainder
[list] is sent out the outlet.

Information for box attributes common to all objects

Output
int: When the two numbers in the inlets are divided, the remainder is sent out the outlet. % is called the modulo operator.

Examples

Find the remainder of a division

See Also
Name Description
expr Evaluate a mathematical expression
!/ Divide input from a number
/ Divide two numbers
Max Basic Tutorial 6: Simple Max Basic Tutorial 6: Simple Math in Max
Math in Max
mousefilter
Gate messages with the mouse

Description
Allows messages to pass only when the mouse button is up (un-clicked).

Arguments
None.

Messages
bang If the mouse button is up, the bang is sent out the outlet. Otherwise, the bang is
ignored.
int input [int] If the mouse button is up, the number is sent out the outlet. Otherwise, the
number is ignored.
float input [float] If the mouse button is up, the number is sent out the outlet. Otherwise, the
number is ignored.
list input [list] If the mouse button is up, the list is sent out the outlet. Otherwise, the list is
ignored.
anything input [list] Performs the same as list.

Information for box attributes common to all objects

Output
int: The number received in the inlet is sent out only if the mouse button is up.

Examples

Nothing gets through unless the mouse is up

See Also
Name Description
mousestate Report the mouse information
Max Basic Tutorial 8: Keyboard Max Basic Tutorial 8: Keyboard and Mouse Input
and Mouse Input
mousestate
Report the mouse information

Description
Provides button status and cursor position information about the mouse/cursor when the cursor is positioned within a Max
patcher window. The mouse button is sampled every 50ms, while the mouse position is sampled every input bang.

Arguments
None.

Messages
bang Sends out the current horizontal and vertical coordinates of the location of the
mouse, as well as the change in location since the last output.
nopoll Undoes a poll message, reverting mousestate to its normal condition of waiting
for a bang before reporting.
mode input [int] The word mode, followed by a long value specifices the type of reference to use for
the mouse coordinates from the second and third outlets. A value of 0 specifies to
use screen-relative coordinates where 0,0 is the top left corner of the primary
display. A value of 1 specifies patcher-relative coordinates where 0,0 is the top left
corner of the content area of the mousestate object's patcher. A value of 2
specifies front-most patcher relative coordinates where 0,0 is the top left corner of
the content area of the top patcher window.
poll Causes mousestate to send out the mouse location, and the change in mouse
location, whenever the mouse is moved, as well as when a bang is received.
reset Resets the 0,0 point to its default setting, in the upper left corner of the screen.
zero Resets the point mousestate considers as the 0,0 point from which to measure
the mouse location. The current location of the mouse is considered the new 0,0
point.

Information for box attributes common to all objects

Output
int: mousestate must have received at least one bang or poll message in its inlet before any output is sent out.

Out left outlet: Each time the mouse button is pressed, 1 is sent out. Each time the mouse button is released, 0 is sent out.

Out 2nd outlet: The horizontal location of the mouse, measured in terms of the number of pixels the mouse is to the right of the
0 point.

Out 3rd outlet: The vertical location of the mouse, measured in terms of the number of pixels the mouse is below the 0 point.

Out 4th outlet: The change in horizontal location of the mouse, since the last time the mouse location was reported.

Out right outlet: The change in vertical location of the mouse, since the last time the mouse location was reported.

Examples
The mouse can provide continuous or discrete values

See Also
Name Description
modifiers Report modifier key presses
mousefilter Gate messages with the mouse
Max Basic Tutorial 8: Keyboard Max Basic Tutorial 8: Keyboard and Mouse Input
and Mouse Input
movie
Play a QuickTime movie in a window

Description
Plays a movie in a separate window. All movie playback control is managed by messages to the object.

Arguments
Name Units Type Opt Description
filename symbol opt Specifies the name of a QuickTime movie file to be read into movie automatically
when the patch is loaded. The same effect can be achieved for imovie by selecting
the object in an unlocked patcher and choosing Get Info... from the Object menu
to select a movie file. Both objects retain the name(s) of the movie(s) they have
loaded at the time that the patch is saved, and attempt to load the same movie(s)
the next time the patch is opened.

Messages
bang Same as resume.
int location [int] Sets the current time location of the movie. If the movie is playing, it will play
from the newly set location. 0 is always the beginning. The end time varies from
one movie to another. (The length message reports the end time location out the
left outlet.)
(drag) When a QuickTIme movie file is dragged from the Max 5 File Browser to a movie
object, the file will be loaded.
active flag [int] The word active, followed by a non-zero number, makes the movie active (the
default). Followed by a 0, active makes the movie inactive. An inactive movie will
not play or change location.
(mouse) Double-clicking on the movie object will make the movie window active.
dispose filename [symbol] Closes the movie window if it is open, and removes all movies from the movie
object's memory. If the word dispose is followed by the name of a loaded movie,
only the named movie will be removed.
clear Has the same effect as dispose with no arguments.
duration Reports the duration of the movie (in time units) out the left-most outlet.
getduration Reports the end time position of the movie (in QuickTime Time Units) from the
left outlet.
getrate Reports the current rate multiplied by 65536 out the right outlet. Thus, normal
speed is reported as 65536, half speed is reported as 32768, double speed
backward is reported as -131072, etc. If the movie is not playing, the rate is
reported as 0, and if no movie has yet been loaded nothing is sent out.
gettime Reports the current time location of the movie.
ff The word ff fast-forwards the movie.
length The length message's functionality is equivalent to the getduration message.
loadintoram flag [int] The word loadintoram, followed by a non-zero number, attempts to load the
entire movie into memory, if possible. The default is 0.
next time-units [int] The word next, followed by a number, moves the time location ahead by that
amount. If no number is supplied, next moves the time ahead by 5. (The actual
time meaning of these units varies from movie to movie.)
nextmovie Stops the movie if it is playing, and switches to the movie that was loaded just
prior to the current movie. (The movies are stored in reverse order from the order
in which they were loaded.) If there is no prior movie, nextmovie wraps around
back to the most recently loaded movie. Note that the title of the movie window is
not automatically changed, even though the "current movie" has been changed by
nextmovie.
matrix matrix [list] The word matrix, followed by nine floating point numbers, reloads the current
movie into RAM after performing a transformation matrix operation on the image.
This transformation is the same one used for the mapping in QuickTime of points
from one coordinate space (i.e, the original image) into another coordinate space
(a scaled, rotated, or translated version of the original image).

The transform matrix operation consists of nine matrix elements


mute flag [int] The word mute, followed by a non-zero number, turns off the movie's sound (if it
has any). Followed by a 0, mute turns on the movie's sound (the default).
loop flag [int] The word loop, followed by a number in the range 0-2, controls looping for the
current film on. The options are:
0: looping off (default) 1: looping on 2: palindrome mode (forward and then
backward)
loopend end [int] The word loopend, followed by a number, sets the end point of a loop. The
default value is corresponds to the end of the film.
looppoints beginning [int] The word looppoints, followed by two numbers, sets the beginning and end
end [int] points of a loop. the default values are 0 (i.e., the start of the film) for the start
point and the end of the film for the endpoint.
loopset beginning [int] The loopset message's functionality is equivalent to the looppoints message.
end [int]
loopstart beginning [int] The word loopstart, followed by a number, sets the beginning point of a loop. The
default value is 0 (i.e., the start of the film).
pause Stops the movie.
pos index [float] The word pos followed by a floating-point number which denotes a position-index
within the movie will cause the playback-position to jump to the specified position
in the movie.
prev time-units [int] The word prev, followed by a number, moves the time location backward by that
amount. If no number is supplied, prev moves the time backward by 5.
open Brings the movie window to the foreground (applies only to movie, not imovie).
palindrome flag [int] The word palindrome, followed by a non-zero number, sets the movie to play in
palindrome mode (forward and then backward). Looping must be turned on.
palindrome 0 (the default) disables palindrome mode.
rate input [list] The word rate, followed by one or more integers or floats, sets the playing speed
of the movie. If rate is followed by one integer, that number is taken to be a whole
number playing speed. If rate is followed by two numbers, the first number is
taken to be the numerator and the second the denominator of a fractional speed. 1
is the normal playing speed, 0 means the movie is stopped, and a negative rate
plays backwards. rate 1 2 would play the movie at half speed. Immediately after
you send a non-zero rate message, the movie will begin playing, so you may wish
to precede any rate messages with an integer to locate to the desired starting
position.
read filename [symbol] The word read, followed by a symbol, looks for a QuickTime movie file with that
name in Max's file search path, and opens it if it exists, displaying the movie's first
frame in a movie window. If the filename contains any spaces or special
characters, the name should be enclosed in double quotes or each special character
should be preceded by a backslash (\). The word read by itself puts up a standard
Open Document dialog box and reads in any movie file you select. The read
message will open at least 26 different types of files that can be opened by
QuickTime, these include movie files such as MPEG, audio files including AIFF
and MP3, and graphics files including GIF and JPEG.
readany filename [symbol] The readany message opens any type of file, using QuickTime routines to try to
interpret it as a movie or other supported media file.
quality interval [int] The word quality, followed by a number, sets the minimum interval, in
milliseconds, between movie redraws. The default is 0 (i.e., no minimum).
passive mode [int] The word passive, followed by a non-zero number, sets the passive mode. In
passive mode, starting a movie will not cause the frame to change unless a bang
message is received. passive0 (the default) sets the movie object to respond to
normal start messages.
start filename [symbol] Sets the movie's rate to 1 and begins playing from the beginning. If the word start
is followed by the name of a specific loaded movie, that movie becomes the current
movie before starting.
startat location [list] The word startat, followed by a number, set the current time location of the
movie and begins playing from that point.
stop Stops the movie.
rd filename [symbol] Same as read.
rect x-position-coordinate The word rect, followed by four numbers, specifies the size of the rectangle in
[int] which the movie is displayed within the movie window. The first two numbers
y-position-coordinate specify the position of the rectangle within the movie window, in relative
[int] coordinates, and the second two numbers specify the width and height, in pixels,
width (pixels) [int] of the rectangle.
height (pixels) [int]
resume Begins playing the movie from its current location, at the most recently specified
rate.
switch filename [symbol] The word switch, followed by a symbol, makes the named movie the active one
without changing the transport state (See the start message).
reload The word reload will reload the current movie into memory (can be used to
refresh; for example, if a movie is playing and the stop message is sent followed
by reload, the movie will reload into memory and be set to play from the
beginning as a newly loaded movie).
rw The word rw rewinds the movie.
time frame [list] The word time, followed by a number that specifies a QuickTime frame number,
goes to the time location specified by the number. When no argument is present,
the time message's functionality is equivalent to the gettime message.
timescale Reports the timescale of the movie out the left-most outlet.
toggleplay The word toggleplay activates or pauses playback of the movie.
vol volume [int] The word vol, followed by a number in the range 1-255, sets the movie's sound
volume. Optionally, the volume can be set by using the word vol, followed by a
floating-point value in the range 0. - 1.0.
wclose Closes the movie window.
windowpos left-coordinate [int] The word windowpos, followed by four numbers, specifies the location and size of
top-coordinate [int] the movie window on the screen. The four numbers specify the left, top, right, and
right-coordinate [int] bottom of the movie window in global coordinates. This message is only supported
bottom-coordinate [int] by the movie object, not the imovie object.

Attributes
Name Type g/s Description
autofit int Toggles scaling the movie to fit in the window currently displayed.
def.:0
border int Toggles the movies border type. The message border 1 (the default) uses the
def.:1 traditional Macintosh-style border for the movie window. The message border 0
displays only the rectangle in which the movie plays.
'Plain' = TEXT_HERE
'Document' = TEXT_HERE
name symbol Name of the movie file loaded.

Information for box attributes common to all objects


Output
int: Out left outlet: The current time location, when a time message is received; the end time location when a length message is
received.

Out middle outlet: The horizontal position of the mouse, relative to the left side of the movie box or window, when the mouse is
clicked or dragged inside the movie.

Out right outlet: The vertical position of the mouse, relative to the top of the movie box or window, when the mouse is clicked or
dragged inside the movie.

Also, in response to a getrate message, the current movie rate multiplied by 65536 is sent out the right outlet.

Examples

Play a QuickTime movie, or move through it in a variety of ways... Hold multiple movies (which are stored in reverse order
from the order received)

See Also
Name Description
imovie Play a movie in a patcher window
mtof
Convert a MIDI note number to frequency

Description
Performs MIDI-note-number to frequency conversion. Frequency is reported in as a float in Hertz (Hz).

Arguments
None.

Messages
int MIDI-note-number [int] A MIDI note number value from 0 to 127. The corresponding frequency is output.
The output value is dependent on the base frequency attribute.
float MIDI-note-number [float] A MIDI note number value from 0 to 127. The corresponding frequency is sent out
the outlet. The output value is dependent on the base frequency attribute.
list MIDI note list [list] Generates a list of frequency values corresponding to the MIDI note values of
incoming list elements.

Attributes
Name Type g/s Description
base float Sets the "base frequency" used when calculating frequency values (e.g., A = 440.).
The default base frequency is 440 Hz.

Information for box attributes common to all objects

Output
float: The frequency corresponding to the received MIDI pitch value.

Examples

Use MIDI note number to provide frequency value for an oscillator

See Also
Name Description
expr Evaluate a mathematical expression
ftom Convert frequency to a MIDI note number
mtr
Record and sequence messages

Description
Records messages and provides sequenced playback.

Arguments
Name Units Type Opt Description
tracks int opt Specifies the number of tracks in the mtr. The number of tracks determines the
number of inlets and outlets in addition to the leftmost inlet and outlet. Up to 32
tracks are possible. If there is no argument, there will be only one track.

Messages
int input [int] In any inlet other than the left inlet: If the track is currently being recorded,
numbers received in that track's inlet are combined with a delta time (the number
of milliseconds elapsed since the previous event) and stored in mtr.
float input [float] In any inlet other than the left inlet: If the track is currently being recorded,
numbers received in that track's inlet are combined with a delta time (the number
of milliseconds elapsed since the previous event) and stored in mtr.
list input [list] In any inlet other than the left inlet: If the track is currently being recorded, lists
received in that track's inlet are stored in mtr, preceded by the delta time.
anything input [list] In any inlet other than the left inlet: If the track is currently being recorded,
symbols received in that track's inlet are stored in mtr, preceded by the delta time.

Although mtr can record individual bytes of MIDI messages received from midiin,
it stores each byte with a separate delta time, and does not format the MIDI
messages the way seq does. If you want to record complete MIDI messages and
edit them later, seq is better suited for the task. On the other hand, mtr is
perfectly suited for recording sequences of numbers, lists, or symbols from
virtually any object in Max: specialized MIDI objects such as notein or pgmin,
user interface objects such as number box, slider, and dial, or any other object.

In order for a file to be read into mtr for playback, it must be in the proper format.
An mtr multi-track sequence can even be typed in a text file, provided it adheres
to the format. The contents of the different tracks are listed in order in an mtr file,
and the format of each track is as follows. Note that a semicolon (;) ends each line.

Line 1: track <track number>; (Track in which to store subsequent data)


Line 2, etc.: <delta time> <message>;
Last line: end; (End of this track's data)
clear tracks [list] In left inlet: Erases the contents of mtr. The word clear, followed by one or more
track numbers, clears those tracks.

In other inlets: Erases the track that corresponds to the inlet.


delay delay-time [int] In left inlet: The word delay, followed by a number of milliseconds, sets the first
delta time value of each track to that number, so that all tracks begin playing back
that amount of time after the play message is received.

In other inlets: Sets the initial delta time of the track that corresponds to the inlet.
first wait-time [int] In left inlet: The word first, followed by a number of milliseconds, causes mtr to
wait that amount of time after a play message is received before playing back.
Unlike delay, first does not alter the delta time value of the first event in a track,
it just waits a certain time (in addition to the first delta time) before playing back
from the beginning.
next tracks [list] In left inlet: Causes each track to output only the next message in its recorded
sequence. When a next message is received, the track number and the delta time
of each message being output are sent out the leftmost outlet as a list. The word
next, followed by one or more track numbers, outputs the next message stored in
those tracks.

In other inlets: Outputs the next message stored on the track that corresponds to
the inlet.
mute tracks [list] In left inlet: Causes mtr to stop producing output, while still continuing to "play"
(still moving forward in the sequence). The word mute, followed by one or more
tracks, mutes those tracks.

In other inlets: Mutes the track that corresponds to the inlet.


play tracks [list] In left inlet: Plays back all messages recorded earlier, sending them out the
corresponding outlets in the same rhythm and at the same speed they were
recorded. The word play, followed by one or more track numbers, begins playing
those tracks.

In other inlets: Plays back all messages on the track that corresponds to the inlet.
read filename [symbol] In left inlet: Calls up the standard Open Document dialog box, so that a previously
saved file can be read into mtr.

In other inlets: Opens a file containing only the track that corresponds to the inlet.
record tracks [list] In left inlet: Begins recording all messages received in the other inlets. The word
record, followed by one or more track numbers, begins recording those tracks.
In other inlets: Begins recording messages on the track that corresponds to the
inlet.
rewind tracks [list] In left inlet: Resets mtr to the beginning of its recorded sequence. This command
is used to return to the beginning of the sequence when stepping through
messages with next. To return to the beginning of a sequence while playing or
recording, just repeat the play or record message. When mtr is playing or
recording, a stop message should precede a rewind message. The word rewind,
followed by one or more track numbers, returns to the beginning of those tracks.

In other inlets: Returns the pointer to the beginning of the track that corresponds
to the inlet.
stop tracks [list] In left inlet: Stops mtr when it is recording or playing. The word stop, followed by
one or more track numbers, stops those tracks.

In other inlets: Stops the track that corresponds to the inlet.


unmute tracks [list] In left inlet: Undoes any previously received mute messages. The word unmute,
followed by one or more track numbers, unmutes those tracks.

In other inlets: Unmutes the track that corresponds to the inlet.


write filename [symbol] In left inlet: Calls up the standard Save As dialog box, allowing the contents of mtr
to be saved as a separate file. Note that the only way to save the contents of mtr is
with the write message; the object's contents cannot be embedded in a patcher
file.

In other inlets: Writes a file containing only the track that corresponds to the inlet.

Information for box attributes common to all objects

Output
anything: Out all track outlets: When a play message is received in the leftmost inlet, the messages stored in each track are sent
out the outlet of that track, in the same rhythm and at the same speed they were recorded. A play message received in the inlet of
an individual track plays that particular track.

When a next message is received in the leftmost inlet, the next message in each track is sent out its corresponding outlet. The
word next, received in the inlet of an individual track, sends out the next message in that track.
list: Out left outlet: Whenever a value is sent out in response to a next message, the track number and delta time of that value
are sent out the left outlet as a two-item list.

Examples

Record MIDI data or other events

See Also
Name Description
multislider Display data as sliders or a scrolling display
seq Sequencer for recording and playing MIDI data
rslider Display or change a range of numbers
slider Move a slider to output values
multislider
Display data as sliders or a scrolling display

Description
Displays data as either an array of sliders or a scrolling display. When configured as sliders, the values are set (and output) as
numeric lists. When configured as a scrolling display, multislider receives numbers, plots them, and scrolls the display area.

Arguments
None.

Messages
bang Outputs the current slider values as a list.
int input [int] Sets all slider values and positions to the number received and outputs a list
reflecting the current values. If the multislider data type is set to float, the values
in the incoming list are converted to floats.
float input [float] Sets all slider values and positions to the number received and outputs a list
reflecting the current values. If the multislider data type is set to int, the values in
the incoming list are truncated and converted to ints.
list input [list] Sets each slider to a corresponding value in the list from left to right, with the first
value in the list setting the first slider. If the multislider has a different number of
sliders than is present in the list, the number of sliders is changed to the number
of items in the list. In such a case, the outside dimensions of the multislider will
not change, only the width or height of the sliders.
anything list [list] anything is used to offer backwards compatibility in conjunction with the
compatibility message.
drawbars flag [int] The word drawbars followed by a non-zero number will set the multislider to
draw bars when displaying slider values. When followed by a 0, the sliders' values
will not be drawn in bars.
drawlines flag [int] The word drawlines followed by a non-zero number will set the multislider to
draw lines when displaying slider values. When followed by a 0, the sliders' values
will not be drawn in lines.
echo flag [int] Toggles echo mode on and off. When echo mode is on, the multislider object will
output any list received in its inlet. The default is off (0).
fetch slider [int] The word fetch, followed by a number, sends the value of the numbered slider out
the right (single slider value) outlet.
interp mode [int] Sending the word interp, followed by a one or zero, enables or disables
interpolation mode. When interpolation mode is on (the default), the multislider
object will output interpolated values when a slider is moved. In most cases you
probably will not want to disable interpolation mode.
max Sets all sliders to their maximum values.
maximum The word maximum causes the value of the slider with the largest value to be sent
out the right outlet.
min Sets all sliders to their minimum values.
minimum The word minimum causes the value of the slider with the smallest value to be
sent out the right outlet.
(mouse) The way that a multislider responds to the mouse is determined by its chosen
display style. A multislider will respond to mouse clicks when its display style is
non-scrolling (Thin Line or Bar). Clicking on a forward or reverse scrolling display
multislider (Point Scroll or Line Scroll) has no effect.
If continuous output mode is enabled, the list of the current values will be sent out
each time the mouse moves while dragging. If the continuous output mode is off,
this list is only sent out when the mouse button is pressed or released. The
continuous output option can be set in the multislider object's Inspector.
When the display style is non-scrolling, clicking on any slider in a multislider
immediately positions the slider at the click point. The current value of all sliders
is sent out. Dragging across a multislider will set the other sliders in the same
manner. If continuous output mode is enabled, the list of the current values will
be sent out each time the mouse moves while dragging. If the continuous output
mode is off, this list is only sent out when the mouse button is pressed or released.
The continuous output option can be set in the multislider object's Inspector.
If the mouse is moved quickly across a range of sliders, the mouse's position is
likely not to be polled quickly enough by the computer to provide a value for each
and every slider it appears to pass. By default, multislider will automatically
interpolate slider values between successively polled mouse positions. You can use
the interp message to disable interpolation, if desired.
normalize number [float] The word normalize, followed by a float, will scale the sample values in the
multislider so that the highest number matches the value given by the argument.
Every value is scaled, and this activity cannot be undone. Although the normalize
message calculates a normalized list based on the value passed as its argument,
the message does not update the values in the multislider object itself or display
them.
peakreset Reset peak values to current slider values
select value-pairs [list] Selectively sets slider values. For example, select 1 30 2 4 5 50 sets the first
slider to 30, the second to 4, and the fifth slider to 50 (the top or leftmost slider is
always number 1).
set slider [number] The word set, followed by a slider number and a value, sets the numbered slider
value [number] to that value without triggering any output.
setborder left [int] The setborder is similar in function to the border message, but it uses a list of
right [int] integer values of zero or one to enable (1) or disable (0) the display of the
top [int] multislider object's borders. All borders are drawn by default (equivalent to the
bottom [int] message setborder 1 1 1 1).
setlist values [list] The word setlist, followed by a list of slider values, sets the sliders to the listed
values without triggering any output.
range minimum [number] The word range followed by a minimum number and a maximum number will set
maximum [number] all sliders to operate within that range.
quantiles numbers [list] In left inlet: The word quantiles, followed by a list of floats between 0 and 1.0,
multiplies each list element by the sum of all the values in the multislider. This
result is then divided by 215 (32,768). Then, multislider sends out the address at
which the sum of all values up to that address is greater than or equal to the result
for each list element.
setmax value [float] The word setmax, followed by a number, sets the high values for the multislider
object.
setmin value [float] The word setmin, followed by a number, sets the low values for the multislider
object.
sum Outputs a sum of all current slider values as a float.

Attributes
Name Type g/s Description
bgcolor float Specifies the background color of the multislider in RGBA format. object.
border_bottom int Toggles drawing a bottom border for the multislider object. This is useful for
def.:1 placing multislider objects next to each other.
border_left int Toggles drawing a left border for the multislider object. This is useful for placing
def.:1 multislider objects next to each other.
border_right int Toggles drawing a right border for the multislider object. This is useful for placing
def.:1 multislider objects next to each other.
border_top int Toggles drawing a top border for the multislider object. This is useful for placing
def.:1 multislider objects next to each other.
bordercolor float Specifies the object's rectangular one-pixel border in RGBA format. The default
value is black (rgb3 0 0 0). The color can also be set using the Inspector.
candicane2 float Specifies the 2nd slider color in candycane mode in RGBA format.
candicane3 float Specifies the 3rd slider color in candycane mode in RGBA format.
candicane4 float Specifies the 4th slider color in candycane mode in RGBA format.
candicane5 float Specifies the 5th slider color in candycane mode in RGBA format.
candicane6 float Specifies the 6th slider color in candycane mode in RGBA format.
candicane7 float Specifies the 7th slider color in candycane mode in RGBA format.
candicane8 float Specifies the 8th slider color in candycane mode in RGBA format.
candycane int Enables the multislider object to use multiple colors for adjacent sliders, with the
def.:1 color pattern repeating (like the stripes in a candycane) every N sliders (indicated
by the integer argument). The first eight colors can be set with the frgba and
rgba4- rgba10 messages, the next fifteen colors are taken from the Max
application's color palette. The number of stripes in the candycane can also be set
using the Inspector.
compatibility int Toggles the backwards-compatibility mode for the maximum, minimum and
def.:0 sum messages. If this mode is enabled, the multislider object will output the
single-value results of these messages out the left outlet, otherwise the values will
be output out the right (single slider value) outlet, just like the fetch message.
Patches saved before Max 4.6 will automatically open with compatibility mode
enabled.
contdata int Toggles continuous output mode for non-scrolling display styles. If this mode is
def.:0 enabled, the multislider object will output a list of its current slider values each
time the mouse is clicked and dragged. If this mode is turned off, the multislider
object will only output a list when the mouse button is pressed and when it is
released. The continuous output mode can also be set using the Inspector.
drawpeaks int Toggles setting the multislider to draw peak-output lines when displaying slider
def.:0 values. When followed by a 0, the sliders will not show any peaks.
ghostbar int When followed by a percentage value from 1 to 100, enables the drawing of a
def.:0 "ghost" bar when mode the multislider object is in Thin Line mode. A percentage
value of 1 will draw a very light bar behind the Thin Line line, a value of 50 will
draw a half-dark bar, and a value of 100 will draw a bar the same color as the Thin
Line slider. When the word ghostbar is followed by a zero, this drawing mode is
disabled (which it is by default).
orientation int The word orientation followed by a non-zero number will set the sliders to be
def.:1 drawn with a vertical orientation. When followed by a 0, multislider will be set to
draw with a horizontal orientation.
'Horizontal' = TEXT_HERE
'Vertical' = TEXT_HERE
parameter_enable int Parameter Mode Enable
peakcolor float Specifies the peak indicators when Peak-Hold display is turned on (see peakhold
and peakreset messages). The default value is grey (rgb2 127 127 127).
setminmax float Sets the low and high range values for the multislider object. The default values
def.:-1. 1. are -1.0 and 1.0 for floating point sliders and 0 and 127 for integer sliders.
setstyle int Sets the display style of the multislider object. The default value is Thin Line
def.:0 (setstyle 0).
'Thin Line' = TEXT_HERE
'Bar' = Display slider values as bars
'Point Scroll' = TEXT_HERE
'Line Scroll' = TEXT_HERE
'Reverse Point Scroll' = TEXT_HERE
'Reverse Line Scroll' = TEXT_HERE
settype int Sets the multislider object for integer (0) or floating point (1) operation. The
def.:1 Inspector can also be used to set the multislider object's type. The default is
integer (settype 0).
'Integer' = Use integer values for operation
'Floating-point' = Use integer values for operation
signed int Sets the signed or unsigned display mode for bar sliders. The default is 0 (off), and
def.:0 bar sliders are drawn from the minimum value. When this mode is set to 1 (on)
sliders are drawn from zero to either a positive or negative slider value.
size int Sets the number of sliders the multislider object has. The default is 1, and the
def.:1 maximum number of sliders is 4096.
slidercolor float Specifies the slider color of the multislider object. The default value is black (frgb
0 0 0).
spacing int Sets the amount of space (in pixels) between sliders. The default is 0 (all sliders
def.:0 touching one another).
thickness int Sets the pen thickness of "thin line"style sliders. The default thickness is 2 pixels.
def.:2

Information about attributes available for Parameter-aware objects

Information for box attributes common to all objects

Output
float: Out right outlet: The value of a numbered slider specified by the fetch message. The output reflects the current data type
settings (see the settype message).
int: Out right outlet: The value of a numbered slider specified by the fetch message. The output reflects the current data type
settings (see the settype message).
list: Out left outlet: When a multislider receives a list, int, or float in its inlet, it outputs a list of its current values. The list is also
sent out when the sliders are changed with the mouse.

Examples

multislider drawing styles

See Also
Name Description
itable Graphic display of a table
kslider Output numbers from an onscreen keyboard
matrixctrl Matrix switch control
pictslider Picture-based slider control
rslider Display or change a range of numbers
slider Move a slider to output values
Max Data Tutorial 1: Data Max Data Tutorial 1: Data Viewing
Viewing
mxj
Execute Java in Max

Description
Execute Java classes as Max objects. The Java classes must be specially written for Max, but work identically within the JVM
(Java Virtual Machine) on both Windows and Macintosh.

Arguments
Name Units Type Opt Description
Java-class symbol The mxj object must be given the name of a valid Java class as the first argument.
The Java class file must exist somewhere within the classpath, and it must be a
class that was designed for use with the mxj object (the class must subclass
com.cycling74.max.MaxObject.).
The number of inlets that an instance of mxj creates and the messages that it will
respond to are determined by declarations made in the peer Java class.
attributes list The mxj object supports the definition of attributes within the Java code for a peer
class. The attributes that are settable at the time of instantiation using the @
paradigm. For instance, if a particular class Foo defined an integer attribute called
intBar, one could create an instance of the class with the attribute set to the value
74 by typing mxj Foo @intBar 74 in an object box.

Messages
bang User-defined according to the Java class instantiated.
int input [int] User-defined according to the Java class instantiated.
float input [float] User-defined according to the Java class instantiated.
list input [list] User-defined according to the Java class instantiated.
anything input [list] User-defined according to the Java class instantiated.
(mouse) Double-clicking with the mouse on the mxj object displays its contents as text in
an editing window which the user can modify.
get attribute [list] The word get followed by an attribute-name will post the attribute value in the
Max window.
viewsource The viewsource message brings up a text editor window and loads the source code
for the peer Java object. If the source code is not in the same directory as the peer
class's .java file, a decompilation of the class file is attempted and the resulting
decompiled source is presented. From within the editor window it's possible to
make edits to the source, save the file, and recompile the class.
zap When a zap message is sent to an mxj object with Java peer class Foo, the next
mxj object that's instantiated with the same peer Java class Foo (ie typing "mxj
Foo" in an object box) will cause the class to reload itself from disk. This is most
useful in a programming context: if one makes a change to Foo.java and
recompiles a new Foo.class the zap message allows one to create an instance of
the new class without having to quit and restart the Max environment. Without
sending the zap message Max would simply use the cached definition of the class
that was loaded when a Foo object was instantiated prior to the changes being
made.

Information for box attributes common to all objects

Output
various: The number of outlets that an instance of mxj creates is determined by declarations made in the constructor of the peer
Java class. The furthest outlet to the right may or may not be an info outlet whose sole responsibility is to report information
about the attributes when queried.
Examples

Instantiations of the keep (in-patcher storage) and Multiplex (list multiplexing) classes

See Also
Name Description
js Execute Javascript
Tutorial 51: Jitter Java Tutorial 51: Jitter Java
next
Detect separation of messages

Description
Sends a bang out its left outlet when an incoming message is not part of the same Max "event" as a previous message. (An "event"
is a mouse click, key press, MIDI event, or tick of the scheduler.) Otherwise, next sends a bang out its right outlet.

Arguments
None.

Messages
bang Performs the same as anything.
int input [int] Performs the same as anything.
float input [float] Performs the same as anything.
anything input [list] Messages are tested to determine whether they are part of the same logical event.
A logical event is one of the following: a mouse click, the ongoing polling of a
mouse drag, an event generated by the scheduler (such as the bang from a
metro), a MIDI event, or a keyboard event. next determines whether the current
message is part of the same event as the previously received message. For
example, if you click on a bang twice, the two bangs are not part of the same
logical event. But if you put bang, bang in a message box, or use the uzi object to
send out two bangs in a row, these bangs are part of the same logical event.

Information for box attributes common to all objects

Output
bang: Out left outlet: A bang is sent out if the current message is not part of the same logical event as the previously received
message.

Out right outlet: A bang is sent out if the current message is part of the same logical event as the previously received message.

Examples

next detects when separate Max messages occur within the same logical event

See Also
Name Description
uzi Send many bang messages
defer Defer execution of a message
delay Delay a bang
nodes
Interpolate parameter with a 2D interface.

Description
Displays nodes in a 2-dimensional space, and calculates the distance from a node points.

Arguments
None.

Messages
bang Outputs the nodes values out the second outlet.
list x [number] Sets the position of the slider (if present) and outputs the new coefficients.
y [number]
ad azimuth [float] Sets the position of the slider (if present) in polar coordinates (azimuth in degrees,
distance [float] distance) and outputs the new coefficients.
active index [int] Sets the active state (0 disabled, 1 enabled) of the node(s). Index numbering for
state [int] the nodes starts at 1. When the index is set to 0, it affects every node.
getad The word getad causes the nodes object to send a list of polar coordinates of the
slider out the dumpout outlet.
getactive index [int] The word getactive causes the nodes object to send a list of the active states of
every node out the dumpout outlet. An optional argument allows you to query the
active state of a specific node.
getnode index [int] The word getnode causes the nodes object to send a list of the values of the node
{x, y, size, active} of every node out the dumpout outlet. An optional argument
allows you to query a specific node.
getsize index [int] The word getsize causes the nodes object to send a list of the values of the node
size of every node out the dumpout outlet. An optional argument allows you to
query a specific node.
getxy The word getxy causes the nodes object to send a list of cartesian coordinates of
the slider out the dumpout outlet.
(mouse) You can manipulate the nodes or the slider depending on the displayknob and
mousemode attributes.
setnode index [int] Sets the position of the node(s). Index numbering for the nodes starts at 1. When
x [float] the index is set to 0, it affects every node. You can also provide additional
y [float] arguments to define the size and active state.
size [float]
active [int]
setnodead index [int] Sets the position of the node(s) in azimuth (angle in degree) and distance. Index
azimuth [float] numbering for the nodes starts at 1. When the index is set to 0, it affects every
distance [float] node. You can also provide additional arguments to define the size and active state.
size [float]
active [int]
setsize index [int] Sets the size of the specified node. Index numbering for the nodes starts at 1.
size [float] When the index is set to 0, it affects every node.

Attributes
Name Type g/s Description
bgcolor float Sets the nodes background color in RGBA format.
bordercolor float Sets the nodes border color in RGBA format.
candycane int Sets the nodes object to use multiple colors for the nodes, with the color pattern
def.:1 repeating (like the stripes in a candycane) every N nodes (indicated by the integer
argument).
candycane2 float Sets the RGBA values for the second node color in candycane mode.
candycane3 float Sets the RGBA values for the third node color in candycane mode.
candycane4 float Sets the RGBA values for the fourth node color in candycane mode.
candycane5 float Sets the RGBA values for the fifth node color in candycane mode.
candycane6 float Sets the RGBA values for the sixth node color in candycane mode.
candycane7 float Sets the RGBA values for the seventh node color in candycane mode.
candycane8 float Sets the RGBA values for the eighth node color in candycane mode.
disabledalpha float Sets the transparency factor (between 0. and 1.) applied to the disabled nodes.
def.:0.4
displayknob int Sets the display options for the slider. The display options are:
def.:0 0: Hidden: the slider is not displayed.
1: Circle: the slider is displayed as a circle.
2: Picture: the slider uses a picture file.
'Hidden' = TEXT_HERE
'Circle' = TEXT_HERE
'Picture' = TEXT_HERE
knobbordercolor float Sets the RGBA values for knob circle border (when displayknob is set to circle).
knobcolor float Sets the RGBA values for knob circle (when displayknob is set to circle).
knobpict symbol The word knobpict, followed by the name of a file, will read any type of file into
def.:<default> the nodes object and attempt to interpret it as a knob image (when displayknob
is set to Picture).
knobsize float Sets the knob size in pixels.
def.:10.
mousemode int Sets the mouse behavior. Mouse behavior options are:
def.:0 0: Automatic: allows the mouse to change the nodes position or the slider (if
displayed).
1: Nodes: the mouse can only edit the nodes position and size.
2: Slider; the mouse can only changes the slider location.
'Automatic' = TEXT_HERE
'Nodes' = TEXT_HERE
'Slider' = TEXT_HERE
nodecolor float Sets the RGBA values for the first node.
nodenumber int Sets the number of nodes.
def.:1
nsize float Sets the sizes of every node.
parameter_enable int Parameter Mode Enable
pointcolor float Sets the RGBA values for the center color of the node.
textcolor float Sets the RGBA values for the text.
xplace float Sets the x position of every node.
yplace float Sets the y position of every node.

Information about attributes available for Parameter-aware objects

Information for box attributes common to all objects

Examples
See Also
Name Description
multislider Display data as sliders or a scrolling display
pictslider Picture-based slider control
pattrstorage Save and recall pattr presets
notein
Receive MIDI note messages

Description
Receives its input from a MIDI note-on or note-off message sent by a MIDI input device.

Arguments
Name Units Type Opt Description
port symbol opt Specifies the port (a-z) from which to receive incoming note messages. If there is
no argument, notein receives from all channels on all ports.
device symbol opt The name of a MIDI input device may be used as the first argument to specify the
port.
port-channel list A letter and number combination (separated by a space) indicates a port and a
specific MIDI channel on which to receive note messages. Channel numbers
greater than 16 will be wrapped around to stay within the 1-16 range.
channel int A number alone can be used in place of a letter and number combination. The
exact meaning of the channel number argument depends on the channel offset
specified for each port in the MIDI Setup dialog.

Messages
anything port [list] Performs the same function as port without the word, "port".
(mouse) Double-clicking on a notein object shows a pop-up menu for choosing a MIDI port
or device.
(MIDI) The notein object receives its input from a MIDI note-on or note-off message
received from a MIDI input device.
port port [symbol] The word port, followed by a letter a-z or the name of a MIDI input port or
device, sets the port from which the object receives incoming note messages. The
word port is optional and may be omitted.

Information for box attributes common to all objects

Output
int: Out left outlet: The number is the pitch value of the incoming note message.

Out 2nd outlet: The number is the velocity of the incoming note-on message if non-zero, 0 for a note-off message. To receive
release velocity, use xnotein.

If a specific channel number is included in the argument, there are only two outlets. If there is no channel number specified by
the argument, notein will have a third outlet, on the right, which will output the channel number of the incoming note message.

Examples

Note-on messages can be received from everywhere, a specific port, or a specific port and channel
See Also
Name Description
ctlin Output received MIDI control values
midiin Output raw MIDI data
noteout Transmit MIDI note messages
nslider Output numbers from a notation display
rtin Receive MIDI real time messages
xbendin Interpret extra precision MIDI pitch bend values
xnotein Interpret MIDI note messages with release velocity
Max MIDI Tutorial 1: Basic MIDI Max MIDI Tutorial 1: Basic MIDI
noteout
Transmit MIDI note messages

Description
Transmits note-on and note-off messages to a MIDI device.

Arguments
Name Units Type Opt Description
port symbol opt Specifies the port (a-z) for transmitting MIDI note messages. Channel numbers
greater than 16 received in the right inlet will be wrapped around to stay within the
1-16 range. If there is no argument, noteout initially transmits out port a, on
MIDI channel 1.
port-channel list A letter and number combination (separated by a space) indicates a port and a
specific MIDI channel on which to transmit note messages. Channel numbers
greater than 16 will be wrapped around to stay within the 1-16 range.
device symbol opt The name of a MIDI output device may be used as the first argument to specify the
port.
channel int A number alone can be used in place of a letter and number combination. The
exact meaning of the channel number argument depends on the channel offset
specified for each port in the MIDI Setup dialog.

Messages
int input [int] In left inlet: The number is the pitch value of a MIDI note message transmitted on
the specified channel and port. Numbers are limited between 0 and 127.
(inlet1) velocity [int] In middle inlet: The number is stored as the velocity of a note message, to be used
with pitch values received in the left inlet. Numbers are limited between 0 and 127.
0 is considered a note-off message, 1-127 are note-on messages.
(inlet2) channel [int] In right inlet: The number is stored as the channel number on which to transmit
the note-on messages.
float input [float] Converted to int.
anything port [list] Performs the same function as port but without need for the word, "port".
(mouse) Double-clicking on a noteout object shows a pop-up menu for choosing a MIDI
port or device.
port port [symbol] In left inlet: The word port, followed by a letter a-z or the name of a MIDI output
port or device, specifies the port used to transmit the MIDI messages. The word
port is optional and may be omitted.

Information for box attributes common to all objects

Output
(MIDI): There are no outlets. The output is a MIDI note-on message transmitted directly to the object's MIDI output port.

Examples

Letter argument transmits to only one port... Otherwise, number specifies both port and channel
See Also
Name Description
ctlout Transmit MIDI controller messages
midiout Transmit raw MIDI data
notein Receive MIDI note messages
nslider Output numbers from a notation display
xbendout Format extra precision MIDI pitch bend messages
xnoteout Format MIDI note messages with release velocity
Max MIDI Tutorial 1: Basic MIDI Max MIDI Tutorial 1: Basic MIDI
!=
Compare numbers for not-equal-to condition

Description
Compares two given numbers. If they are not equal, outputs a 1, if they are equal, outputs a 0.

Arguments
Name Units Type Opt Description
initial- int or opt Sets the initial value, to be compared with a number received in the left inlet. A
comparison-value float float argument forces a float comparison.

Messages
bang In left inlet: Performs the comparison with the numbers currently stored. If there
is no argument, != initially holds 0 for comparison.
int input [int] In left inlet: The number is compared with the number in the right inlet. If the two
numbers are not equal, != outputs 1. If they are equal != outputs 0.
(inlet1) comparison-value [int] In right inlet: The number is stored, to be compared with a number received in the
left inlet.
float input [float] Converted to int before comparison, unless != has a float argument.
set set-input [int] Sets the number to be compared without causing output (bang will output it).
list input [number] In left inlet: Compares first and second number, outputs 1 if they are not equal, 0
comparison-value [number] if they are equal.

Information for box attributes common to all objects

Output
int: 1 if the numbers in the inlets are not equal, 0 if they are equal.

Examples

Test if two numbers are not equal

See Also
Name Description
select Output bangs based on input matching
split Look for a range of numbers
< Compare numbers for less than condition
<= Compare numbers as less than or equal to
== Compare numbers for equal-to condition
> Compare numbers for greater than condition
>= Compare numbers for greater than or equal to condition
Max Basic Tutorial 19: Timing Max Basic Tutorial 19: Timing
nslider
Output numbers from a notation display

Description
nslider or "Note Slider" is a musical-notation-based integer value slider.

Arguments
None.

Messages
bang In left inlet: Sends out the pitch and velocity values currently stored in nslider.
int input [int] The number received in the inlet is displayed graphically by nslider if it falls
within its displayed range. The current velocity value (from 1 to 127) that nslider
holds is sent out its right outlet, followed by the received number out the left
outlet.
(inlet1) velocity [int] In right inlet: The number received in the right inlet sets the output key velocity
without triggering output.
float input [float] In left inlet: Converted to int.
(inlet1) velocity [float] In right inlet: Converted to int.
list value-pair [list] A list of two numbers sent to the left inlet of nslider can be used to set and output
the note and velocity values.
chord value-pairs [list] In left inlet: The word chord, followed by a list of MIDI note name and velocity
pairs, can be used to play chords on the nslider in polyphonic mode (set by the
mode 1 message). The chord message sends note-offs for currently held notes,
followed by note-on commands for the specified note and velocity pairs. When the
nslider object's state is saved by a preset object in polyphonic mode, the preset
object will store chord messages.
clear In left inlet: The clear message will clear any notes on the staves, but will not
trigger any output.
flush In left inlet: When the nslider object is in polyphonic mode (set by the mode 1
message), the flush message will send note-offs to currently held notes and clear
the nslider object's display.
(mouse) nslider also sends out numbers when you click or drag on it with the mouse. The
velocity value is determined by the previous value received in the right inlet.
If the nslider object is in polyphonic mode, you need to click on a note twice: once
to send a note-on and draws the note, and once again to send a note-off and erase
the note.
set value-pair [list] In left inlet: The word set, followed by a number, changes the value displayed by
nslider, without triggering output. If the set message is followed by two numbers,
both the note and velocity values are set, without causing output.

Attributes
Name Type g/s Description
bgcolor float Sets the background color for the object in RGBA format.
bordercolor float Sets the border color for the object in RGBA format.
clefs int Display clefs
def.:1
fgcolor float Sets the foreground color for the object in RGBA format.
mode int Sets the nslider object's mode of operation.
def.:0 Monophonic: (the default) Only one note can be selected and displayed at one
time.
Polyphonic: The kslider object keeps track of note-ons and note-offs, so it
mirrors which notes are currently held down on your MIDI keyboard. A key is
turned off by sending the kslider object a key on message with a velocity of 0.
'Monophonic' = TEXT_HERE
'Polyphonic' = TEXT_HERE
parameter_enable int Parameter Mode Enable
rounded int Sets the radius, in pixels for the nslider object.
def.:8

Information about attributes available for Parameter-aware objects

Information for box attributes common to all objects

Output
int: nslider sends its current velocity value out its right outlet, followed by the (displayable) pitch value out its left outlet, when a
number is received in its inlet or you click or drag on the object. In polyphonic mode, it will send a note value with a velocity of
zero when a note is removed from the staves.

Examples

A useful tool to monitor an incoming MIDI stream

See Also
Name Description
kslider Output numbers from an onscreen keyboard
makenote Generate a note-on/note-off pair
notein Receive MIDI note messages
noteout Transmit MIDI note messages
pictslider Picture-based slider control
rslider Display or change a range of numbers
slider Move a slider to output values
number
Display and output a number

Description
Displays, inputs, and outputs integer numbers.

Arguments
None.

Messages
bang Sends the currently displayed number out the outlet.
int input [int] The number received in the inlet is stored and displayed in the number box and
sent out the outlet. A float is converted to int by an int number box, and vice
versa.
float input [float] The number received in the inlet is stored and displayed in the number box and
sent out the outlet. A float is converted to int by an int number box, and vice
versa.
max maximum [list] The word max, followed by a number, sets the maximum value that can be
displayed or sent out by the number box. The word max by itself sets the
maximum to None (removes a prior maximum value constraint).
min minimum [list] The word min, followed by a number, sets the minimum value that can be
displayed or sent out by the number box. The word min by itself sets the
minimum to None (removes a prior minimum value constraint).
(mouse) Clicking and dragging up and down on the number box with the mouse (when the
patcher window is locked) moves the displayed value up and down, and outputs
the new values continuously.
In the float number box, dragging to the left of the decimal point changes the
value in increments of 1. Dragging to the right of the decimal point changes the
fractional part of the number in increments of 0.01.
When the active patcher window is locked, numbers can be entered into a number
box by clicking on it with the mouse and typing in a number on the computer
keyboard. Typing the Return or Enter keys on Macintosh or the Enter key on
Windows, or clicking outside the number box, sends the number out the outlet.
select The word select will make the number box active so that you can type numbers
straight into it (click on any empty space in a locked patcher to deselect it).
set input [int] The word set, followed by a number, sets the stored and displayed value to that
number without triggering output.

Attributes
Name Type g/s Description
bgcolor float Sets the color for the number box object's displayed/unclicked background.
bordercolor float Sets the color for the number box object's outline.
cantchange int The word cantchange, followed by a zero or one, toggles the ability to disallow
def.:0 changes with the mouse or the computer keyboard. The default is 0
(mouse/keyboard output active).
format int Sets characteristics of the appearance and behavior of the number box. The
def.:0 options are:
Decimal: (the default) Shows numbers in decimal form.
Hex: Shows numbers in hexadecimal, useful for MIDI-related applications.
Roland Octal: Shows numbers in a format used by some hardware devices where
each digit ranges from 1 to 8; 11 is 0 and 88 is 63.
Binary: Shows numbers as ones and zeroes.
MIDI Note Names: Shows numbers according to their MIDI pitch value, with 60
displayed as C3.
Note Names C4: Same as MIDI Note Names except that 60 is displayed as C4.
With all display modes, numbers must be typed in the format in which they are
displayed.
'Decimal' = TEXT_HERE
'Hex' = TEXT_HERE
'Roland Octal' = TEXT_HERE
'Binary' = TEXT_HERE
'MIDI' = TEXT_HERE
'MIDI (C4)' = TEXT_HERE
hbgcolor float Sets the color for the number box object's clicked-on background.
htextcolor float Sets the color for the number box object's clicked-on number.
htricolor float Sets the highlight color for the triangle inside the number box object that
indicates that the contents are editable.
maximum atom Sets the maximum value that can be displayed or sent out by the number box.
def.:<none>
minimum atom Sets the minimum value that can be displayed or sent out by the number box.
def.:<none>
mouseup int Toggles sending the current value on Mouse Up.
def.:0
outputonclick int Toggles sending the current value when you click on the number box.
def.:0
parameter_enable int Parameter Mode Enable
textcolor float Sets the color for the number box object's displayed/unclicked number values.
triangle int Toggles the drawing of a triangular arrow pointing to the number in the number
def.:1 box. The default is 1 (draw the triangle).
tricolor float Sets the color for the triangle inside the number box object that indicates that the
contents are editable.
triscale float Scales the size of the triangle drawn in the number box.
def.:1.
Legacy
brgba list (3 ints) brgba is a legacy RGB alias for the bgcolor RGBA attribute. See here for more
information.
frgba list (3 ints) frgba is a legacy RGB alias for the textcolor RGBA attribute. See here for more
information.
rgba2 list (3 ints) rgba2 is a legacy RGB alias for the htextcolor RGBA attribute. See here for more
information.
rgba3 list (3 ints) rgba3 is a legacy RGB alias for the hbgcolor RGBA attribute. See here for more
information.
rgba4 list (3 ints) rgba4 is a legacy RGB alias for the bordercolor RGBA attribute. See here for
more information.

Information about attributes available for Parameter-aware objects

Information for box attributes common to all objects

Menu Items
Name Description
Color Choosing the Color... menu item from the Object menu when the object is
selected opens a color picker, permitting adjustment to the appearance of the
number box.

Output
float: The number displayed in the number box is sent out the outlet. Numbers received in the inlet or typed on the computer
keyboard can exceed the limits of the number box, but the value that gets stored, displayed, and sent out will automatically be
limited to the specified range.
int: The number displayed in the number box is sent out the outlet. Numbers received in the inlet or typed on the computer
keyboard can exceed the limits of the number box, but the value that gets stored, displayed, and sent out will automatically be
limited to the specified range.

Examples

Displays numbers passing through.... Can be used to output numbers

See Also
Name Description
float Store a decimal number
int Store an integer value
Max Basic Tutorial 3: Numbers Max Basic Tutorial 3: Numbers and Lists
and Lists
numkey
Interpret numbers typed on the keyboard

Description
Arguments
Name Units Type Opt Description
format float opt A float argument causes numkey to understand the decimal point and the
fractional part of a number, and send out floats instead of ints. (The argument
does not, however, set an initial value for numkey. The initial value is always 0.)

Messages
bang Sends the number currently stored in numkey out the left outlet, and resets the
stored number to 0.
int ASCII [int] The number is an ASCII value received from a key or keyup object. When digits
are typed on the computer keyboard, numkey recognizes the ASCII values and
interprets them as the numbers being typed.

The keys recognized by numkey are the digits 0-9, the Delete (Backspace) key,
decimal point (period), Return, and Enter. Digits are combined as a single number
and stored in numkey.
clear Reset the stored number to 0

Information for box attributes common to all objects

Output
float: When there is a float argument, numkey understands decimal points and fractional parts of a number, and sends out floats
instead of ints.
int: When digits are typed on the computer keyboard, and the ASCII value (from key or keyup) is received in the inlet, the digits
are combined as a single number and stored in numkey. The stored number is sent out the right outlet each time a new digit is
typed. The Delete key on Macintosh or Backspace key on Windows erases the most recently typed digit, and sends the stored
number out the right outlet. The period key acts as a decimal point and causes numkey not to store subsequent digits until a new
number is started (unless there is a float argument). Typing the Return or Enter keys on Macintosh or the Enter key on Windows
sends the stored number out the left outlet and resets the number stored in numkey to 0, so that a new number can be typed in.

Examples

Recognizes all numbers typed in

See Also
Name Description
key Report keyboard presses
keyup Report key information on release
number Display and output a number
Max Basic Tutorial 8: Keyboard Max Basic Tutorial 8: Keyboard and Mouse Input
and Mouse Input
offer
Store one-time number pairs

Description
Store two ints as an x, y pair, and access them by x value. When a pair is retrieved, it is deleted from the collection.

Arguments
None.

Messages
bang bang will cause offer to output every y-value received since the last clear message
was received (or since the last initialization).
int x [int] In left inlet: The number specifies the x value of an x,y pair. If a y value has been
received in the right inlet, the two numbers are stored together in offer;
otherwise, offer looks for an x value that matches the incoming number, sends out
the corresponding y value, then deletes the stored pair. If there is no x value
stored in offer that matches the number received, offer does nothing.
(inlet1) y-value [int] In right inlet: The number specifies a y value to be stored in offer. The next x
value (int) received in the left inlet causes the two numbers to be stored together
as an x,y pair.
clear In left inlet: Deletes the entire contents of offer.

Information for box attributes common to all objects

Output
int: If the number received in the left inlet matches the x value of an x,y pair stored in offer, the corresponding y value is sent
out and the stored pair is deleted.

Examples

A pair of numbers can be stored, then recalled a single time

See Also
Name Description
coll Store and edit a collection of data
funbuff Store pairs of numbers
table Store and edit an array of numbers
onebang
Gate bangs using a bang

Description
Allows a bang in the left inlet to pass through ONLY if a bang has been received in the right inlet. After that, a bang in the left
inlet will not get through again until a bang has been received again in the right inlet.

Arguments
Name Units Type Opt Description
initialization int opt A non-zero argument sets onebang to permit a bang to be sent out the left outlet
the first time a bang is received in the left inlet.

Messages
bang In left inlet: Causes a bang to be sent out the left inlet only if a bang has been
received in the right inlet since the last bang was sent out.

In right inlet: Resets onebang to permit a bang to be sent out the next time a
bang is received in the left inlet.
int input [int] In either inlet: Same as a bang.
float input [float] In either inlet: Same as a bang.
list input [list] In either inlet: Same as a bang.
anything input [list] In either inlet: Converted to bang.
stop In left inlet: Undoes the effect of a bang in the right inlet.

Information for box attributes common to all objects

Output
bang: When onebang receives a bang in its left inlet, it sends a bang out its left outlet only if it has received a bang in its right
inlet since the last time it sent out a bang. Otherwise, it sends a bang out its right outlet.

Examples

Allow just one of (potentially) many bang messages to get through

See Also
Name Description
gate Pass input to an outlet
Ggate Send input to one of two outlets
onecopy
Prevent multiple copies of the same patcher from being opened

Description
Use the onecopy object inside a patcher that you want to place in the extras folder for inclusion in the Extras menu. When the
patcher's name is chosen using the Extras menu, its window will be brought to the front instead of opened a second time if it has
already been loaded. The patch will be loaded if it is not currently open. The onecopy object cooperates with the Extras menu to
ensure that only one copy of the patcher is opened at a time. However, opening the patcher containing a onecopy object by
choosing Open... from the File menu will open additional copies.

Arguments
None.

Information for box attributes common to all objects

Output
(Behavioral): onecopy includes the patcher, within which it resides, in the Extras menu and ensures that only one copy of the
patcher is opened at a time.

Examples

Use onecopy to prevent multiple copies of the same patch from being opened from the Extras menu

See Also
Name Description
thispatcher Send messages to a patcher
pcontrol Open and close subwindows
opendialog
Open a dialog to ask for a file or folder

Description
Use the opendialog object to select a file of a specific type or folder from a standard dialog window. To choose a folder, use the
"fold" type. opendialog reports the entire pathname of the file or folder chosen, which can be passed to any Max object after the
word read or load.

Arguments
Name Units Type Opt Description
folder symbol opt Sets opendialog to choose folders only
soundfile symbol opt Use this argument to list audio files (AIFF, NeXT/Sun, and WAV, along with some
generic data file types). The QuickTime appendix lists all the files that can be
opened.
file-types symbol opt One or more symbols set the list of file types that determine which files are listed
by the opendialog object.

Messages
bang Opens a standard Open Document dialog window for choosing a file or folder.
anything filetype [list] One or more symbols are interpreted as one or more type codes used to determine
which files are listed by the opendialog object. Example type codes for files are
TEXT for text files, maxb for Max binary format patcher files, and AIFF for AIFF
format audio files. types with no arguments makes the object accept all file types,
which is the default setting.
set filetype [list] The word set, followed by one or more four-letter symbols sets the opendialog
object to search for the specified file type(s) without opening a dialog window.
Example type codes for files are TEXT for text files, maxb for Max binary format
patcher files, and AIFF for AIFF format audio files. set with no arguments makes
the object accept all file types, which is the default setting.
types filetype [list] The word types, followed by one or more four-letter symbols (e.g., sets the
opendialog object to search for the specified file type(s) and opens a standard
dialog window. Example type codes for files are TEXT for text files, maxb for Max
binary format patcher files, and AIFF for AIFF format audio files. types with no
arguments makes the object accept all file types, which is the default setting.
sound Sets opendialog to list audio files (AIFF, NeXT/Sun, and WAV, along with some
generic data file types) and opens a standard dialog window. The QuickTime
appendix lists all the files that can be opened.

Information for box attributes common to all objects

Output
bang: If the dialog box is cancelled by the user, a bang message is sent out the right outlet.
symbol: Out left outlet: The absolute pathname of the file chosen by the user as a symbol. The output pathnames contain slash
separators.

Absolute pathnames look like this:

"C:/Max Folder/extras/mystuff/mypatch.pat"

The conformpath object can be used to convert paths of one pathtype and/or pathstyle to another.

Examples
Look for folders or a certain kind of file

See Also
Name Description
conformpath Convert file paths styles
dialog Open a dialog box for text entry
dropfile Interface for file drag and drop
date Report current date and time
filedate Report the modification date of a file
filein Read and access a file of binary data
filepath Manage and report on the Max search path
folder List the files in a folder
savedialog Open a dialog asking for a filename
strippath Separate filename from a full pathname
outlet
Send messages out of a patcher

Description
Show up as an outlet at the bottom of an object box when the patcher is used inside another patcher (as an object or a subpatch).
Messages received by the outlet object will come out of the corresponding outlet in the subpatch's object box.

Arguments
None.

Messages
(mouse) Double-clicking on an outlet object will open the parent patch or bring it to front.

Attributes
Name Type g/s Description
comment object Sets the mouse-over Assistance message for the outlet. This value can only be set
using the Comment setting in the inlet object's Inspector.

Information for box attributes common to all objects

Output
anything: Any messages received by outlet in a subpatch are sent out the outlet of that subpatch, through patch cords.

Examples

Outlets of the subpatch object correspond to the outlet objects inside the subpatch

See Also
Name Description
bpatcher Embed a subpatch with a visible UI
forward Send messages to specified receive objects
inlet Receive messages from outside a patcher
patcher Create a subpatch within a patch
receive Receive messages without patch cords
send Send messages without patch cords
Max Basic Tutorial 14: Max Basic Tutorial 14: Encapsulation
Encapsulation
pack
Create a list

Description
Combine items into an output list. The arguments determine the list format and types of the list elements. The number of inlets is
based on the number of arguments.

Arguments
Name Units Type Opt Description
list-elements any opt The number of inlets is determined by the number of arguments. Each argument
sets an initial type and value for an item in the list produced by pack. If there are
no arguments, the object will be created with two inlets, and the two list elements
will be set to (int) 0 initially.

Messages
bang Output currently stored list
int input [int] The number is stored as an item in a list, with its position in the list corresponding
to the inlet in which it was received. A number in the left inlet also causes the list
to be output. If the inlet has been initialized with a float or symbol argument, the
incoming number will be converted to a float or a blank symbol.
float input [float] The number is stored as an item in a list, with its position in the list corresponding
to the inlet in which it was received. A number in the left inlet also causes the
entire list to be the output. If the inlet has been initialized with an int or symbol
argument, the incoming number will be converted to an int or a (blank) symbol.
list input [list] Any multi-item message is treated as a list. The first item in the incoming list is
stored in in the location that corresponds to the inlet in which it was received.
Each subsequent item is stored as if it had arrived in subsequent inlets (limited to
the number of inlets available). A list received in the left inlet causes the entire
stored list to be sent out the outlet.
anything input [list] Performs the same function as list.
nth index [int] The nth message will output the stored list element at the index. Output is sent
from the first outlet.
send receive-name [list] Sends the stored list to all receive objects with a matching name.
set input [list] Sets the values without causing list output. Although the set message works with
any inlet, it is only meaningful in the left inlet, which is the only inlet that will
trigger output.
symbol input [symbol] Stores the symbol in the list at the position corresponding to the inlet it was
received. If the list element was initialized as a number, the symbol is converted to
0 before being stored. A symbol in the left inlet triggers output of the list.

Information for box attributes common to all objects

Output
any: When the nth message is received, the value of the specified item is sent out.
list: The length of the list is determined by the number of arguments. When input is received in the left inlet, the stored list is
sent out the outlet.

Examples
Numbers and symbols may be mixed as needed in pack

See Also
Name Description
bondo Synchronize a group of messages
buddy Synchronize arriving data
join Combine items into a list
match Watch for a message match, then output the message
pak Output a list when any element changes
swap Swap position of two numbers
thresh Combine messages when received close together
unjoin Break a list into messages
unpack Break a list into individual messages
zl Process lists in many ways
Max Basic Tutorial 9: Mouse Max Basic Tutorial 9: Mouse Drawing
Drawing
pak
Output a list when any element changes

Description
The pak object (pronounced "pock") offers much of the functionality of pack, but outputs the entire list occurs whenever input is
received in any inlet.

Arguments
Name Units Type Opt Description
list-elements any opt The number of inlets is determined by the number of arguments. Each argument
sets an initial type and value for an item in the list produced by pak. If there are
no arguments, the object will be created with two inlets, and the two list elements
will be set to (int) 0 initially.

Messages
bang Output currently stored list
int input [int] The number is stored as an item in a list, with its position in the list corresponding
to the inlet in which it was received, then the entire list is output. If the inlet has
been initialized with a float or symbol argument, the incoming number will be
converted to a float or a blank symbol.
float input [float] The number is stored as an item in a list, with its position in the list corresponding
to the inlet in which it was received, then the entire list is output. If the inlet has
been initialized with an int or symbol argument, the incoming number will be
converted to an int or a (blank) symbol.
list input [list] Any multi-item message is treated as a list. The first item in the incoming list is
stored in in the location that corresponds to the inlet in which it was received.
Each subsequent item is stored as if it had arrived in subsequent inlets (limited to
the number of inlets available). After all values are stored, the list is output.
anything input [list] Performs the same function as list.
set message [list] Set data without output

Information for box attributes common to all objects

Output
list: The length of the list is determined by the number of arguments. When input is received in any inlet, the stored list is sent
out the outlet.

Examples

See Also
Name Description
bondo Synchronize a group of messages
buddy Synchronize arriving data
join Combine items into a list
match Watch for a message match, then output the message
swap Swap position of two numbers
thresh Combine messages when received close together
unjoin Break a list into messages
unpack Break a list into individual messages
zl Process lists in many ways
Tutorial 3: Math Operations on a Tutorial 3: Math Operations on a Matrix
Matrix
panel
Colored background area

Description
The panel object lets you create colored panels for use in creating user interfaces. The panel can be a variety of shapes, including
circles, triangles, arrows, and rectangles with optional rounded corners. Shadows and gradients can also be used.

Arguments
None.

Messages
(mouse) When drag_window is set to 1 and the patcher is locked, click-dragging on the
panel will drag the patcher window.
size width (pixels) [int] The word size, followed by two numbers, specifies the width and height, in pixels,
height (pixels) [int] of the panel object. The default panel size has a width of 69 and a height of 57.

Attributes
Name Type g/s Description
angle float The word angle, followed by a floating-point number in the range 0.-359., sets
def.:0. the gradient angle of the panel display.
arrow_orientation int If shape is set to 3 (arrow), this attribute sets the direction that the arrow is
def.:0 pointing.
'Left to Right' = TEXT_HERE
'Right to Left' = TEXT_HERE
'Top to Bottom' = TEXT_HERE
'Bottom to Top' = TEXT_HERE
bgcolor float Sets the color of the panel in RGBA format.
border int Sets the size in pixels of the panel object's border.
def.:0
bordercolor float Sets the color of the panel border in RGBA format.
drag_window int When drag_window is set to 1 and the patcher is locked, click-dragging on the
def.:0 panel will drag the patcher window.
grad1 float If mode is set to 1 (gradient), this attribute sets the color of the first gradient used
in the panel in RGBA format.
grad2 float If mode is set to 1 (gradient), this attribute sets the color of the second gradient
used in the panel in RGBA format.
horizontal_direction int If shape is set to 2 (triangle), this attribute sets the horizontal direction that the
def.:0 triangle is oriented.
'Left to Right' = TEXT_HERE
'Right to Left' = TEXT_HERE
mode int Sets the fill mode of the panel object.
'Color' = Color fill
'Gradient' = Gradient fill
rounded int Sets the amount in pixels by which to round a rectangular panel.
def.:8
shadow int Sets the size, in pixels for a "shadow" effect for the panel object. Positive numbers
def.:0 create a "raised" shadow effect, and negative numbers created a "recessed" effect.
shape int Sets the shape of the panel.
def.:0 'Rectangle' =
'Circle' =
'Triangle' =
'Arrow' =
vertical_direction int If shape is set to 2 (triangle), this attribute sets the vertical direction that the
def.:0 triangle is oriented.
'Top to Bottom' = TEXT_HERE
'Center' =
'Bottom to Top' = TEXT_HERE

Information for box attributes common to all objects

Menu Items
Name Description
Color Choosing the Color... menu item from the Object menu when the object is
selected opens a color picker, permitting adjustment to the appearance of the
panel object.

Output
none: Panel has no outputs and is used for creating user interfaces.

Examples

See Also
Name Description
fpic Display a picture from a graphics file
jsui Create user interfaces with Javascript
lcd Draw graphics in a patcher window
textbutton A user interface button/toggle
ubutton Send a bang with a transparent button
live.line Straight line
past
Notify when a threshold is passed

Description
Sends a bang when a number rises above a certain specified value.

Arguments
Name Units Type Opt Description
list list Sets the numbers which must be equaled or exceeded by the numbers received in
the inlet. Output will be triggered when any of the threshold values are met or
exceeded.
number int Triggers output when the number is met or exceeded.

Messages
int input [int] If there is only one argument, and the input is greater than or equal to it, and the
previous input was not greater than or equal to it, past sends a bang out the
outlet.
float input [float] If there is only one argument, and the input is greater than or equal to it, and the
previous input was not greater than or equal to it, past sends a bang out the
outlet.
list input [list] The numbers in the list are compared to the arguments. If all of the numbers in
the list are greater than or equal to the corresponding arguments, a bang is sent
out the outlet. Before a bang is sent again, however, past must receive a clear
message, or must receive another list in which the number that equaled or
exceeded its argument goes back below (is less than) its argument.
clear Causes past to forget previously received input, readying it to send a bang
message again.
set watch-list [list] The word set, followed by one or more numbers, sets the numbers which must be
equaled or exceeded by the numbers received in the past object's inlet.

Information for box attributes common to all objects

Output
bang: If all of the arguments are equaled or exceeded by the numbers received in the inlet, past sends out a bang. Otherwise,
past does nothing. A bang is sent only as a number increases past its threshold. Once the threshold has been passed, the number
must go below the threshold again, then increase past it, before another bang will be sent.

Examples

Send out bang only when the input goes past the threshold in an upward direction

See Also
Name Description
maximum Output the highest value
peak Output larger numbers
> Compare numbers for greater than condition
patcher
Create a subpatch within a patch

Description
Creates patches within patches.

Arguments
Name Units Type Opt Description
subpatch symbol opt The subpatch can be given a name by the argument, so that its name appears in
the title bar of the subpatch window. The name in the title bar of the subpatch
window is displayed in brackets to indicate that it is part of another file. If there is
no argument typed in, the subpatch window is named [sub patch]. Different
patcher objects that share the same name are still distinct subpatches, and do not
share the same contents.

Attributes
Name Type g/s Description
bgcolor float Sets the background color in RGBA format.
boxanimatetime int Sets the rate, in milliseconds, used for animation of object behavior in the patcher
window.
default_fontface int Sets the default type style. 0 is plain (regular), 1 is bold, 2 is italic, and 3 is bold
italic.
'regular' = TEXT_HERE
'bold' = TEXT_HERE
'italic' = TEXT_HERE
'bold italic' = TEXT_HERE
default_fontname symbol Sets the default font name.
default_fontsize float Sets the default font size (in points).
'8' = TEXT_HERE
'9' = TEXT_HERE
'10' = TEXT_HERE
'11' = TEXT_HERE
'12' = TEXT_HERE
'13' = TEXT_HERE
'14' = TEXT_HERE
'16' = TEXT_HERE
'18' = TEXT_HERE
'20' = TEXT_HERE
'24' = TEXT_HERE
'30' = TEXT_HERE
'36' = TEXT_HERE
'48' = TEXT_HERE
'64' = TEXT_HERE
'72' = TEXT_HERE
defaultfocusbox symbol Sets the patcher window to get the focus by default.
description symbol Description
digest symbol Digest
edit_framecolor float Sets the color of the outline/halo that appears around an object or message box
when the object is being edited in RGBA format.
editing_bgcolor float Sets the background color displayed when the windows is being edited in RGBA
format.
enablehscroll int Toggles horizontal scrollbar display in a patcher window.
enablevscroll int Toggles vertical scrollbar display in a patcher window.
filepath symbol (get) Sets the filepath for the patcher window.
globalpatchername symbol Sets the global name by which this patcher can be referred to by pattr objects (for
more information, see the pattrmarker object).
gridonopen int Toggles displaying the grid in the patcher window when unlocked.
'default' = TEXT_HERE
'off' = TEXT_HERE
'on' = TEXT_HERE
gridsize float Sets the grid size in pixels.
gridsnaponopen int Toggles automatically setting the "Snap To Grid" option when the patcher is
unlocked.
'default' = TEXT_HERE
'off' = TEXT_HERE
'on' = TEXT_HERE
imprint int Toggles saving default-valued object attributes.
lockededit int Unsupported
openinpresentation int Toggles opening the patcher in Presentation mode automatically.
openrect float Sets the fixed initial window position (vertical offset/horizontal
offset/height/width) for the patcher window.
showontab symbol Show on Parent Patcher Tab
statusbarvisible int Show Status Bar on Open
'No' = TEXT_HERE
'Yes' = TEXT_HERE
'When Toolbar is Shown on Open' = TEXT_HERE
tags symbol Tags
title symbol Sets the title which appears in the patcher window.
toolbarvisible int Toggles showing the toolbar when the patcher is opened.

Information for box attributes common to all objects

Output
anything: The number of outlets a patcher object has is determined by the number of outlet objects contained within the
subpatch window. Output can also be sent via send and value objects contained in the subpatch. The actual messages sent out of
a patcher object depend on the contents of the subpatch.

When a patcher object is first created, the subpatch window is automatically opened for editing. To view or edit the contents of a
patcher object (or any subpatch object) later on, double-click on the object when the patcher window is locked.

All the objects in a subpatch of a patcher object are saved as part of the patcher which contains the object.

Examples

A patch can be contained (and saved) as part of another patch

See Also
Name Description
bpatcher Embed a subpatch with a visible UI
inlet Receive messages from outside a patcher
outlet Send messages out of a patcher
pcontrol Open and close subwindows
thispatcher Send messages to a patcher
Max Basic Tutorial 14: Max Basic Tutorial 14: Encapsulation
Encapsulation
Max pattr Tutorial 1: Patcher Max pattr Tutorial 1: Patcher Storage
Storage
patcherargs
Retrieve patcher arguments

Description
Retrieves patcher arguments and parses attribute style arguments. "normal" arguments are sent out the left outlet (first), and
attribute style arguments are sent out the right outlet (second).

Arguments
Name Units Type Opt Description
defaults int, float, symbol The patcherargs object permits access to more than 10 arguments for patchers
which are typed into an object box, but those contained within a bpatcher object
remain limited to 10 arguments.

Messages
bang Sends a list of the parent patcher's arguments out the left outlet.

If the parent patcher uses any attribute-style arguments (e.g. if any Jitter objects
are used in the patcher), they are sent out the right outlet as a series of lists.
(mouse) Double-clicking on the object will send the parent patcher's arguments out the left
outlet.

If the parent patcher uses any attribute-style arguments (e.g. if any Jitter objects
are used in the patcher), they are sent out the right outlet as a series of lists.

Information for box attributes common to all objects

Output
Int, float, symbol: Out left outlet: A list of the parent patcher's arguments are sent out the left outlet when the patcher is loaded.

Out right outlet: A series of lists corresponding to the attribute-style arguments (if any Jitter objects are contained in the patcher)
are sent out the right outlet when the patcher is loaded.

Examples

See Also
Name Description
bpatcher Embed a subpatch with a visible UI
thispatcher Send messages to a patcher
pattr
Provide an alias with a named data wrapper

Description
Stores its own data, or binds to another object to share its contents with other pattr-based objects (such as pattrstorage). Can be
used for data routing or preset creation.

Arguments
Name Units Type Opt Description
name symbol opt A symbol argument may be optionally used to set the pattr object's name. In the
absence of an argument (or the explicit setting of the name attribute using the
@name syntax), the pattr object is given an arbitrary, semi-random name, such as
u197000004.

Messages
bang Outputs the data maintained by the pattr object from the left outlet.
int input [int] An int is stored inside the pattr object and output from its left outlet. Optionally,
the value is passed along to a bound object. (See the bindto attribute for more
information on bound objects).
float input [float] float is stored inside the pattr object and output from its left outlet. Optionally,
the value is passed along to a bound object. (See the bindto attribute for more
information on bound objects).
list input [list] list is stored inside the pattr object and output from its left outlet. Optionally, the
value is passed along to a bound object. (See the bindto attribute for more
information on bound objects).
anything input [list] Any message is stored inside the pattr object and output from its left outlet.
Optionally, the value is passed along to a bound object. (See the bindto attribute
for more information on bound objects).
assign input [float] The word assign, followed by a floating point value, causes that value to be stored
and displayed and sent out the pattr object's left outlet. If the objects Parameter
Enabled attribute is set (checked) and the Parameter Visibility attribute is set to
Stored Only, the assign message will not add the new value to the Live
applications undo chain.
(mouse) Double-clicking on a pattr object that is parameter-enabled will open the
Parameters Window in Max for Live.
init If the pattr object's initial attribute has been set, the init message will cause the
pattr object's value to be set to value of the initial attribute.

Attributes
Name Type g/s Description
autorestore int Enables (1) or disables (0) the autorestore state of the pattr object. The default is 1
(enabled). When enabled, the pattr object will automatically output its last-saved
value when the patcher is loaded (and, if bound to another object, send the value
to that object. See the bindto attribute, below for more information on bound
objects).
bindto symbol The word bindto, which may be followed by an optional symbol argument, sets
the pattr object's binding state. The default state is unbound (no arguments). By
default, the pattr object maintains its own data. When "bound" using the bindto
feature, a pattr object maintains the data for the other object and automatically
gets and sets values for that object. bindto takes an optional symbol argument,
which specifies the name of the object to which pattr will bind. Binding targets
need not be at the same patcher-level as the pattr object. In this case, a double-
colon syntax ('::') is used to separate levels of patcher hierarchy for the purposes of
describing a path for name resolution (e.g. somepatcher::someobject). If the
named object is at a higher patcher-level than the pattr object, the word parent
can be used to refer to a patcher at a higher level (e.g. parent::objectaboveme,
parent::parent::objectaboveobjectaboveme or
parent::patchernexttome::someobject ).

If the named object contains attributes, and the user wishes to bind to a specific
attribute, the same double-colon syntax is used to specify the name of that
attribute (e.g. someobject::someattribute). A bindto message sent without an
argument unbinds the pattr object from any bound object, and causes it to resume
the maintenance its own internal state. See the pattr helpfile for more information
about this feature.
default_active int Enables (1) or disables (0) the pattr object's default active state, when it is
discovered by a pattrstorage object. The default is 1 (active). See the Reference for
the pattrstorage object for more information.
default_interp atom The word default_interp, followed by a symbol and an optional 2nd argument,
defines the pattr object's default interpolation setting, when it is discovered by a
pattrstorage object. The default is linear. See the Reference for the pattrstorage
object for more information.
default_priority int The word default_priority, followed by an int, defines the pattr object's default
priority, when it is discovered by a pattrstorage object. The default is 0. See the
Reference for the pattrstorage object for more information.
dirty int Enables (1) or disables (0) the patcher-dirty flag. The default is 0 (disabled). When
enabled, the pattr object will dirty the patch whenever its state changes.
initial atom The pattr object's initial value. If autorestore is set to 1, this value will be restored
def.: upon patch load, rather than the value of the pattr object at the time the patch
was last saved. The initial attribute can be used in combination with the init
message to reset the pattr object to the specified value.
invisible int The word invisible, followed by a 1 or 0, determines whether or not the pattr
object is invisible to pattrstorage objects. The default is 0 (visible).
parameter_enable int Enables parameter support.
thru int Enables (1) or disables (0) the pattr object's thru behavior. The default is 1
(enabled). When enabled, the object will output its value whenever it changes.
When disabled, the object will only output its value when it receives a bang
message.
type symbol The word type, followed by a symbol corresponding to a valid type, sets the data
type maintained internally by the pattr object, when the object is not bound. The
default is atom. Available types include char, long, float32, float64, symbol,
and atom.

Information about attributes available for Parameter-aware objects

Information for box attributes common to all objects

Output
(internal): A user interface object (or other object that responds to the internal messaging system utilized by pattr) connected to
the middle outlet of the pattr object will be automatically named (if necessary) and bound to. The name is automatically
generated from the object's class name (e.g. a connected number box might be named number[1].) Currently, the following Max
user interface objects can be bound in this fashion: dial, function, gain~, ggate, gswitch, js (requires user support), jsui (see
the JavaScript in Max manual for more information on using the pattr system with JavaScript), led, matrixctrl, multislider,
nslider, number box (int and float), pattr, pattrstorage, pictctrl, pictslider, radiogroup, rslider, slider, swatch, table,
textedit, toggle, and umenu.
anything: Out left outlet: When the pattr object receives new data, a bang, or registers the change of the value of its bound
object, this value is output.

Out right outlet: get queries to the pattr object's attributes are output from the right outlet, also known as the dumpout outlet.
Examples

See Also
Name Description
autopattr Expose multiple objects to the pattr system
pattrforward Send any message to a named object
pattrhub Access all pattr objects in a patcher
pattrmarker Provide pattr communication between patchers
pattrstorage Save and recall pattr presets
Max pattr Tutorial 1: Patcher Max pattr Tutorial 1: Patcher Storage
Storage
pattrforward
Send any message to a named object

Description
Routes messages or selects new message routing destinations according to the messages it receives. You can also use the
pattrforward object to route messages directly to a specific inlet of an object exposed by pattr or autopattr objects, and also send
messages directly to a subpatcher, abstraction or bpatcher.

Arguments
Name Units Type Opt Description
target symbol opt A symbol argument may be optionally used to specify the target object.

Messages
bang bang is passed to the target object.
int input [int] An int is passed to the target object.
float input [float] A float is passed to the target object.
list input [list] A list is passed to the target object.
anything input [list] Incoming messages to the pattrforward object are analyzed. If the first element of
the message matches the symbols in0, in1 ... inN, the pattrforward object will
forward all remaining arguments to a specific inlet of the target object. in0 refers
to the leftmost inlet (this is the default behavior of the pattrforward object), in1
refers to the inlet to the 2nd inlet from the left, and so on.

If the target object is a subpatcher, abstraction or bpatcher, the special element


inx can be used to send messages directly to the patcher object (in essence, in
order to communicate with a virtual thispatcher object associated with the patch).
(mouse) Double-clicking on the pattrforward object reveals the current target object in its
parent patcher.

Attributes
Name Type g/s Description
send symbol The word send, followed by the patcher name of any object in the patcher
hierarchy, sets the target object. Names can refer to objects in patchers other than
the one in which the pattrforward object resides. A double-colon syntax ('::') is
used to separate levels of the patcher hierarchy. For example,
some_subpatcher::some_object or parent::some_other_object would be valid
target object names.

Information for box attributes common to all objects

Output
anything: A message received in the inlet of pattrforward is sent to the named object anywhere in the patcher hierarchy.

Examples
See Also
Name Description
autopattr Expose multiple objects to the pattr system
forward Send messages to specified receive objects
pattr Provide an alias with a named data wrapper
pattrhub Access all pattr objects in a patcher
pattrmarker Provide pattr communication between patchers
pattrstorage Save and recall pattr presets
receive Receive messages without patch cords
send Send messages without patch cords
thispatcher Send messages to a patcher
pattrhub
Access all pattr objects in a patcher

Description
Centralizes communication with all pattr objects in a patcher.

Arguments
None.

Messages
bang bang is passed through the pattrhub object and output from its left outlet.
int input [int] An int is passed through the pattrhub object and output from its left outlet.
float input [float] float is passed through the pattrhub object and output from its left outlet.
list input [list] list is passed through the pattrhub object and output from its left outlet.
anything arguments [list] Incoming messages to the pattrhub object are analyzed. If the first element of the
message matches the name of a pattr- or autopattr-maintained object, the
subsequent arguments in the message set that object's value. If the first element of
the message matches get (name), where (name) matches the name of a pattr- or
autopattr-maintained object, the value of that object is sent from the pattrhub
object's right outlet, preceded by the object's name. Otherwise, the message is
passed through the pattrhub object and output from its left outlet.
getattributes The getattributes message causes a list of all pattr- or autopattr-maintained
object names to be output from the pattrhub object's right outlet, preceded by the
symbol attributes.
getstate The getstate message causes a series of lists to be output from the pattrhub
object's right outlet -- one for every pattr- or autopattr-maintained object in the
patcher containing the pattrhub object. Each list begins with the name of the
object, and is followed by the object's current value.

Attributes
Name Type g/s Description
patcher symbol The word patcher, followed by a symbol describing a valid path to a patcher, sets
the patcher referenced by the pattrhub object. The default is the special symbol
this, which represents the patcher the pattrhub object resides within. The
pattrhub object can refer to patchers other than the one in which the object
resides. A double-colon syntax ('::') is used to separate levels of patcher hierarchy.
See the pattrhub help file for further information on this feature.

Information for box attributes common to all objects

Output
anything: Out left outlet: Any message not matching a get or set request to a pattr- or autopattr-maintained object in the
pattrhub object's patcher is passed through the left outlet unchanged.

Out right outlet: get queries to the a pattr- or autopattr-maintained object in the pattrhub object's patcher are output from the
right outlet, also known as the dumpout outlet.

Examples
See Also
Name Description
autopattr Expose multiple objects to the pattr system
pattr Provide an alias with a named data wrapper
pattrforward Send any message to a named object
pattrmarker Provide pattr communication between patchers
pattrstorage Save and recall pattr presets
Max pattr Tutorial 1: Patcher Max pattr Tutorial 1: Patcher Storage
Storage
pattrmarker
Provide pattr communication between patchers

Description
The pattrmarker object associates a patcher with a global name, which can be used when looking up named objects. This permits,
among other conveniences, name lookup and communication between two or more independent patcher hierarchies.

Arguments
Name Units Type Opt Description
name symbol The name for the parent patcher of the pattrmarker object in the pattr global
namespace.

Messages
getmarkerlist all [int] Reports a list of all registered names in the pattr global namespace from the
pattrmarker object's outlet, prepended by the word markerlist. These names are
reported whether they were registered via pattrmarker objects or via the
globalpatchername attribute of the patcher object. With no argument, or an
argument of 0, the names of pattrmarker objects with the invisible attribute
enabled will not appear in the reported list. With an argument of 1, all names,
regardless of the invisible status, will be reported.
reveal name [symbol] Opens a view of the patcher referred to by the global name argument.

Attributes
Name Type g/s Description
invisible int When enabled, the name of this pattrmarker object will not appear in the list
reported by the getmarkerlist message.
name symbol The global name of the parent patcher of the pattrmarker object.

Information for box attributes common to all objects

Examples

See Also
Name Description
autopattr Expose multiple objects to the pattr system
pattr Provide an alias with a named data wrapper
pattrforward Send any message to a named object
pattrhub Access all pattr objects in a patcher
pattrstorage Save and recall pattr presets
pattrstorage
Save and recall pattr presets

Description
View and modify client object data, and store or recall presets.

Arguments
Name Units Type Opt Description
name symbol opt A symbol argument may be optionally used to set the pattrstorage object's
scripting name. In the absence of an argument, the pattrstorage object is given an
arbitrary, semi-random name, such as u197000004.

Messages
int index [int] Recalls the data from the preset specified by int.
float index [float] Recalls the data from the preset specified by float. If the number falls between two
whole numbers (e.g. 1.5), the pattrstorage object will interpolate between the
data stored in the preset corresponding to the integer portion of the float and the
data stored at the preset numbered one higher (e.g. 1.5 will cause pattrstorage to
interpolate 50% between presets 1 and 2). See the interp message for more
information about interpolation modes.
anything arguments [list] Incoming messages to the pattrstorage object are analyzed. If the first element of
the message matches the path name or alias of an object maintained by the
pattrstorage object (visible in the object's client list), the subsequent arguments
in the message set that object's value. Otherwise, the message is ignored.
active client [list] The word active, followed by a symbol that specifies the path name or alias of a
client object and a 1 or 0, sets that object's active status. When a client object is
active (default), its data will be recalled when presets are recalled--otherwise, the
object is ignored during recall. Setting the active state of a parent object (such as a
patcher-any client object containing other client objects), automatically sets the
active state of the child objects of the parent to the same value.
alias client [symbol] The word alias, followed by two symbols, generates an alias for the client object
alias [symbol] whose path name is given in the first argument. The alias permits the object to be
referred to by a name given in the second argument.

For example, alias a_patcher::a_pattr the_pattr would alias the object at the
location a_patcher::a_pattr to the name the_pattr.

Aliases can be used interchangeably with path names within the pattrstorage
object, and are useful for referring to long paths by simpler, shorter names.

get alias The word get alias, followed by a symbol that specifies the path name of
a client object, returns that object's alias (if any) from the pattrstorage object's
outlet, preceded by the symbol alias.
delete index [list] The word delete, followed by a number, clears any data in the preset whose index
is specified by that number and removes the preset from the pattrstorage object's
internal list. If delete is not followed by an argument, all presets are cleared and
removed. See the getslotlist message for further information on viewing the
object's list of presets.
dump The word dump reports the current value of all client objects from the
pattrstorage object's outlet as a series of messages, each in the form [object
pathname] [data ...]. The output of dump is finished when the message dump
done is output.
clear The word clear removes all presets from the pattrstorage object's internal list.
client_close Closes the client list window.
clientwindow name [list] Opens the pattrstorage object's client list window (the title bar reads
clientwindow (name), where (name) is the patcher name of the pattrstorage object
which created the window).
copy pattrstorage The word copy, followed by 2 or 3 arguments, copies the stored values from one
[symbol] numbered preset to another. Followed by 2 numbers, the stored values from the
from-index [int] preset slot specified by the first number will be copied to the preset slot specified
t0-index [int] by the second number. If that slot doesn't yet exist, it will be automatically
created. Followed by a symbol and 2 numbers, the stored values from a preset slot,
as specified by the first number, of the pattrstorage object referred to by the
symbol will be copied to a preset slot, as specified by the second number, of the
object receiving the copy message. For example, the message copy
parent::psto_parent 3 1 would cause preset 3 of the pattrstorage object called
psto_parent, located in the parent patch of the pattrstorage object receiving the
copy message, to be copied to preset 1 of the pattrstorage object receiving the
message. In order for this to function reliably, client path names must match
exactly. If they do not, the data for that client is ignored.
(mouse) Double-clicking on a pattrstorage object opens the object's client list window, as
if the object had received the clientwindow message.
fade list [list] Identical to the recall message. Deprecated.
getactive client [list] The word getactive, followed by a symbol that specifies the path name or alias of
a client object, reports the active status of the client object from the pattrstorage
object's outlet, preceded by the symbol active.
getalias client [list] The word getalias, followed by a symbol that specifies the path name or alias of a
client object, will cause pattrstorage to return that client-object's alias from its
outlet.
getclientlist The word getclientlist reports the path names of any client objects from the
pattrstorage object's outlet as a series of messages, each preceded by the symbol
clientlist. The output of getclientlist is finished when the message clientlist
done is output.
getcurrent The word getcurrent reports the currently active preset from the pattrstorage
object's outlet, preceded by the symbol current.
getedited The word getedited reports the edit state of the currently active preset from the
pattrstorage object's outlet, preceded by the symbol edited. If the data in the
currently active preset has been edited, the state is reported as 1. Otherwise, the
edit state is reported as 0.
getinterp client [list] The word getinterp, followed by a symbol that specifies the path name or alias of
a client object, reports that object's interpolation mode from the pattrstorage
object's outlet, preceded by the symbol interp.
getlockedslots The word getlockedslots reports the indices of any locked slots from the
pattrstorage object's outlet as a list, preceded by the symbol lockedslots.
getpriority client [list] The word getpriority, followed by a symbol that specifies the path name or alias
of a client object, reports that object's priority from the pattrstorage object's
outlet, preceded by the symbol priority.
getslotlist The word getslotlist reports the numbers of any valid presets from the
pattrstorage object's outlet, preceded by the symbol slotlist.
getslotname index [int] The word getslotname, followed by a number, causes the name of the preset slot
specified by the number to be output from the pattrstorage object's outlet,
preceded by the symbol slotname.
getslotnamelist range [int] The word getslotnamelist, followed by an optional number, reports the slot
names of all used slots to be sent from the pattrstorage object's outlet as a series
of messages, each preceded by the symbol slotlist. The output of getslotlist is
finished when the message slotname done is output.

Without an argument, or with an argument of 0, the getslotnamelist message


will cause all slots from 0 to the largest stored slot number to be output, regardless
of whether the slot has been defined or not. The facilitates the use of the
getslotlist message with objects such as umenu. To filter undefined slots (even if
they have names), send the getslotlist message with a non-0 argument.

For more information, see the pattrstorage object's help file.


getstoredvalue client [list] The word getstoredvalue, followed by a symbol that specifies the path name or
alias of a client object and a number which specifies a preset, reports that object's
value, as stored in that preset slot, from the pattrstorage object's outlet, in the
form [object pathname or alias] [data ...].
getsubscriptionlist The word getsubscriptionlist causes the names of all subscribed objects to be
sent from the pattrstorage object's outlet as a series of messages, each preceded
by the symbol subscriptionlist. The output of getsubscriptionlist is finished
when the message subscriptionlist done is output. See the subscribemode
attribute for more information.
grab The word grab causes the current value of all client objects to be reacquired by the
pattrstorage object. This is particularly useful when the pattrstorage object is
managing client objects whose data changes internally, without sending
notifications to the pattr system.
insert index [int] The word insert, followed by a number, stores the data for every object
maintained by pattrstorage in a numbered preset. The number argument specifies
the index of the preset to be stored. Any presets numbers at the specified index or
higher are automatically incremented to make room for the inserted preset.
interp arguments [list] The word interp, followed by at least 1 and up to 3 arguments (symbol, symbol,
float/symbol), sets the interpolation status and mode for a specific client object.
The first symbol specifies the path name or alias of a client object. The second
symbol argument determines the mode, and can be one of the following values:

off- No interpolation. Same as no additional argument.

linear- Linear interpolation. Presets recalled using float or fade messages will be
interpolated using a standard linear algorithm.

thresh- Threshold. Takes optional 3rd argument, which sets the threshold. Presets
recalled using float or fade messages will recall data from the first preset
specified when the fade amount is below the threshold, and will recall data from
the second preset specified when the fade amount is greater than or equal to the
threshold.

ithresh- Inverse threshold. Takes optional 3rd argument (float), which sets the
threshold. Presets recalled using float or fade messages will recall data from the
first preset specified when the fade amount is greater than or equal to the
threshold, and will recall data from the second preset specified when the fade
amount is less than the threshold.

pow- Power curve. Takes optional 3rd argument (float), which sets the exponent
to which the fade amount will be raised. Presets recalled using float or fade
messages will recall data between the two specified presets, along the curve
described. Power curves can be used to create faster or slower "attacks" and
"decays" for the fade envelope.

table- Table-specified curve. Takes optional 3rd argument (symbol), which


specifies the name of a table to use for curve lookup. Presets recalled using float
or fade messages will recall data between the two specified presets, along the
curve described in the table. Tables are assumed to contain values between 0 and
100, representing the new fade amount * 100 (this is clipped internal to the
pattrstorage object, but is not normalized). The length of the table is stretched to
match the expected fade values (between 0 and 1), so any number of table entries
can be used. If the lookup fade amount does not fall exactly onto a table-specified
value, linear interpolation is used to determine the new fade amount. Please see
the pattrstorage help file for examples of table-specified interpolation.
locate client [symbol] The word locate, followed by a symbol corresponding to the path name or alias of
an object, will cause the containing patcher of that object to be opened.
lock index [int] The word lock, followed by 2 numbers, sets the lock status for a particular preset
status [int] number. The first argument specifies the preset number to be locked or unlocked.
The second argument specifies the lock state, and should be either 0 (unlocked) or
1 (locked). Locked presets cannot be deleted (using the delete or remove
messages) or overwritten (using the store message). Locked presets can be moved
(as a result of insert, remove or renumber messages, if performed on other
presets). Locks are saved in the preset data file.
lockall status [int] The word lockall, followed by a number, sets the lock status for all presets at
once. The argument specifies the lock state, and should be either 0 (unlocked) or 1
(locked). Locked presets cannot be deleted (using the delete or remove messages)
or overwritten (using the store message). Locked presets can be moved (as a
result of insert, remove or renumber messages, if performed on other, unlocked
presets). Locks are saved in the preset data file.
priority client [list] The word priority, followed by a symbol that specifies the path name or alias of a
client object and a number, sets the recall and display priority for that object.
When presets are recalled, the data for client objects will be restored in the order
established by priority. Lower priorities are executed first. Negative priorities are
permitted. Priority is only respected within a single level of the patcher hierarchy.
Data in parent patchers will always be restored before data in nested patchers.
purge The word purge rebuilds the internal client list of the pattrstorage object,
removing entries for client objects which have been deleted or moved. Typically,
the pattrstorage object retains a reference to such objects, so that their settings
(priority, active, interp, etc.) can be restored if the objects reappear.
setall client [list] The word setall, followed by a symbol that specifies the path name or alias of a
client object and a variable number of additional arguments corresponding to the
value of the client object, sets the value of the specified client object for all preset
slots to that value. No data is sent to the client object itself.
setstoredvalue client [list] The word setstoredvalue, followed by a symbol that specifies the path name or
alias of a client object, a number which specifies a preset and a variable number of
additional arguments corresponding to the data expected by the client object, sets
the value of the specified client object within the specified preset slot to the
specified data.
slotname index [int] The word slotname, followed by a number and an optional symbol, sets the name
slotname [symbol] of the preset slot specified by the number. If the symbol argument is not present,
the name of the slot is removed. Undefined slots can be given names for labeling
purposes. If a preset object is linked to the pattrstorage object, it will display the
slot name of the corresponding pattrstorage slot.
store client-and-index The word store, followed by 1 or 2 arguments, stores data in a numbered preset. If
[list] the word store is followed by a number, the data for every object maintained by
pattrstorage will be stored. If store is followed by 2 arguments--a symbol and a
number--and the symbol argument matches the path name or alias of a client
object, only the data for the specified object will be stored. The number argument
always specifies the index of the preset to be stored. If the preset index specified by
the number argument is already in use, the existing data will be overwritten
without a warning.
storeagain client [list] The word storeagain simply executes a store operation, using the most recently-
use preset slot. If there is no previously-used preset slot (if the store message has
never been sent to the object), the message is ignored.
storenext client [list] The word storenext executes a store operation, using the next empty preset slot,
counting up from preset 1. For instance, if preset slots 1, 2 and 4 have data stored
in them, and the pattrstorage object receives the storenext message, the current
state of the client objects would be stored to preset slot 3. A second storenext
message would cause the data to be stored to preset slot 5.
read filename [list] The word read, followed by an optional symbol that specifies a filename, reads an
JSON or XML file representing preset data from disk into the pattrstorage object.
If the argument is given, and represents a valid file path, the file will be read from
that location--otherwise, a standard File Dialog will be presented for the user to
manually choose the file to be read.
readagain filename [list] The word readagain re-reads an JSON or XML file previously specified by the
read or write messages. If no file has been previously specified, a standard File
Dialog will be presented for the user to manually choose the file to be read.
recall client-name, The word recall, followed by 1 to 4 arguments, recalls data from a preset. If recall
preset-indices, and is followed by a number or a floating-point number, the data for every object
interpolation-value whose value is stored in the specified preset (or in the interpolated preset
[list] represented by a floating-point number--see float message, above) will be
recalled. If recall is followed by 2 arguments--a symbol and a number--and the
symbol argument matches the path name or alias of a client object, only the data
for the specified object will be recalled. The number argument always specifies the
index (or interpolated index) of the preset to recall.

Followed by 3 or 4 arguments, the recall message recalls interpolated data from 2


presets at a specified weight between the two. If the word recall is followed by two
numbers that specify the indices of two presets and a a floating point number
between 0 and 1.0 that specifies an interpolation value, the data for every object
whose value is stored in the specified presets will be recalled.

If recall is followed by a symbol that specifies the path name or alias of a client
object, followed by two numbers that specify the indices of two presets, and a
floating point interpolation value (see above), only the data for the specified object
will be recalled.

In these latter cases, the floating point argument specifies the weight of the
interpolation, and should be between 0. and 1. A floating point argument of 0.
would simply recall the data for the preset matching the first index, and 1. would
recall the data for the preset matching the second index. See the interp message
for more information about interpolation modes.
recallmulti weighted-pairs The word recallmulti, followed by at least 2 numeric arguments, permits weighted
[list] recall of multiple presets. Each argument determines the (normalized) weight of a
particular preset in the final output. If the argument is an integer, the weight is
100%. If the argument is a floating point number, the integer part of the number
determines the preset number, and the floating point part of the number
determines the weight. For instance, recallmulti 1.3 2.3 5.4 would weight preset
1 at 30%, preset 2 at 30% and preset 5 at 40%. Since weights are normalized, the
total weight can be higher than 100%; for instance, recallmulti 1.5 3.5 6.8
would calculate correct weights (27.77%, 27.77% and 44.44% respectively), and
recallmulti 1 2 3, recallmulti 1.5 2.5 3.5 and recallmulti 1.99 2.99 3.99 all
result in the same output (33.33% for each member).
remove index [int] The word remove, followed by a number, deletes the data for every object
maintained by pattrstorage in a numbered preset. The number argument specifies
the index of the preset to be removed. Any presets numbers higher than the
specified index are automatically decremented.
renumber The word renumber renumbers stored presets into consecutive preset slots,
beginning with slot 1.
resolvealias client [list] The word resolvealias, followed by a symbol that specifies the alias of a client
object, returns that object's full path name (if any) from the pattrstorage object's
outlet, preceded by the symbol resolvealias.
subscribe target [list] The word subscribe, followed by one or more symbols, each corresponding to the
path name or alias of an object, will add the specified object to the pattrstorage
object's subscription list. See the subscribemode attribute for more information.
storage_close Closes the stored data window.
storagewindow name [list] Opens the pattrstorage object's stored data window (the title bar reads
storagewindow (name), where (name) is the patcher name of the pattrstorage
object which created the window).
unsubscribe target [list] The word unsubscribe, followed by one or more symbols, each corresponding to
the path name or alias of an object, will remove the specified object from the
pattrstorage object's subscription list. See the subscribemode attribute for more
information.
write filename [list] The word write, followed by an optional symbol that specifies a filename, writes
any preset data to a JSON file on disk. If the argument is given, and represents a
valid file path, the file will be saved at that location - otherwise, a standard File
Dialog will be presented for the user to manually choose a name and location for
the file to be saved.
writeagain filename [list] The word writeagain writes any preset data to a JSON file on disk previously
specified by the read or write messages. If no file has been previously specified, a
standard File Dialog will be presented for the user to manually choose a name and
location for the file to be saved.
writejson filename [symbol] The word writejson, followed by an optional symbol that specifies a filename,
writes any preset data to a file on disk, in JSON format. If the argument is given,
and represents a valid file path, the file will be saved at that location--otherwise, a
standard File Dialog will be presented for the user to manually choose a name and
location for the file to be saved.
writ.html filename [symbol] The word writ.html, followed by an optional symbol that specifies a filename,
writes any preset data to a file on disk, in XML format. If the argument is given,
and represents a valid file path, the file will be saved at that location--otherwise, a
standard File Dialog will be presented for the user to manually choose a name and
location for the file to be saved.

Attributes
Name Type g/s Description
activewritemode int Sets the write mode for the active property of client objects. The default is 0
(disabled). When enabled, the active state of client objects will be saved with the
XML preset data file and restored when this file is re-read.
autopattr_vis int Sets the visibility of autopattr objects in the clientwindow and storagewindow
displays. The default is 0 (disabled). Since autopattr objects are not used for
forming path names, one can generally ignore them for the purposes of display.
When performing pattrstorage object functions, such as setting the active state
or priority for an entire set of objects being exposed by a single autopattr object,
the user needs to know the name of the objects' actual container object. Enabling
autopattr_vis may make this process somewhat clearer visually and conceptually.
autorestore int Enables or disables the pattrstorage object's autorestore state. The default is 1
(on). When enabled, the pattrstorage object will automatically try to locate and
read an XML file representing preset data when the patcher loads. The
pattrstorage object will attempt to load the last-saved file. If the pattrstorage
object in question has never saved a file, the object will attempt to load a file with
the name (name).html, where (name) is the patcher name of the pattrstorage
object (usually, its argument).
autowatch int Sets the pattrstorage object's file watching behavior. The default is 0 (disabled).
When file watching is enabled, the most recently read or written XML data file
will be reloaded automatically if it is modified. This allows you to use an external
editor for your XML data file. When you save the file, the pattrstorage object will
notice. Note that when the file is re-read, any currently unsaved data will be lost.
backupmode int Sets the number of backup XML files to be maintained and rotated by the
pattrstorage object when writing files. The default is 0 (disabled). The argument
specifies the number of backups the pattrstorage object should make before the
files start rotating (being automatically deleted to make room for new backups).
The most recent backup is called pstoname.bak.html. The next,
pstoname_1.bak.html, followed by pstoname_2.bak.html, etc.
changemode int Sets the pattrstorage object's data-filtration behavior. The default is 0 (disabled).
When enabled, only changed values are sent from the pattrstorage object to
client objects, and repeated data is filtered.
client_rect float Sets a new size and position for the client list window. The window position is
def.:50. 50. 400. specified in global coordinates by 4 numbers (left, top, right, bottom).
500.
dirty int Enables or disables the patcher-dirty flag. The default is 0 (disabled). When
enabled, the pattrstorage object will dirty the patch whenever its state changes.
fileusagemode int Enables or disables the inclusion of JSON/XML storage files in collectives and
standalones. The default is 0 (include storage file).
flat int Enables or disables the pattrstorage object's client list display flag. The default is
0 (disabled). When enabled, the pattrstorage object's 2 windows will not display a
hierarchical view of clients, instead display only data-containing objects (no
patchers), and their full path name or alias.
greedy int Sets the pattrstorage object's client search behavior flag. The greedy attribute
provides a way to limit the amount of data a single pattrstorage object will
manage. The following values are possible:

0 = disabled (the default). The pattrstorage object can see all pattr objects or
objects bound to autopattr objects in any child patches of the pattrstorage object
(or child patches of those child patches, tunneling down through the patcher
hierarchy), until another pattrstorage object is found. Although the pattrstorage
object found in a child patch will be a client of the parent pattrstorage object, no
other objects at that level or below in the patcher hierarchy will be.

1 = see everything. When the greedy attribute is set to 1, the pattrstorage object
can see everything, all the way down to the bottom of the patcher hierarchy
(including any pattrstorage objects it finds along the way).

2 = clients only. When the greedy attribute is set to 2, the pattrstorage object
can only see potential client objects in its patch. No other patches are searched.
notifymode int Sets the pattrstorage object's add/remove-notification behavior. The default is 0
(disabled). When enabled, the pattrstorage object will send a message from it's
outlet every time an object is added or removed from its client list, in the form
[add/remove] [object pathname]. Note that the pattrstorage object must
occasionally purge and fully rebuild its client list in response to certain events,
resulting in significant output when notifymode is enabled and objects are being
added and removed regularly.
outputmode int Sets the pattrstorage object's auto-output behavior. The default is 0 (disabled).
When enabled, the pattrstorage object will send a message from its outlet every
time the value of one of its client objects changes, in the form [object pathname]
[data ...]. The following modes are available:

0 = disabled
1 = output all changes to client objects
2 = output all non-repeated changes to client objects (see changemode)
3 = output all changes to client objects not initiated by a message to the
pattrstorage object
4 = output all non-repeated changes to client objects not initiated by a message to
the pattrstorage object (see changemode)
parameter_enable int Enables parameter support. Please read the document Device Parameters in
Max for Live for more information.
savemode int Sets the pattrstorage object's save behavior. The default is 1 (prompt on object
free). In this mode, if the pattrstorage object's preset data has changed (presets
have been stored, deleted or modified since the last file read or write operation) at
the time the object is freed, the object will prompt the user to write a preset file. In
mode 2, pattrstorage will attempt to autosave a preset file (without user
interaction), whenever the patcher is saved. In mode 0, pattrstorage will neither
prompt nor autosave. In mode 3, pattrstorage will attempt to autosave a preset
file (without user interaction), whenever the patcher is freed.

The following values are possible:

0 = Neither prompt nor autosave


1 = Prompt the user to save a preset file when the object is freed (default)
2 = Attempt to autosave whenever the patcher is saved, or if unsuccessful, prompt
the user to save a preset file
3 = Attempt to autosave (without user interaction) when the patcher is freed.
Failing that, prompt the user
storage_rect float Sets a new size and position for the stored data window. The window position is
def.:600. 50. 400. specified in global coordinates by 4 numbers (left, top, right, bottom).
500.
subscribemode int Sets the subscription mode. The default is 0 (disabled). When enabled, the
pattrstorage object uses a user-specified subscription list to determine which
objects are clients, rather than discovering and maintaining all objects within the
patcher/patcher hierarchy (as determined by the greedy attribute. The subscribe
and unsubscribe messages can be used to add and remove objects to and from
this list, and the getsubscriptionlist message can be used to output a list of
currently subscribed objects.

Information about attributes available for Parameter-aware objects

Information for box attributes common to all objects

Output
anything: Multiple messages, corresponding to the various input messages above.

Examples

See Also
Name Description
autopattr Expose multiple objects to the pattr system
pattrforward Send any message to a named object
pattrhub Access all pattr objects in a patcher
pattrmarker Provide pattr communication between patchers
Save and recall pattr presets
Max pattr Tutorial 2: Automatic
Max pattr Tutorial 2: Automatic Bindings and Storage
Bindings and Storage
pcontrol
Open and close subwindows

Description
Serves as a remote control for patcher/subpatcher windows and functions.

Arguments
None.

Messages
close patcher [list] Closes the patcher window of any subpatches or patcher objects connected to the
pcontrol object's outlet.
help filename [symbol] The word help, followed by a symbol, opens a help file in Max's max-help folder
with the name of the symbol followed by .help.
load filename [list] The word load, followed by the name of a patcher file, opens that file if it can be
found in Max's search path. The file name may optionally be followed by up to
nine numbers and/or symbols, which will be substituted for the appropriate
changeable # arguments (#1 to #9) in the patch being opened.
loadunique patcher [list] The word loadunique, followed by the name of a patcher file, opens a single
instance that file if it can be found in Max's search path. If the file has already
been loaded, the previously loaded copy will be activated (i.e. only a single copy of
the file may be opened). As with the load message, the file name may optionally
be followed by up to nine numbers and/or symbols, which will be substituted for
the appropriate changeable # arguments (#1 to #9) in the patch being opened.
open patcher [list] Opens the patcher window of any subpatches or patcher objects connected to the
pcontrol object's outlet.
shroud filename [list] The word shroud, followed by the name of a patcher file, opens that file but does
not show its window. (Use this message with care, since having patchers open but
invisible can potentially lead to some disconcerting results.)

Information for box attributes common to all objects

Output
Patcher-Control: Any subpatches or patcher objects connected to the pcontrol object's outlet can have their patcher window
opened or closed, or MIDI enabled/disabled, when the appropriate message is received in the inlet of pcontrol.

Examples

Show/hide a subpatch window, or enable/disable its MIDI objects

See Also
Name Description
bpatcher Embed a subpatch with a visible UI
inlet Receive messages from outside a patcher
patcher Create a subpatch within a patch
thispatcher Send messages to a patcher
peak
Output larger numbers

Description
Compares a number to a previous peak-value and, if larger, it is sent out the output while the new peak-value is set to that
number.

Arguments
Name Units Type Opt Description
format float opt The initial value stored in peak is 0. Providing a float argument will cause peak to
operate with floating point numbers instead of integers.

Messages
bang Sends the currently stored peak value out the left outlet.
int input [int] In left inlet: If the input is greater than the value currently stored in peak, it is
stored as the new peak value and is sent out.
(inlet1) input [int] In right inlet: The number is stored in peak as the new peak value, and is sent out.
float input [float] In left inlet: If the input is greater than the value currently stored in peak, it is
stored as the new peak value and is sent out.
(inlet1) input [float] In right inlet: The number is stored in peak as the new peak value, and is sent out.
list input [number] In left inlet: The second number is stored as the new peak value and is sent out,
peak [number] then the first number is received in the left inlet.

Information for box attributes common to all objects

Output
int: Out left outlet: New peak values are sent out. (A number received in the right inlet is always the new peak value.)

Out middle outlet: If the number received is a new peak value, the output is 1. If the number received in the left inlet is not a new
peak value, the output is 0.

Out right outlet: If the number received is a new peak value, the output is 0. If the number received in the left inlet is not a new
peak value, the output is 1.

Examples

Find the greatest in a series of numbers... A number in the right inlet always sets a new peak

See Also
Name Description
maximum Output the highest value
past Notify when a threshold is passed
trough Output a number if it is less than previous numbers
> Compare numbers for greater than condition
Max Data Tutorial 2: Data Scaling Max Data Tutorial 2: Data Scaling
pgmin
Receive MIDI program changes

Description
Arguments
Name Units Type Opt Description
port symbol opt Specifies the port (a-z) from which to receive incoming program change messages.
If there is no argument, pgmin receives from all channels on all ports.
device symbol opt The name of a MIDI input device may be used as the first argument to specify the
port.
port-channel list A letter (a-z) and number combination (separated by a space) indicates a port and
a specific MIDI channel on which to receive program change messages. Channel
numbers greater than 16 will be wrapped around to stay within the 1-16 range.
channel int A number alone can be used in place of a letter and number combination. The
exact meaning of the channel number argument depends on the channel offset
specified for each port in the MIDI Setup dialog.

Messages
anything port [list] Performs the same function as port but without need for the word, "port".
(mouse) Double-clicking on a pgmin object shows a pop-up menu for choosing a MIDI
port or device.
(MIDI) The pgmin object receives its input from a MIDI program message received from a
MIDI input device.
port port [symbol] The word port, followed by a letter a-z or the name of a MIDI input port or
device, sets the port from which the object receives incoming program change
messages. The word port is optional and may be omitted.

Information for box attributes common to all objects

Output
int: If a specific channel number is included in the argument, there is only one outlet. The output is the incoming program
number on the specified channel and port. Note: The pgmin object always adds 1 to the incoming program number. Thus, an
incoming program change value of 32 will come out the outlet of pgmin as 33.

If there is no channel number specified by the argument, pgmin will have a second outlet, on the right, which will output the
channel number of the incoming program change message.

Examples

Program changes can be received from everywhere, a specific port, or a specific port and channel
See Also
Name Description
midiin Output raw MIDI data
pgmout Send MIDI program changes
pgmout
Send MIDI program changes

Description
Arguments
Name Units Type Opt Description
port symbol opt Specifies the port for transmitting MIDI program change messages. When a letter
argument is present, channel numbers greater than 16 received in the right inlet
will be wrapped around to stay within the 1-16 range. If there is no argument,
pgmout initially transmits out port a, on MIDI channel 1.
port-channel list A letter and number combination (separated by a space) indicates a port and a
specific MIDI channel on which to transmit program change messages. Channel
numbers greater than 16 will be wrapped around to stay within the 1-16 range.
device symbol opt The name of a MIDI output device may be used as the first argument to specify the
port.
channel int A number alone can be used in place of a letter and number combination. The
exact meaning of the channel number argument depends on the channel offset
specified for each port in the MIDI Setup dialog.

Messages
int input [int] In left inlet: The number has 1 subtracted from it and then is transmitted as a
program change value on the specified channel and port. Numbers are limited
between 1 and 128, and are sent out as program changes 0 to 127.
(inlet1) channel [int] In right inlet: The number is stored as the channel number on which to transmit
the program change messages.
float input [float] Converted to int.
anything port [list] Performs the same function as port but without need for the word, "port".
(mouse) Double-clicking on a pgmout object shows a pop-up menu for choosing a MIDI
port or device.
port port [symbol] The word port, followed by a letter a- z or the name of a MIDI output port or
device, specifies the port used to transmit the MIDI messages. The word port is
optional and may be omitted.
list input [list] In left inlet: The first number is the program number +1, and the second number
is the channel of a MIDI program change message transmitted on the specified
channel and port.

Information for box attributes common to all objects

Output
(MIDI): There are no outlets. The output is a MIDI program change message transmitted directly to the object's MIDI output
port.

Examples
Letter argument transmits to only one port. Otherwise, number specifies both port and channel

See Also
Name Description
midiout Transmit raw MIDI data
pgmin Receive MIDI program changes
pictctrl
Picture-based control

Description
Creating buttons, switches, knobs, and other controls using images from a picture file for its appearance.

Arguments
None.

Messages
bang Sends the current value of the pictctrl to the outlet.
int input [int] Sets the value of the button or knob set by the control, and sends the current value
out the outlet. In button and toggle mode, the value must be either 0 or 1. In dial
mode, the range of values is determined by pictctrl object's Range attribute.
float input [float] Converted to int.
(drag) When a image file is dragged from the Max 5 File Browser to a pictctrl object, the
image will be loaded.
(mouse) Clicking on the pictctrl object and dragging sends the current value out the outlet.
Additional behaviors depend on how the object is configured using messages or
setting attributes using the Inspector.
link filename [symbol] The word link, followed by a filename to a file which has already been loaded into
the pictctrl object will link the object with that file.
picture imagefile-name [list] The word picture followed by the name of an image file will read that file into the
pictctrl object. The word with no name following opens a standard file dialog for
choosing an image file.
set input [int] The word set, followed by a number, sets the value of the button or knob to that
number, without triggering output.
read filename [list] The word read followed by the name of an image file will read that file into the
pictctrl object. The word with no name following opens a standard file dialog for
choosing an image file.
readany filename [list] The word readany followed by the name of a file will read any type of file into the
pictctrl object and attempt to interpret it as a picture.

Attributes
Name Type g/s Description
active int Toggles mouse control of the pictctrl object. The default is 1 (enabled). If a
def.:1 separate set of inactive images is present in the pictctrl object's picture file and if
the inactive images attribute is set, the active message will also change the
appearance of the control.
clickedimage int Toggles the use of an alternate set of image frames in your picture file to give the
def.:0 dial a different appearance when the user clicks on it and drags the mouse pointer.
clickedimage 0 disables this feature.
clickincrement int Sets the output value to increment by 1 each time the object is clicked (Click to
def.:0 Increment mode). Any movement of the mouse after clicking is ignored. When the
uppermost value is reached, the value returns to zero with the next click. All other
mouse tracking modes are disabled. clickincrement 0 disables Click to Increment
mode.
clip int Causes pictctrl, while in dial-mode, to clip mouse-movement within the range of
def.:1 the dial. When followed by a 0, pictctrl will wrap around to the minimum when it
surpasses the maximum value (within the range of the dial) and vice versa to the
maximum when it surpasses the minimum value.
degrees int Specifies the degree-of-rotation pictctrl has while in dial-mode.
def.:270
frames int Specifies the number of images (columns) in the picture file. The number of
def.:10 frames does not have to be the same as the range of the control; the pictctrl object
will use the nearest image for any given value.
imagemask int When non-zero, indicates that your picture file has an image mask. The default is
def.:0 0 (no image mask). This attribute is present for legacy support - it has been
superseded by the use of alpha channels in images.
inactiveimage int When non-zero, indicates that your picture file has an additional row of images for
def.:0 its inactive state. The default is 0 (no inactive state).
mode int Selects mode of operation for the pictctrl object.
def.:0 Button (the default)
Toggle
Dial mode
'Button' = TEXT_HERE
'Toggle' = TEXT_HERE
'Dial' = TEXT_HERE
multiplier int Sets a multiplier value. When pictctrl is in dial mode, the object's value is
def.:0 multiplied by this number before being sent out the outlet. The multiplication
happens before the addition of the Offset value. The default multiplier value is 1.
name symbol Designates the graphics file that the pictctrl object will use will use for the
def.:<default> control's button or dial file. By convention, the pictslider object uses images saved
in Portable Network Graphics (.png) format. If you are using Max on Windows and
want to to work with images other than PNG or PICT files, we recommend that
you install QuickTime and choose a complete install of all optional components.
The symbol used as a filename must either be the name of a file in Max's current
search path, or an absolute pathname for the file (e.g. "MyDisk:/Documents/UI
Pictures/CoolButton.png").
offset int Sets an offset value. When pictctrl is in dial mode, the offset value is added to the
def.:0 object's value before being sent out the outlet. The default offset value is 0.
parameter_enable int Parameter Mode Enable
range int Sets the range of the pictctrl object when it is in dial mode. The default value is
def.:128 128.
ratio int Specifies how many pixels the mouse pointer must move before the value of the
def.:2 dial changes by one increment. If the pictctrl object is using Circular Tracking, the
ratio message specifies how many degrees the cursor must move, relative to the
center of the object, to increase the value by one.
snap int Sets pictctrl to snap to the image's original size. When followed by a 0, pictctrl
def.:0 will not snap to the image's original size.
threshold int Sets the button Alpha hit threshold.
def.:0
trackcircular int Sets the pictctrl object to respond when you click on it and drag the mouse in a
def.:0 circular arc relative to the control's center (Circular Tracking mode). Moving the
mouse clockwise increases the control's value, and moving it counterclockwise
decreases its value. Enabling circular tracking disables all other tracking modes.
trackcircular 0 disables circular tracking.
trackhorizontal int Sets the pictctrl object to respond when you click on it and drag the mouse
def.:0 horizontally; moving the mouse to the right increases the object's value, and
moving it to the left decreases the value. Enabling this mode of operation disables
the Circular Tracking and Click to Increment modes (see the clickincrement and
trackcircular messages).
tracking int Toggles live tracking. If live tracking is on, the pictctrl object will change its state
def.:0 if the mouse moves in and out of the rectangular border of the object with the
mouse button held down. tracking 0 disables live tracking
trackvertical int Sets the pictctrl object to respond when you click on it and drag the mouse
def.:0 vertically; moving the mouse up increases the object's value, and moving it down
decreases the value. Enabling this mode of operation disables the Circular
Tracking and Click to Increment modes (see the clickincrement and trackcircular
messages).

Information about attributes available for Parameter-aware objects

Information for box attributes common to all objects

Picture File Format


Specifications: When you create a new pictctrl object in a patcher window, it has no associated picture file. Use the Open button
in the Inspector to choose a picture file for the control. By convention, the pictctrl object uses images saved in Portable Network
Graphics (.png) format. If you are using Max on Windows and want to to work with images other than PNG or PICT files, we
recommend that you install QuickTime and choose a complete install of all optional components. The layout of the picture in the
file varies depending on which mode of operation the pictctrl uses. All three modes require that the pictures be made up of a grid
of images, in which all images have the same width and height.

Button mode has the simplest layout:

The first row of images is mandatory: these two images are used for the idle and clicked states (values zero and one, respectively)
of the button. The next row of images, if present, is used for the control when it is in its inactive state. The next rows contain the
masks for the top row of images, and the inactive images if present.

Toggle mode has a similar layout:

In this mode, the top two rows are mandatory. The first row of images are used when the control's value is zero, the next row
when its value is one. The third row is optional; it is used for the control when it is in its inactive state. (Note that there are no
"clicked" images for the inactive state, since when inactive, the control ignores mouse clicks.) The next rows contain masks for
the images.

The Dial mode layout varies in size depending on how many image frames it has, which must be the same as the Image Frames
parameter as set in the inspector:

The first row of images is mandatory: one image for each visually distinct state of the control. Dials need as many picts as you
wish them to have visible states. Note that dials can receive and send a larger range of values than are represented by picts (e.g.
your dial can have a range of 128 even if you only use eight pict frames to represent the range of the dial). The next row of images
is optional, and is used when the user is clicking and dragging on the object to change its value. The next row is also optional;
(Note that there are no "clicked" images for the inactive state, since when inactive, the control ignores mouse clicks.) The
following rows contain masks for the images.

Output
int: The current value of the pictctrl object. In toggle and button modes this will be a 0 or a 1. In dial mode, this value is specified
by the range, offset, and multiplier that you set in the Inspector window.

Examples
Create customized controls to create a more attractive user interface

See Also
Name Description
dial Output numbers using an onscreen dial
kslider Output numbers from an onscreen keyboard
matrixctrl Matrix switch control
pictslider Picture-based slider control
rslider Display or change a range of numbers
slider Move a slider to output values
tab Select values with tabs or multiple buttons
textbutton A user interface button/toggle
ubutton Send a bang with a transparent button
Max Interface Tutorial 2: Picture Max Interface Tutorial 2: Picture UI Elements
UI Elements
pictslider
Picture-based slider control

Description
A slider control that uses pictures in external files for its appearance. It uses two pictures--one for the "knob" and one for the
background over which the knob moves. The pictslider object has default pictures that are used if you do not want to supply
pictures of your own, but its intended use is creating controls with customized appearances.

Arguments
None.

Messages
bang In left inlet: Sends the current values of the pictslider to its outlets. The horizontal
value is sent out the left outlet; the vertical value out its right outlet.
int input [int] In left inlet: sets the pictslider object's horizontal value. The value is also sent out
the left outlet, and the pictslider object's current vertical value is sent out the right
outlet.

In right inlet: sets the pictslider object's vertical value. The value is also sent out
the right outlet, and the control's current horizontal value is sent out the left outlet.
float input [float] Converted to int.
list horizontal [int] In left inlet: A list of two numbers sent to the left inlet sets the pictslider object's
vertical [int] horizontal value to the first number and its vertical value to the second. The two
values are sent out the left and right outlets.
bkgndpicture filename [list] The word bkgndpicture, followed by a symbol that specifies a filename,
designates the graphics file that the pictslider object will use for the control's
background image. By convention, the pictslider object uses images saved in
Portable Network Graphics (.png) format. If you are using Max on Windows and
want to to work with images other than PNG or PICT files, we recommend that
you install QuickTime and choose a complete install of all optional components.
The symbol used as a filename must either be the name of a file in Max's current
search path, or an absolute pathname for the file (e.g. "MyDisk:/Documents/UI
Pictures/CoolBkgnd.png").
(drag) When a image file is dragged from the Max 5 File Browser to a pictslider object,
the image will be loaded as the object's background image.
knobpicture filename [list] In left inlet: The word knobpicture, followed by a symbol that specifies a
filename, designates the graphics file that the pictslider object will use for the
control's knob file. The symbol used as a filename must either be the name of a file
in Max's current search path, or an absolute pathname for the file (e.g.
"MyDisk:/Documents/UI Pictures/CoolKnob.png"). The word knobpicture by
itself puts up a standard Open Document dialog box.
(mouse) Clicking on the pictctrl object and dragging sends the current value out the outlet.
Additional behaviors depend on how the object is configured using messages or
setting attributes.
set horizontal [int] In left inlet: The word set, followed by a number, sets the pictcslider object's
vertical [int] horizontal value but does not send the value out its left outlet.The word set,
followed by two numbers, sets the pictslider object's horizontal value to the first
number and its vertical value to the to the second number, but does not send the
values out its outlets.

In right inlet: The word set, followed by a number, sets the pictslider object's
vertical value, but does not send the value out its right outlet.
readanybkgnd filename [list] The word readanybkgnd followed by the name of a file will read any type of file
into the pictslider object and attempt to interpret it as a background image.
readanyknob filename [list] The word readanyknob followed by the name of a file will read any type of file
into the pictslider object and attempt to interpret it as a knob image.
track ratio [float] In left inlet: The word track, followed by a float, sets the tracking ratio for
horizontal movements of the pictslider object's knob.

In right inlet: The word track, followed by a float, sets the tracking ratio for
vertical movements of the pictslider object's knob.

Attributes
Name Type g/s Description
active int Toggles mouse control of the pictslider object. The default is 1 (enabled). If a
def.:1 separate set of inactive images is present in the pictslider object's graphics file and
if the inactive images attribute is set, the active message will also change the
appearance of the control.
bkgnddrag int Toggles background drag mode for the pictslider object. When this mode is
def.:0 enabled, clicking and dragging anywhere in the background area of the slider will
move the knob; the knob will move relative to the motion of the mouse, just as if
you had clicked in the knob itself. The message bkgnddrag 0 disables this mode.
You must also uncheck the KnobJumps to Click Location checkbox in the
pictslider object's Inspector or send the object a jump 0 message to enable this
mode.
bkgndpict symbol Designates the graphics file that the pictslider object will use for the control's
def.:<default> background image. The symbol used as a filename must either be the name of a
file in Max's current search path, or an absolute pathname for the file (e.g.
"MyDisk:/Documents/UI Pictures/CoolBkgnd.png").
bkgndsize int Sets the pictslider object to change the size of the object to match the size of the
def.:0 background picture. After receiving this message, the object's size cannot be
changed. bkgndsize 0 allows the control to be resized in the usual manner by
dragging its lower-right corner.
bottommargin int Sets the bottom margin, in pixels, for the pictslider. The margin reduces the area
def.:0 in which the knob moves; if a margin is zero, the knob can move all the way to the
bottom of the slider.
bottomvalue int Sets the values emitted by the pictslider object when the knob is moved as far as
def.:0 possible to the bottom. The message bottomvalue 100 will cause the control to
send 100 out of its left outlet when the knob is moved all the way to the bottom.
clickedimage int Specifies that the graphics file used by the pictslider object contains an additional
def.:1 image to be displayed when the control is clicked.
horizontaltracking float Sets the horizontal tracking ratio for movements of the pictslider object's knob.
def.:1. The default value is 1.0. Values greater than one cause the knob to move more
quickly when dragged; values less than one cause it to move more slowly.
imagemask int When set to 1, specifies that the graphics file used by the pictslider object contains
def.:0 image masks. This attribute is present for legacy support - it has been superseded
by the use of alpha channels in images.
inactiveimage int When set to non-zero, specifies that the graphics file used by the pictslider object
def.:1 contains additional images for the object's inactive state.
invisiblebkgnd int When set to non-zero, the pictslider object will not draw any background image.
def.:0 The knob will appear to float above any objects underneath it.
jump int When set to non-zero, makes pictslider move the knob to the position of the
def.:1 cursor if you click in the object outside of the knob. jump 0 disables this behavior;
you must click in the knob itself to move it.
knobpict symbol Designates the graphics file that the pictslider object will use for the control's
def.:<default> knob image. By convention, the pictslider object uses images saved in Portable
Network Graphics (.png) format. If you are using Max on Windows and want to to
work with images other than PNG or PICT files, we recommend that you install
QuickTime and choose a complete install of all optional components. The symbol
used as a filename must either be the name of a file in Max's current search path,
or an absolute pathname for the file (e.g. "MyDisk:/Documents/UI
Pictures/CoolKnob.png").
leftmargin int Sets the left margin, in pixels, for the pictslider. The margin reduces the area in
def.:0 which the knob moves; if a margin is zero, the knob can move all the way to the
left of the slider.
leftvalue int Sets the values emitted by the pictslider object when the knob is moved as far as
def.:0 possible to the left. The message leftvalue 100 will cause the control to send 100
out of its left outlet when the knob is moved all the way to the left.
movehorizontal int When set to non-zero, allows the knob to change when the mouse is moved
def.:1 horizontally. The message movehorizontal 0 prevents the knob from moving
when the mouse is moved horizontally.
movevertical int When set to non-zero, allows the knob to change when the mouse is moved
def.:1 vertically. The message movevertical 0 prevents the knob from moving when the
mouse is moved vertically.
parameter_enable int Parameter Mode Enable
rightmargin int Sets the right margin, in pixels, for the pictslider. The margin reduces the area in
def.:0 which the knob moves; if a margin is zero, the knob can move all the way to the
right of the slider.
rightvalue int Sets the values emitted by the pictslider object when the knob is moved as far as
def.:127 possible to the right. The message rightvalue 100 will cause the control to send
100 out of its left outlet when the knob is moved all the way to the right.
scaleknob int When set to non-zero, tells the pictslider object to stretch or shrink the knob
def.:0 when you change the size of the entire object. scaleknob 0 will result in the knob
always being drawn at its original size.
topmargin int Sets the top margin, in pixels, for the pictslider. The margin reduces the area in
def.:0 which the knob moves; if a margin is zero, the knob can move all the way to the
top of the slider.
topvalue int Sets the values emitted by the pictslider object when the knob is moved as far as
def.:127 possible to the top. The message topvalue 100 will cause the control to send 100
out of its left outlet when the knob is moved all the way to the top.
verticaltracking float Sets the vertical tracking ratio for movements of the pictslider object's knob. The
def.:1. default value is 1.0. Values greater than one cause the knob to move more quickly
when dragged; values less than one cause it to move more slowly.

Information about attributes available for Parameter-aware objects

Information for box attributes common to all objects

Picture File Format


Specifications: The pictslider object uses the two picture files: one for the background, and one for the knob that is moved over
the background with the mouse.

Background picture files can be in PICT format, or if QuickTime Version 3.0 or later is installed, one of the other graphics file
formats listed in the QuickTime appendix. Background picture files must have the following layout:

Only one image is required; if only one image is supplied, it will be used for drawing all states of the background. Additional
images are placed to the right of the first image. You can add images for the inactive state of the control. The inactive image will
be used after the control has received an active 0 message.

Knob files must be in PICT format with the following layout:


The picture is made up of a grid of one or more images. All images have the same width and height.

Only one image is required; if only one image is supplied, it will be used for drawing all states of the knob. Additional images are
placed to the right of the first image. You can add images for either or both the "clicked" or inactive states of the control. The
"clicked" image will be shown when the user is dragging the control's knob. The inactive image will be used after the control has
received an active 0 message.

Image masks can be used to create knobs with non-rectangular outlines. These masks are directly below their corresponding
images in the picture file. If you wish to use masks for any of the knob images, you must provide masks for all of them--each
image will have a corresponding row of masks. Black pixels in the mask image create areas of the corresponding image that will
be drawn, and white pixels create invisible areas.

Output
int: Moving the slider's knob by clicking and dragging it with the mouse, or sending values to either of its inlets, causes its
horizontal value to be emitted from the left outlet and its vertical value to be emitted from the right outlet. Incoming values are
constrained to the ranges determined by the top/bottom and left/right values set in the inspector.

Examples

pictslider lets you create both one- and two-dimensional UI elements

See Also
Name Description
dial Output numbers using an onscreen dial
kslider Output numbers from an onscreen keyboard
multislider Display data as sliders or a scrolling display
nslider Output numbers from a notation display
pictctrl Picture-based control
rslider Display or change a range of numbers
slider Move a slider to output values
tab Select values with tabs or multiple buttons
textbutton A user interface button/toggle
ubutton Send a bang with a transparent button
Max Basic Tutorial 14: Max Basic Tutorial 14: Encapsulation
Encapsulation
Max Interface Tutorial 2: Picture Max Interface Tutorial 2: Picture UI Elements
UI Elements
pipe
Delay numbers, lists or symbols

Description
Delays numbers, lists of numbers or symbols. pipe uses the Max time format syntax, so the delay interval can be either fixed or
tempo-relative.

Arguments
Name Units Type Opt Description
initialization list opt The number of arguments to the pipe object depends on the number of items in a
list you wish to delay, but the final argument is always used to set the initial value
for the delay time.

If no argument is specified, the initial value is 0 and the delay time is 0 ms.

If there is one argument, this sets the delay time.

If there are two arguments, the first argument sets an initial value to be stored in
pipe, and the second argument sets the delay time.

If more than two arguments are present, pipe creates additional inlets and outlets
for delaying additional numbers.

The pipe object allows you to specify time intervals using either a number which
specifies time in milliseconds (e.g. pipe 200) or a notevalue (e.g. pipe 2n).

Note: While the pipe object lets you specify time in any of Max's standard time
formats, the interval attribute argument should be used when specifying time in
any other time unit besides milliseconds or notevalues (e.g. pipe @ interval 11025
samples ).

If notevalue, ticks, or bars.beats.units are specified for the delay interval, the
object will not operate unless the transport is running.

Messages
bang Re-triggers the numbers currently stored in the pipe to be output again after the
specified time (in addition to any numbers already being delayed).
int delay [int] In left inlet: Sets value and triggers delay

In middle inlets: Sets value without triggering delay

In right inlet: Sets the delay time


float delay [float] Float is converted to int unless the inlet was initialized with a float argument.

In left inlet: Sets value and triggers delay

In middle inlets: Sets value without triggering delay

In right inlet: Sets the delay time


list In left inlet: For each character provided, a value will be set for each
corresponding input and triggers a delay.

In middle inlets: The middle inlets of pipe use the first character and set the
stored value for the input inlet.
In right inlet: Specify time in one of the Max time formats.
anything See the list listing
clear Halts all output
flush Immediately sends out all values currently being delayed by pipe, and clears the
pipe object's memory. Values are sent out each outlet in reverse order from that
in which they were received in the corresponding inlet.
stop Halts all output

Attributes
Name Type g/s Description
clock symbol Use the clock attribute to specify a named setclock object for timing rather than
by Maxs internal millisecond clock. The word clock by itself sets the pipe object
back to using Maxs regular millisecond clock.
delaytime atom Sets the delay time for this object using any of Max's time formats
quantize atom Quantizes the output of pipe to a specified time-boundary. This is achieved by
making internal adjustments to the times used for sending output. The
quantization can be specified in the following time formats: bars.beats.units, ticks
or note values.

Fixed time units (for example: ms, seconds, hz, samples, etc.) will have no effect.

Information for box attributes common to all objects

Output
int: When a value is received in the pipe object's left inlet, it is delayed by the time specified, then sent out the left outlet. If there
are middle inlets, the values in those inlets are also delayed and sent out their corresponding outlet, in response to a value is
received in the left inlet. Unlike delay, more than one value at a time can be delayed in a pipe. When a new delay time is
received in the right inlet, it does not affect when the values already being delayed by pipe will come out.

Examples

One or more numbers can be delayed with pipe

See Also
Name Description
delay Delay a bang
Max Basic Tutorial 19: Timing Max Basic Tutorial 19: Timing
playbar
Movie/SoundFiles controller

Description
Interacts with movie, imovie, sfplay~ or jit.qt.movie to control the playback, position and looping of the media

Arguments
None.

Messages
bang If the left outlet of a playbar object is connected to a movie or imovie object,
bang links the two objects together so the playbar can control the QuickTime
movie. After playbar and movie are linked, any messages sent to the movie object
which change its location or playing status are reflected in the playbar object.
(Linking will happen automatically when a patcher file containing connected
playbar and movie objects is loaded. Thus, sending the bang to playbar is only
necessary when you're building a patch.)
(mouse) Clicking and dragging with the mouse can be used to start/stop a movie,
rewind/fast-forward it, or to select a particular point in the movie.
loop flag [int] The word loop followed by a non-zero number will turn looping on; loop followed
by a 0 will turn looping off.
palindrome flag [int] The word palindrome followed by a non-zero number will turn palindrome-
playback on (loop forward and backwards); palindrome followed by a 0 will turn
palindrome-playback off. Looping must be turned on for palindrome-playback.
Note: the palindrome mode of playback does not work with the sfplay~ object.

Attributes
Name Type g/s Description
hideloop int Hide Loop
def.:0
hiderwff int Hide the rewind/forward controls
def.:0

Information for box attributes common to all objects

Output
(internal): Out left outlet: Once the playbar and a movie object are linked, the playbar controls the QuickTime movie. playbar
only supports being connected to one movie object at a time. The connection must be made with a patch cord; it cannot take
place via a send- receive pair.
int: Out right outlet: Each command processed by playbar is sent by number out its right outlet. A directory of command
numbers and their meaning can be found in the QuickTime Standard Movie Play Controller documentation. By properly
interpreting these commands, you can potentially use playbar for other purposes besides movie control. However, the "thumb"
in the controller has no range until an associated QuickTime movie with a non-zero duration is linked to the playbar.

Examples
Using playbar with movie and imovie

See Also
Name Description
movie Play a QuickTime movie in a window
imovie Play a movie in a patcher window
+
Add two numbers, output the result

Description
Arguments
Name Units Type Opt Description
initial int or float opt Sets the initial value, to be added to a number received in the left inlet. A float
argument causes the numbers to be added as floats.

Messages
bang In left inlet: Performs the addition with the numbers currently stored. If there is
no argument, + initially holds 0.
int input [int] The number is added to the number in the right inlet, and the result is sent out the
outlet.
(inlet1) value-added-to [int] The number is stored for addition to a number received in the left inlet.
float input [float] Converted to int, unless + has a float argument.
set set-input [int] In left inlet: The word set, followed by a number, adds that number to the number
in the right inlet but nothing is sent out. A subsequent bang sends out the result.
list input [list] In left inlet: The first number is added to the second number, and the result is sent
out the outlet.

Information for box attributes common to all objects

Output
float: Only if there is an argument with a decimal point.
int: The sum of the two numbers received in the inlets.

Examples

Normally adds ints... Floats are truncated before addition... unless there is a float argument

See Also
Name Description
expr Evaluate a mathematical expression
Max Basic Tutorial 6: Simple Max Basic Tutorial 6: Simple Math in Max
Math in Max
poltocar
Convert polar to cartesian coordinates

Description
Converts a polar-coordinate pair consisting of distance and angle values into a cartesian-coordinate pair consisting of real and
imaginary values.

Arguments
None.

Messages
bang Causes poltocar to output the very last conversion it has calculated.
int coordinate [int] Converted to float.
float coordinate [float] In left inlet: The distance portion of a polar coordinate pair to be converted into a
Cartesian coordinate pair consisting of real and imaginary values. When used in
an audio context, the value represents magnitude (amplitude) portion of a polar
coordinate pair to be converted into a cartesian (real/imaginary) coordinate pair.

In right inlet: The angle portion of a polar coordinate pair to be converted into a
Cartesian coordinate pair consisting of real and imaginary values. When used in
an audio context, the value represents the phase portion of a polar coordinate pair
to be converted into a cartesian (real/imaginary) coordinate pair.

Information for box attributes common to all objects

Output
float: Out left outlet: The real portion of a Cartesian coordinate pair.

Out right outlet: The imaginary portion of a Cartesian coordinate pair.

Examples

Convert Polar to Cartesian coordinates

See Also
Name Description
cos Cosine function
cartopol Convert cartesian to polar coordinates
lcd Draw graphics in a patcher window
sin Sine function
poly
Allocate notes to different voices

Description
Provides polyphonic voice-allocation by allocating data to different individual voices.

Arguments
Name Units Type Opt Description
voices number opt Sets the number of voices to which poly can allocate notes (thus limiting the
number of notes poly can hold at one time). If there is no argument present, poly
will hold up to 16 notes.
steal-mode float opt If there is no second argument, or if the second argument is 0, poly sends any
notes it cannot hold out the rightmost outlet. If there is a non=zero second
argument, poly steals voices: when poly receives more notes than it has voices, it
turns off the note it has held the longest and puts the new note in its place.

Messages
int pitch [int] The number is treated as the pitch value of pitch-velocity pair and the note is sent
out.
(inlet1) velocity [int] The number is stored as the velocity to be paired with numbers received in the left
inlet.
stop In left inlet: Immediately sends note-offs for all the notes currently being held by
poly, freeing all voices.

Information for box attributes common to all objects

Output
int: Out left outlet: The output is the voice number of the note-on or note-off being sent out.

Out 2nd outlet: The output is the pitch of the note-on or note-off.

Out 3rd outlet: The number is the velocity of the note-on or note-off.
list: Out 4th outlet: The first number is the pitch, and the second number is the velocity, of any notes poly cannot hold. If there is
a non-zero second argument, poly steals voices rather than send out overflow, so the fourth outlet is not created.

Examples

Send each voice to a different place... Limit the number of notes held at a time

See Also
Name Description
borax Report note-on and note-off information
flush Output MIDI note-offs for held notes
makenote Generate a note-on/note-off pair
polyin
Received MIDI poly pressure

Description
Arguments
Name Units Type Opt Description
port symbol opt Specifies the port from which to receive incoming MIDI messages. If there is no
argument, polyin receives from all channels on all ports.
device symbol opt The name of a MIDI input device may be used as the first argument to specify the
port.
port-channel list A letter and number combination (separated by a space) indicates a port and a
specific MIDI channel on which to receive polyphonic key pressure messages.
Channel numbers greater than 16 will be wrapped around to stay within the 1-16
range.
channel int A number alone can be used in place of a letter and number combination. The
exact meaning of the channel number argument depends on the channel offset
specified for each port in the MIDI Setup dialog.

Messages
anything MIDI-input-port (a through Performs the same function as port but without need for the word, "port".
z) [list]
(mouse) Double-clicking on a polyin object shows a pop-up menu for choosing a MIDI port
or device.
(MIDI) The polyin object receives its input from a MIDI poly pressure message received
from a MIDI input device.
port port [symbol] The word port, followed by a letter a-z or the name of a MIDI input port or
device, sets the port from which the object receives incoming program change
messages. The word port is optional and may be omitted.

Information for box attributes common to all objects

Output
int: Out left outlet: The number is the pressure value of the incoming polyphonic key pressure message.

Out 2nd outlet: The number is the pitch value (key number) of the incoming message.

If a specific channel number is included in the argument, there are only two outlets. If there is no channel number specified by
the argument, polyin will have a third outlet, on the right, which will output the channel number of the incoming note-on
message.

Examples

Messages can be received from everywhere, a specific port, or a specific port and channel

See Also
Name Description
midiin Output raw MIDI data
polyout Send MIDI poly pressure
polyout
Send MIDI poly pressure

Description
Arguments
Name Units Type Opt Description
port symbol opt Specifies the port for transmitting MIDI program change messages. When a letter
argument is present, channel numbers greater than 16 received in the right inlet
will be wrapped around to stay within the 1-16 range. If there is no argument,
polyout initially transmits out port a, on MIDI channel 1.
port-channel list A letter and number combination (separated by a space) indicates a port and a
specific MIDI channel on which to transmit program change messages. Channel
numbers greater than 16 will be wrapped around to stay within the 1-16 range.
device symbol opt The name of a MIDI output device may be used as the first argument to specify the
port.
channel int A number alone can be used in place of a letter and number combination. The
exact meaning of the channel number argument depends on the channel offset
specified for each port in the MIDI Setup dialog.

Messages
int input [int] In left inlet: The number has 1 subtracted from it and then is transmitted as a poly
pressure value on the specified channel and port. Numbers are limited between 1
and 128, and are sent out as poly pressure values of 0 to 127.
(inlet1) key [int] In middle inlet: The number is stored as the key number, to be used with pressure
values received in the left inlet. Numbers are limited between 0 and 127.
(inlet2) channel [int] In right inlet: The number is stored as the channel number on which to transmit
the program change messages.
float input [float] Converted to int.
anything port [list] Performs the same function as port but without need for the word, "port".
(mouse) Double-clicking on a polyout object shows a pop-up menu for choosing a MIDI
port or device.
port port [symbol] The word port, followed by a letter a- z or the name of a MIDI output port or
device, specifies the port used to transmit the MIDI messages. The word port is
optional and may be omitted.
list value [int] In left inlet: The first number is the pressure value, the second number is the key
key [int] number, and the third number is the channel, of a transmitted MIDI polyphonic
channel [int] key pressure message.

Information for box attributes common to all objects

Output
(MIDI): There are no outlets. The output is a MIDI polyphonic key pressure message transmitted directly to the object's MIDI
output port.

Examples
Letter argument transmits to only one port... Otherwise, number specifies both port and channel

See Also
Name Description
midiout Transmit raw MIDI data
polyin Received MIDI poly pressure
pow
Computes input to the nth power

Description
Raises the base value (set in the left inlet) to the power of the exponent (set in the right inlet).

Arguments
Name Units Type Opt Description
exponent float or int opt Sets the exponent value. The default value is 0.

Messages
bang Causes pow to output the most recent value it has calculated.
int input [int] In left inlet: Sets the exponent.
In right inlet: Sets the base value.
float input [float] In left inlet: Sets the exponent.
In right inlet: Sets the base value.
(inlet1) exponent [float] Sets the exponent.
list base [number] A list consisting of the base-value followed by the exponent-value will cause pow
exponent [number] to output the base-value raised to the power of the exponent.

Information for box attributes common to all objects

Output
float: The base value (from the left inlet) raised to the exponent (from the right inlet).

Examples

pow will give you a square deal (and other numbers, too)

See Also
Name Description
expr Evaluate a mathematical expression
>> Bit shift to the right
<< Bit shift to the left
prepend
Add a message in front of input

Description
Prepends any input messages with a stored message.

Arguments
Name Units Type Opt Description
message symbol Sets the message to be prepended at the beginning of incoming messages. The first
argument must be a symbol.

Messages
bang The message stored in prepend is attached to the beginning of the message
received in the inlet, and the combined message is sent out its outlet followed by
the word "bang").
int input [int] The integer stored in prepend is attached to the beginning of the message
received in the inlet, and the combined message is sent out its outlet.
float input [float] The float stored in prepend is attached to the beginning of the message received
in the inlet, and the combined message is sent out its outlet.
list input [list] The list stored in prepend is attached to the beginning of the message received in
the inlet, and the combined message is sent out its outlet.
anything input [list] The message stored in prepend is attached to the beginning of the message
received in the inlet, and the combined message is sent out its outlet.
set message [list] The word set, followed by any message, will replace the message stored in
prepend, without triggering output.

Information for box attributes common to all objects

Output
anything: The message received in the inlet is combined with the message stored in prepend, and then sent out the outlet. The
maximum allowed length of any constructed message is 256 items.

Examples

Symbols can be combined into meaningful messages with prepend

See Also
Name Description
append Append arguments to the end of a message
message Send any message
route Select outlet based on input matching
preset
Store and recall settings

Description
preset can store and recall the parameters of any specified user interface objects at the click of a mouse. It can also be used as a
user interface link to a named pattrstorage object.

Arguments
None.

Messages
bang Sends out the settings of the preset that was most recently recalled with an int or a
mouse click.
int slotnumber [int] Sending any integer will trigger the preset of the same number.
float preset-number [float] Converted to int.
list See the bang listing.
clear slotnumber [int] Erases the contents of the most recently sent preset. The word clear, followed by a
number, erases the contents of that numbered preset.
clearall Erases the contents of all presets.
(mouse) Clicking on a button in the preset object will recall a stored preset.

Shift-clicking on a button in the preset object will store a preset.


name ID [symbol] The word name, followed by a symbol, sets the ID Name for the preset. The ID
Name allows the preset to have a unique ID so that files created for it will not read
into other presets.
store slotnumber [int] The word store, followed by a number, stores the current setting of all user
interface objects in the same window in the preset indicated by the number. If
objects are connected to the preset object's left outlet with patch cords, only those
connected objects will be affected.

The presets (storage locations in the preset object) are numbered left-to-right,
top-to-bottom. When settings are stored in a preset, the dot's color changes to
indicate that it contains something. Settings can also be stored in a preset by
holding down the Shift key and clicking on the preset with the mouse.
read filename [symbol] The word read, followed by no arguments or a number, displays an Open
slotnumber [int] Document dialog box for choosing a file of preset data to read. If the preset has
been given a Preset Name Code, only files of the type specified by the code will be
displayed. The number argument specifies the preset number into which the file
data should be read. If the number is 0 or -1, the data in the file will be read into
the number of presets contained in the file starting with the first one. If the word
read is followed by a symbol or a number and a symbol, no dialog box is
displayed. Instead, the symbol is taken as a filename from which to read presets.
The number functions as previously described.
write filename [symbol] The word write, followed by no arguments or a number, displays a Save As dialog
slotnumber [int] box for specifying a destination filename for writing the preset data. If the preset
has been given a Preset Name Code, the file is given this code as its file type. The
number argument specifies the preset number from which the preset data should
be written. If the number is 0 or -1, all presets will be written. If the word write is
followed by a symbol or a number and a symbol, no dialog box is displayed.
Instead, the symbol is taken as a filename to use for writing the data, and the file
will be placed in the current default folder. The number functions as previously
described.

Attributes
Name Type g/s Description
active1 float Sets the first (upper) gradient color for active presets in RGBA format.
active2 float Sets the second (lower) gradient color for active presets in RGBA format.
bgcolor float Sets the background color in RGBA format.
bordercolor float Sets the border color in RGBA format.
bubblesize int Sets the size of the preset "bubble", in pixels. A bubble must be larger than 2
def.:9 pixels.
circlecolor float Sets the color used for the circle displayed when the mouse is over a preset button
in RGBA format.
clicked1 float Sets the first (upper) gradient color for the clicked preset in RGBA format.
clicked2 float Sets the second (lower) gradient color for the clicked preset in RGBA format.
embed int Toggles the ability to save your presets as part of the main patch (The default
def.:1 behavior is 0 (don't save).
emptycolor float Sets the color for empty preset locations in RGBA format.
margin int Sets the edge spacing in pixels, for the preset object's panel
def.:3
pattrstorage symbol the pattrstorage attribute takes as its argument the name of a pattrstorage
object and sets the preset object to allow its use as a user interface object for the
named pattrstorage object's contents.
showtrack int Toggles the display of preset numbers on mouse-over. The default setting is 1 (on).
def.:1
If a preset object is linked to a pattrstorage object whose presets are identified
using the slotname message, the slot name for the corresponding pattrstorage
slot will be displayed on mouseover.
spacing int Sets the spacing, in pixels, between bubbles
def.:3
stored1 float Sets the first (upper) gradient color for stored presets in RGBA format.
stored2 float Sets the second (lower) gradient color for stored presets in RGBA format.
textcolor float Sets the color of the text (number) displayed on mouseover in RGBA format.

Information for box attributes common to all objects

Output
(internal): Any user interface objects connected to the third outlet of preset will be excluded from the effects of that preset.
(This is particularly useful when there are many objects you want to affect with preset, and only a few you want to exclude.)

Objects whose data is stored in a preset include almost all user interface objects. Although an itable object will get stored and
recalled, a table object must be connected to the preset object's outlet with a patch cord. The outlet of preset can also be
connected to a send object, to communicate with objects connected to a receive object of the same name.

The number of visible presets can be adjusted by resizing the preset object's box. The maximum number of presets in a single
preset object is 2048.
int: Out second outlet: When a preset is recalled, the number of the preset is sent out.
int: Out fourth outlet: When a preset is stored, the number of the preset is sent out.
int or float: Out left outlet: When a preset is recalled, either by a mouse click or by a number in the inlet, the settings stored in
that preset are sent out the outlet to all connected objects, or, if no objects are connected, to all user interface objects in the
window.

Examples
Remember many past settings and recall them later

See Also
Name Description
grab Intercept the output of another object
Max pattr Tutorial 1: Patcher Max pattr Tutorial 1: Patcher Storage
Storage
print
Print any message in the max window

Description
print will print any input into the Max window for debugging, messaging, or analysis purposes.

Arguments
Name Units Type Opt Description
identifier anything opt The argument is an identifier for the print object. Each message printed in the
Max window is preceded by the name of the print object. The name can be either a
number or a word. If there is no argument, the name of the print object is print.
Using an argument to print can help distinguish the output of two or more print
objects.

Messages
bang Performs the same function as anything.
int input [int] Performs the same function as anything.
float input [float] Performs the same function as anything.
list input [list] Performs the same function as anything.
anything input [list] Messages are not interpreted by the print object. They are simply printed
verbatim in the Max window.
(mouse) Double-clicking on any print object opens the Max window or brings it to the
front.

Attributes
Name Type g/s Description
popup int Popup When Message Received
def.:0

Information for box attributes common to all objects

Output
anything: There are no outlets. The message received in the inlet is printed in the Max window.

Examples

Used for displaying output, or for notifying when an event takes place

See Also
Name Description
Max Basic Tutorial 1: Hello Max Basic Tutorial 1: Hello
Max Basic Tutorial 2: Bang! Max Basic Tutorial 2: Bang!
prob
Create a weighted transition table

Description
Creates a table of weighted numeric transitions. A bang message causes the weighting, and a potential transition, to be calculated.

Arguments
None.

Messages
bang Makes a weighted random choice of a number to be sent out, based on the
immediately previous output and on the specified likelihoods of subsequent
numbers. No output will be produced if no input has been received or if the
contents of the prob object have been cleared using the clear message.
int input [int] Sets (but does not send out) out the current number value. The subsequent output,
in response to a bang message, will be determined by the stored matrix of
probable transitions from that number.
list matrix [list] The numbers make an entry in a probability matrix of transitions from one
number to another (known as a first-order Markov chain). The list should consist
of three numbers: a current value, a next value, and a probability that current will
be followed by next. The first two numbers in the list identify a possible succession
of output values: a possibility that the first number will be followed by the second.
The third number sets the relative likelihood that the sequence of numbers will
occur. Once the first number has been sent out, the next output is determined by
the relative likelihood(s) assigned to each possible subsequent number.
clear Erases the contents of the prob object.
embed flag [int] The word embed, followed by a non-zero number, causes the contents of prob to
be saved as part of the patch that contains it. The message embed 0 causes prob
to forget its contents when the patch is closed.
dump Prints out a complete list of the stored transition probabilities (Markov chain) in
the Max window.
reset value [int] The word reset, followed by a number, tells prob what number to revert to in the
event that it gets "stuck" on a number that has no possible next number.

Information for box attributes common to all objects

Output
bang: Out right outlet: If the current number (the last number chosen) has no possible transitions listed in the transition
probability matrix, bang is sent out (and nothing is sent out the left outlet) in response to a bang in the inlet.
int: Out left outlet: When bang is received in the inlet, prob sends out a number, which it chooses based on its knowledge of the
last number chosen and the relative likelihood assigned to each possible subsequent number.

Examples
Likelihood of a certain output depends on the previous output

See Also
Name Description
anal Make a histogram of number pairs
histo Create a histogram of numbers received
mean Calculate a running average
Max Data Tutorial 5: List Max Data Tutorial 5: List Processing
Processing
pv
Share data within a patch hierarchy

Description
Creates a value that is shared between objects, but only within a single patcher. Unlike the value object, pv objects that share the
same name only share the same value if they are in the same patcher, or one of its subpatches.

Arguments
Name Units Type Opt Description
name symbol Obligatory. The first argument provides an identifying name. All pv objects with
that name within the patcher will share the same value.
message symbol opt Any message typed in after the first argument initializes the stored contents of the
pv object. Note that when two or more pv objects in a patcher file that share the
same name are initialized to different values, the one which is initialized last
determines the value. Since the order in which pv objects will be initialized cannot
be precisely determined, the best practice is to initialize only one of the related pv
objects.

Messages
bang Sends out the stored message.
int input [int] Performs the same as the anything message.
float input [float] Performs the same as the anything message.
list input [list] Performs the same as the anything message.
anything input [list] The message is stored, to be shared by all other pv objects of the same name that
are inside the object's patcher or its subpatches (or, if in a subpatch, its parent
patch). A message received in any other such pv object will change the stored
message.
status Posts information about the communications between all pv objects involved in
the patcher.
symbol input [symbol] Performs the same as the anything message.

Information for box attributes common to all objects

Output
any message: When bang is received in the inlet, the stored message is sent out.

Examples

See Also
Name Description
float Store a decimal number
int Store an integer value
pvar Connect to a named object in a patcher
receive Receive messages without patch cords
send Send messages without patch cords
value Share a number with other objects
pvar
Connect to a named object in a patcher

Description
The pvar object lets you build user interfaces in one part of your patcher that are associated with the "process" part in another
part of the patcher. Unlike the send and receive objects, pvar does not work globally; the pvar object and its associated object
must be in the same patcher. You set an object's name by selecting the object and choosing Name... from the Object menu. The
name cannot be a number, although it can contain numbers.

Arguments
Name Units Type Opt Description
object-name symbol opt The first argument specifies the name of the object to which pvar will be
associated with. If no name is supplied, the setname message can be used to
connect later.
number-of-outlets int opt The second argument specifies the number of outlets pvar will have. pvar connects
to as many outlets as its associated object has, unless it is more than the number
you specify as an argument. The default number of outlets is 1.

Messages
bang Performs the same function as anything.
int input-message [int] Performs the same function as anything.
float input-message [float] Performs the same function as anything.
list input-message [list] Performs the same function as anything.
anything input-message [list] The message is sent to the named object currently associated with pvar.
loadbang Performs the same function as anything.
setname object-name [symbol] The word setname, followed by a symbol, specifies the name of the object to
which pvar will be associated with. The named object must be in the same patcher
as the pvar object.

Information for box attributes common to all objects

Output
any message: The outlets of pvar correspond to the outlets of its associated named object. When the named object sends
anything out one of its outlets, the output also comes out of the corresponding outlets of the pvar object.

Examples

pvar can be used to build a user interface without any messy patch cords

See Also
Name Description
receive Receive messages without patch cords
send Send messages without patch cords
thispatcher Send messages to a patcher
value Share a number with other objects
qlim
Queue-based message limiter

Description
Slows down throughput of messages. Limiting is based on a minimum amount of time between passed message.

Arguments
Name Units Type Opt Description
minimum ms int The minimum amount of time, in milliseconds, between successive outputs.

Messages
bang Performs the same function as an anything message applied to the passing of
bang messages.
int number [int] In left inlet: Equivalent to anything.
In right inlet: The number is stored as the minimum amount of time, in
milliseconds, between successive outputs.
float number [float] In left inlet: Equivalent to anything.
list list items [list] In left inlet: Equivalent to anything.
anything anything [list] In left inlet: Any number, bang, or message is passed out the outlet, provided that
a certain minimum time has elapsed since the previous output. Otherwise, the
message is held until that amount of time has passed (or until it is overwritten by
another incoming message).

Attributes
Name Type g/s Description
defer float Turn this on to send output in the low-priority queue.
quantize atom Send output only on the specified time-boundary if appropriate. This is achieved
by making internal adjustments to the times used for sending output. The
quantization can be specified in the following time formats: bars.beats.units, ticks
or note values.
threshold atom Sets the time threshold. The threshold can be specified in the following time
formats: bars.beats.units, ticks or note values.

Information for box attributes common to all objects

Examples
See Also
Name Description
speedlim Limit the speed of message throughput
qlist
Store a collection of messages

Description
Stores a collection of timed or untimed "cues" in the form of messages which can be sent either out its outlet or remotely to
various receive objects in your patch.

Arguments
None.

Messages
bang Sending a bang to qlist triggers automatic-playback of the entire cue list. It begins
sending messages from the first line, until a line begins with a number, at which
point qlist will use that number as a delay time in milliseconds before continuing
to send the remaining messages. A qlist that is playing automatically can be
stopped using the stop message.
append message [list] The word append followed by any arguments will append those arguments to the
last entry in the qlist object's cue-list. To append a semicolon, it must be preceded
by a backslash character.
clear The word clear will clear the contents of the cue-list. This is the same as sending a
set message with no arguments.
(mouse) Double-clicking with the mouse on the qlist object displays its contents as text in
an editing window which the user can modify.
fwd lines [int] The word fwd, followed by a number, is used to "fast forward" through a given
number of lines, without remotely sending messages to named receive objects. For
example, fwd 2 will output the next two lines in the cue-list which bengin with
numerical values. Lines beginning with symbols will be ignored.
insert message [list] The word insert followed by any arguments will append those arguments to the
qlist object's cue-list as a new entry in the list. To append a semicolon, it must be
preceded by a backslash character.
next ignore-symbols [int] The word next is used to output the next line in the cue-list. It will remotely send
all lines beginning with a symbol, and stop after it encounters and outputs a line
beginning with a numerical value. If the word next is followed by a non-zero
argument, it will ignore lines beginning with symbols and only output the next line
beginning with a numerical value.
open The word open will cause the qlist object's text editing window to be opened.
set cue-list-contents [list] The word set can be used to set the contents of a qlist object. It completely clears
any previous cue-list contents. Sending a set message with no arguments is the
same as sending a clear message.
stop The word stop can be used to stop a qlist which is in the middle of playback as a
result of a bang message.
read filename [symbol] The word read will allow you to read a file from disk via a standard Max file
opening dialog. If followed by a symbol argument, Max will use the symbol as a
filename (or filepath and filename) and try to read a text file with the given name
from the disk.
rewind lines [int] Move backwards by a certain number of lines.
tempo tempo-multiplier [float] The word tempo, followed by a floating-point numerical value, can be used to
allow a qlist to automatically play itself at a faster or slower speed than indicated
by the millisecond values stored internally in the cue list. By default the tempo is
1.0, which means the playback tempo is not scaled. A tempo of 0.5 plays back the
cue list at half speed, whereas a tempo of 2. plays it back twice as fast.
wclose The word wclose will cause the qlist object's text editing window to be closed.
write filename [symbol] The word write will allow you to save a file via a standard Max file saving dialog. If
followed by a symbol argument, Max will use the symbol as a filename (or filepath
and filename) and write a text file with the given name to disk.

Information for box attributes common to all objects

Output
bang: Out middle outlet. A bang is sent when a cue list has reached the end, and there are no more lines to send or output.
bang: Out right outlet. A bang is sent when a file has been read successfully from disk.
int: Out left outlet. The qlist object outputs a numerical value or list of numerical values when a line in the cue list begins with a
number. Output is usually in response to a next or fwd message, but can also be a result of the object's internal timer, when the
entire list of cues is being played as the result of a bang message.
list: Out left outlet. The qlist object outputs a numerical value or list of numerical values when a line in the cue list begins with a
number. Output is usually in response to a next or fwd message, but can also be a result of the object's internal timer, when the
entire list of cues is being played as the result of a bang message.

Examples

qlist is flexible and can be interfaced with a patcher of your own design

See Also
Name Description
coll Store and edit a collection of data
text Format messages as a text file
qmetro
Queue-based metronome

Description
Outputs bang messages at a set interval. Similar to metro, qmetro will drop output if the processing queue is overloaded.

Arguments
Name Units Type Opt Description
interval ms number opt The optional first argument sets an initial value for the time interval at which
metro sends its output. This time interval can be either a number which specifies
time in milliseconds (e.g. metro 100) or notevalue (e.g. metro 4n).

Note: While the metro object lets you specify time in any of Max's standard time
formats, the interval attribute argument should be used when specifying time in
any other time unit besides milliseconds or notevalues (e.g. metro @interval
11025 samples).

If there is no argument, the initial time interval is 5 milliseconds.

Messages
bang In left inlet: starts the qmetro object.
int input [int] In left inlet: Any number other than 0 starts the qmetro object. At regular
intervals, qmetro sends a bang out the outlet. 0 stops qmetro.

In right inlet: The number is the time interval, in milliseconds, at which qmetro
sends out a bang. A new number in the right inlet does not take effect until the
next output is sent.
float input [float] Performs the same function as int.
list input [list] In right inlet: A list may be used to specify time in one of the Max time formats.
anything interval [list] Same as list.
clock clockname [symbol] The word clock, followed by the name of an existing setclock object, sets the
qmetro object to be controlled by that setclock object rather than by Maxs
internal millisecond clock. The word clock by itself sets the qmetro object back to
using Maxs regular millisecond clock.
stop In left inlet: Stops qmetro.
reset The word reset will reset the object's counter used in 'clocker'-mode.

Attributes
Name Type g/s Description
active int Turns the qmetro object on and off.
autostart int If turned on (non-zero) the qmetro object will begin running automatically at the
time specified with the autostarttime attribute.
autostarttime atom If the autostart attribute is enabled (non-zero) the qmetro object will begin
running automatically at the time specified with the this attribute. The autostart
operates as a timepoint object that is internal to the qmetro object.
defer float Turn this on to send output in the low-priority queue.
interval atom Sets the The time interval at which the qmetro object sends out a bang. Time can
be specified in any of the time formats used in Max.
quantize atom Send output only on the specified time-boundary if appropriate. This is achieved
by making internal adjustments to the times used for sending output. The
quantization can be specified in the following time formats: bars.beats.units, ticks
or note values.
transport symbol This attribute names a master time transport. If the time is specified using a
'relative' unit (for example: ticks, bars.beats.units, or notevalues), then the named
transport is used to determine delay times based on tempo, time-signature, and
other related information.

Information for box attributes common to all objects

Examples

See Also
Name Description
clocker Report elapsed time, at regular intervals
counter Keep count based on bang messages
cpuclock Retrieve the CPU time
delay Delay a bang
setclock Create and control an alternative clock
tempo Output numbers at a metronomic tempo
transport Control a master clock
uzi Send many bang messages
Max Basic Tutorial 4: Metro and Max Basic Tutorial 4: Metro and Toggle
Toggle
quickthresh
Fast chord detection

Description
Combines messages when they are received close together. quickthresh is a faster, low-latency alternative to thresh that is
optimized for chord detection.

Arguments
Name Units Type Opt Description
threshold ms number opt The base threshold time in milliseconds; all notes received within this time period
The default value for the base threshold is 40 ms.
fudge ms number opt The "fudge" time in milliseconds - if any notes are played within this amount of
time at the end of the base thresh time, the threshold is extended. If not provided,
the default value is 10 ms.
extension ms number opt The thresh extension time in milliseconds. This is an additional time frame added
to the first argument, if necessary, in order to capture additional notes (due to
sloppy playing) into the list. The default value is 20 ms.

Messages
bang bang will reset quickthresh and output the notes in its buffer.
int input [int] The incoming values which appear within a certain time threshold are stored and
output as a list. See the argument descriptions to learn how the time thresholding
works.
(inlet1) threshold [int] Sets the millisecond value for the base thresh time. All values received in the left
inlet within this time period are collected into a list.
(inlet2) fudge [int] Sets the "fudge" time in milliseconds. If there are any incoming values within this
amount of time at the end of the base thresh time, the threshold is extended to
allow more values to be added to the list.
(inlet3) extension [int] In fourth inlet: Sets the threshold extension in milliseconds. This is an extension
of the base thresh time, which is used if values arrive in the object's inlet in the
"fudge" time zone.
float input [float] In left inlet: The incoming values which appear within a certain time threshold are
stored and output as a list. See the arguments' descriptions to learn how the time
thresholding works.
(inlet1) threshold [float] In second inlet: Sets the millisecond value for the base thresh time. All values
received in the left inlet within this time period are collected into a list.
(inlet2) fudge [float] In third inlet: Sets the "fudge" time in milliseconds. If there are any incoming
values within this amount of time at the end of the base thresh time, the threshold
is extended to allow more values to be added to the list.
(inlet3) extension [float] In fourth inlet: Sets the threshold extension in milliseconds. This is an extension
of the base thresh time, which is used if values arrive in the object's inlet in the
"fudge" time zone.
set threshold [int] The word set, followed by three millisecond values, can be used to set the three
fudge [int] threshold parameter values (base thresh time, "fudge" time and thresh extension).
extension [int]

Information for box attributes common to all objects

Output
float: When quickthresh has used up its threshold time, any incoming values that were played within the time threshold are
output as a list.
Examples

A comparison of quickthresh and thresh shows that quickthresh detects chords with lower, more constant, latency

See Also
Name Description
bondo Synchronize a group of messages
buddy Synchronize arriving data
iter Break a list into individual messages
join Combine items into a list
pack Create a list
thresh Combine messages when received close together
radiogroup
Radio button/check box user interface

Description
Provides a user interface for option selection. There are two modes of operation: radio button and checkbox.

Arguments
None.

Messages
bang In radio button mode: A bang outputs the currently selected radio button
number.

In check box mode: A bang outputs a list of zeros and ones representing the
on/off state of the check boxes.

In flag mode: A bang send the integer that corresponds to the bit pattern of the
currently checked boxes (i.e., if boxes one, two, and three are checked, a bang will
output a value of 7)out the radiogroup object's output.
int selection [int] In radio button mode: An integer sets the radio button selection and outputs the
input value. Numbering starts with 0, and a negative number indicates that no
buttons will be selected.

In flag mode: An integer value received in the radiogroup object's inlet will set
the buttons or checkboxes to reflect the bit pattern of the integer value (i.e., a
value of 19 will select boxes one, two, and five, corresponding to the binary value
10011) and send the integer value out the radiogroup object's output.
list states [list] In check box mode: list of zeros and ones sets the check box states and causes
output of the input list. If you have specified check box mode and have the flag
mode set using the flagmode 1 message, a list of zeros and ones sets the check
box states and causes output of the input list.
enableitem indices [list] In radio button and check box modes: The word enableitem, followed by followed
by a number or list of numbers, will enable the items whose numbers are indicated
if they have been disabled with the disableitem message.
disableitem indices [list] In radio button and check box modes: disable the items whose numbers are
indicated (they will be drawn in grey and will not respond to clicks, although they
will still respond to set messages, ints or lists).
(mouse) In radio button mode, clicking on a radio button will set the radio button
selection and output the corresponding button number (numbering starts from
zero). In check box mode, clicking on a check box will change its state (from one
to zero or from zero to one) and output a list of zeros and ones corresponding to
the on/off state of the boxes. if the entire group of buttons/boxes is inactive
(grayed out) it will not respond to clicks. if an individual item is disabled (grayed
out) it will not respond to clicks, although active items in the group will still
respond to clicks as usual. The Flag Mode variation on the check box mode has
check boxes that correspond to bit positions for a binary value (i.e. the first
checkbox corresponds to the 1s, the second to 2s, the third to 4s, etc.) Clicking on a
check box will select or deselect the check box and output the integer value which
corresponds to the bit pattern.
set selection [list] In radio button mode: The word set, followed by a number, sets the currently
selected radio button without triggering any output.

In check box mode: The word set, followed by a list of zeros and ones, sets the
check box states without triggering any output.
If you are using check box mode and are also using Flag Mode, a number will set
the state of the first 32 checkboxes in a pattern which corresponds to the bit
pattern of the number without triggering output (see the flagmode section for
more information).

Attributes
Name Type g/s Description
activecolor float Sets the color for the active radiobuttons/checkboxes in RGBA format.
bgcolor float Sets the background color for the object in RGBA format.
enabled atom Enables/disables buttons. The word enabled, followed by followed by a list of
zeroes and ones whose length is the same as the number of buttons or boxes, will
disable (0) or enable (1) the item in the list position that corresponds to the button
or box (e.g., enableitem 1 1 1 0 will disable only the fourth button or box).
flagmode int Sets the flag mode of operation for the radiogroup object. In this mode, each
def.:0 check box corresponds to one bit in an integer value (i.e., the first radio button or
checkbox corresponds to the ones bit, the second button or checkbox to the twos
bit, the third button or checkbox to the fours bit, etc.). The message flagmode 0
disables this mode (default).
inactive int Toggles the active or inactive state of the entire group of radio buttons or check
def.:0 boxes.
inactivecolor float Sets the color for the inactive radiobuttons/checkboxes in RGBA format.
itemtype int Selects the mode of operation for the radiogroup object.
def.:0 Button (the default)
Checkbox
'Radio Buttons' = TEXT_HERE
'Check Boxes' = TEXT_HERE
offset int Sets the pixel offset (spacing) between the tops of the buttons/boxes. the
def.:16 minimum offset is 14 pixels, the default offset is 16 pixels.
parameter_enable int Parameter Mode Enable
selection atom Specifies the currently selected button or box.
size int Specifies the number of buttons or boxes. The default is 2, and the maximum is
def.:2 64. Note: If you care using the radiogroup object in check box mode and have
enabled Flag Mode, you will only be able to set 32 checkboxes.

Information about attributes available for Parameter-aware objects

Information for box attributes common to all objects

Output
int: In radio button mode: Clicking on a radio button outputs an int corresponding to the radio button selected. Numbering
begins with 0.

In flag mode: Clicking on a check box outputs an int corresponding to the bit pattern represented by the checked boxes (i.e., if
boxes one, two, and three are checked, a bang will output a value of 7).
list: In check box mode: A bang will output a list of zeros and one which indicate the on/off state of the group of check boxes.

Examples
Radio buttons allow a single selection, and multiple selection check boxes can control several gates

See Also
Name Description
button Blink and send a bang
matrixctrl Matrix switch control
pictctrl Picture-based control
toggle Switch between off and on (0/1)
ubutton Send a bang with a transparent button
Max Basic Tutorial 21: Max Basic Tutorial 21: Controlling Data Flow
Controlling Data Flow
random
Generate a random number

Description
Outputs random numbers within the range between 0 and 1 less than the argument specified.

Arguments
Name Units Type Opt Description
range int opt Sets an initial limit to the random output. The output will always be between 0 and
one less than this maximum limit. If there is no argument, the limit is initially set
to 1, which causes random to output 0 whenever it receives a bang.
seed int opt A second argument is used to set a "seed" value for the random generator. If no
argument is specified, the time value will be used to initialize the seed.

Messages
bang In left inlet: Sends out a randomly generated number between 0 and one less than
its maximum limit.
seed seed-value [int] In left inlet: The word seed, followed by a number, provides a "seed" value for the
random generator, which causes a specific (reproducible) sequence of pseudo-
random numbers to occur. The number 0 uses the time elapsed since system
startup (an unpredictable value) as the seed, ensuring an unpredictable sequence
of numbers. This unpredictable seed is used by default when the random object is
created.

Information for box attributes common to all objects

Output
int: When a bang is received in the left inlet, random generates a random number between 0 and one less than its maximum
limit.

Examples

Generate random events, or make decisions based on probability

See Also
Name Description
decide Choose randomly between 1 and 0
drunk Output random numbers within a step range
urn Generate random numbers without duplicates
Max Basic Tutorial 10: Random Max Basic Tutorial 10: Random Drawing
Drawing
!/
Divide input from a number

Description
Divides a number by the incoming value. Functions like the / object, but the inlets' functions are reversed.

Arguments
Name Units Type Opt Description
divisor number opt Sets an initial value for the divisor. If there is no argument, the divisor is set to 1
initially. A float argument causes the numbers to be divided as floats.

Messages
bang In left inlet: Performs the division with the numbers currently stored.
int input [int] Stores the value as the divisor (the number to be divided into the number in the
right inlet) and produces output.
(inlet1) input [int] Numbers received in the right inlet are divided by numbers received in the number
in the left inlet.
float input [float] Converted to int, unless !/ has a float argument.
(inlet1) input [float] Converted to int, unless !/ has a float argument.

Information for box attributes common to all objects

Output
float: Only if there is an argument with a decimal point.
int: The two numbers in the inlets are divided, and the result is sent out the outlet.

Examples

/ with the inputs swapped

See Also
Name Description
/ Divide two numbers
expr Evaluate a mathematical expression
receive
Receive messages without patch cords

Description
Receives and outputs messages from send objects sharing the same name. This allows you to send any kind of message between
Patcher windows or within a window without using patch cords. A receive object can be instantiated with its short-form: the
letter "r".

Arguments
Name Units Type Opt Description
name symbol opt Name the receive object. If there is no argument, receive has one inlet, and a
name must be provided by a set message before anything can be received. All
receive objects that share the same name will receive data from any send objects
that share their name.

For information about using named objects in Max for Live, click here.

Messages
(mouse) Double-clicking on a receive object looks for and opens a loaded patcher window
containing a send object with the same name. Repeatedly double-clicking on the
receive object looks for and opens more such windows.
set name [symbol] The word set, followed by a symbol, provides a name for receive, as if that name
had been typed in as an argument.

Information for box attributes common to all objects

Output
anything: Any message received in the inlet of any send or forward object with the same name, or sent explicitly from an int,
float, grab, or message box, is passed out the outlet of receive, even if the sending object is in a different loaded patch.

Examples

Virtual connections exist between all send and receive objects that share the same name

See Also
Name Description
float Store a decimal number
forward Send messages to specified receive objects
int Store an integer value
message Send any message
pattrforward Send any message to a named object
pvar Connect to a named object in a patcher
route Select outlet based on input matching
send Send messages without patch cords
value Share a number with other objects
Max Basic Tutorial 16: Remote Max Basic Tutorial 16: Remote Messaging
Messaging
regexp
Use regular expressions to process input

Description
Arguments
Name Units Type Opt Description
expression list opt A regular expression may be used as an argument to set the regular expression
(see above for regular expression formatting and metacharacter information).

Messages
int subject-string [int] Any int received in the regexp object's inlet is treated as the subject string to be
processed according to the regular expression and symbol substitutions provided.
float subject-string [float] Any float received in the regexp object's inlet is treated as the subject string to be
processed according to the regular expression and symbol substitutions provided.
list subject-string [list] Any symbol or list received in the regexp object's inlet (not matching the object's
attributes) is treated as the subject string to be processed according to the regular
expression and symbol substitutions provided.
anything subject-string [list] Performs the same function as a list message.

Attributes
Name Type g/s Description
re symbol The word re, followed by a PERL-compatible regular expression, sets the regular
expression rules to be used when parsing or making substitutions within any
symbol or list input.

If a regular expression contains spaces, it must be enclosed within double quotes


when specified using the re message or as a typed-in argument to the regexp
object.

Regular expressions use the following form and syntax:

[...] defines a 'class' of characters. any of the characters within it may be matched.
several special symbols may also appear within it:

...-... specifies a range (within ASCII codes)

\\d specifies a decimal digit (\\D specifies a non-decimal digit). Note that double
backslashes must be used -- Max erases single backslashes.

\\s specifies white space (\\S specifies non-white space). Note that double
backslashes must be used -- Max erases single backslashes.

\\w specifies an alphanumeric (\\W specifies a nonalphanumeric). Note that


double backslashes must be used -- Max erases single backslashes.

^... specifies a complement of

...* appears zero times

...+ appears at least once

...? appears once or not at all

(...) specifies a backreference that may be referred to in a substitution string such


as %n, where n is the position of the parenthesis in left-to-right order.
substitute symbol The word substitute, followed by a symbol, passes a symbol to be used in
substitutions. If the word substitute is not followed by a symbol, the previous
substitution symbol is removed.

Note: If you need to output a % followed by a number in any substitution string,


you should use %%, so that the % is not read as a backreference.
tosymbol int The word tosymbol, followed by a zero or one, toggles the output behavior of the
regexp object. When enabled, output from the left outlet of the object will be a
single symbol. When disabled, output from the left outlet of the object will consist
of a list of individual elements.

Information for box attributes common to all objects

Output
symbol or list: Out left outlet: If a substitute string has been set using the substitute message, the input list or symbol is sent out
the left outlet with any required substitutions (n.b. substitute strings may contain back references, of the form %n).

Out center-left outlet: If the regular expressions contains parentheses, they are treated as backreferences. The middle outlet
reports the backreferences upon every match within the subject string, and outputs them in the form of a list.

Out center outlet: The rightmost outlet reports a list of the instances where the regular expression matched portions of the
subject string.

Out center-right outlet: The rightmost outlet passes the original input, in the case that not match occurs.

Out right outlet: The rightmost outlet is used to report the values of the object's attributes.

Examples
See Also
Name Description
fromsymbol Convert a symbol into numbers/messages
key Report keyboard presses
keyup Report key information on release
message Send any message
spell Convert input to ASCII codes
tosymbol Convert messages, numbers, or lists to a single symbol
relativepath
Convert an absolute to a relative path

Description
Converts an absolute path to one that is relative to the Max application folder.

Arguments
None.

Messages
anything pathname [symbol] An absolute pathname of a folder or file as a symbol. An absolute pathname looks
like this:
'MyDisk:/Max Folder/extras/filename'

Information for box attributes common to all objects

Output
symbol: The pathname of the folder or file relative to the Max application folder as a symbol. If the input pathname is within the
Max application folder, the path is changed to start with a dot-slash (./) followed by the folder names of the path. Otherwise, the
input is repeated to the output.

Examples

See Also
Name Description
absolutepath Convert a file name to an absolute path
conformpath Convert file paths styles
opendialog Open a dialog to ask for a file or folder
strippath Separate filename from a full pathname
!-
Subtraction object (inlets reversed)

Description
Subtracts the input from a specified value The !- object functions just like the - object, but the inlets' functions are reversed.

Arguments
Name Units Type Opt Description
value int or float opt Sets the initial value, to be subtracted from a number received in the left inlet. A
float argument causes the numbers to be subtracted as floats.

Messages
bang In left inlet: Performs the subtraction with the numbers currently stored. If there
is no argument, !- initially holds 0.
int input [int] In left inlet: The number is stored, and will be subtracted from a number received
in the right inlet.
(inlet1) input [int] In right inlet: The number in the left inlet is subtracted from the number, and the
result is sent out the outlet.
float input [float] Converted to int, unless !- has a float argument.
(inlet1) input [float] Converted to int, unless !- has a float argument.

Information for box attributes common to all objects

Output
float: Only if there is an argument with a decimal point.
int: The difference between the two numbers received in the inlets.

Examples

- with the inputs swapped

See Also
Name Description
- Subtract two numbers, output the result
expr Evaluate a mathematical expression
round
Round to a value

Description
Calculates and outputs an integer multiple of any given number.

Arguments
Name Units Type Opt Description
multiple number opt An argument can be used to specify the value to whose nearest multiple the
rounding will be done.

Messages
int input [int] Value to be rounded, Number values received in the left inlet will be rounded to
either the absolute nearest integer multiple or the nearest integer multiple
between the value received in this inlet or 0 (see the nearest attribute for more
information).
float input [float] Value to be rounded.
list input [list] Values to be rounded.
anything input [list] Values to be rounded.

Attributes
Name Type g/s Description
nearest int When set to 1 (the default), the round object will round to the nearest multiple of
the specified number value.

Note: This attribute does not set the rounding step (which is set using round
object's right inlet), It specifies that rounding to the nearest number value will
occur.

Information for box attributes common to all objects

Output
float: The nearest whole numbers of the input.
list: List of the nearest whole numbers of the input list.

Examples

See Also
Name Description
expr Evaluate a mathematical expression
vexpr Evaluate a math expression for a list
round~ Round an input signal value
route
Select outlet based on input matching

Description
Tries to match a message's first argument to the route object's own arguments. The rightmost outlet passes any message that
matched no other choice, so you may gang route objects to get more choices

Arguments
Name Units Type Opt Description
selectors anything opt Arguments can be a mix of ints, floats, or symbols. The number of arguments
determines the number of outlets, in addition to the rightmost outlet. Each
argument assigns a name or a number to an outlet. If there is no argument, there
is one other outlet, which is assigned the number 0.

Messages
bang Performs the same function as anything.
int input [int] Performs the same function as anything.
float input [float] Performs the same function as anything.
list input [list] Performs the same function as anything.
anything input [list] If the first item of the message is the same as one of the arguments of route, the
rest of the message is sent out the outlet that corresponds to that argument. If the
first item does not match any of the arguments, the entire message is passed out
the rightmost outlet.

Information for box attributes common to all objects

Output
anything: The first item of any message received in the inlet is compared with the arguments. If it matches one of the arguments,
the rest of the message is sent out the specified outlet. Otherwise, the entire message is passed out the rightmost outlet.
bang: If the first item of a message matches one of the arguments, but the message has no additional items, bang is sent out the
specified outlet.

Examples

Arguments assign names or numbers to the outlets, and route the input to the correct outlet

See Also
Name Description
bucket Pass numbers from outlet to outlet
forward Send messages to specified receive objects
gate Pass input to an outlet
join Combine items into a list
pack Create a list
receive Receive messages without patch cords
routepass Route a complete incoming message based on input matching
select Output bangs based on input matching
send Send messages without patch cords
sprintf Format a message of words and numbers
zl Process lists in many ways
Max Basic Tutorial 18: Data Max Basic Tutorial 18: Data Collections
Collections
routepass
Route a complete incoming message based on input matching

Description
Tries to match a message's first argument to the route object's own arguments. Unlike the route object, routepass does not strip
off the matched portion of the message. The rightmost outlet passes any message that matched no other choice, so you may gang
route objects to get more choices

Arguments
Name Units Type Opt Description
selectors anything opt Arguments can be a mix of ints, floats, or symbols. The number of arguments
determines the number of outlets, in addition to the rightmost outlet. Each
argument assigns a name or a number to an outlet. If there is no argument, there
is one other outlet, which is assigned the number 0.

Messages
bang Sending a bang to the object will send a bang out any outlet that uses 'bang' as its
argument. If bangs are not specified as arguments, a bant will be passed out the
rightmost outlet.
int input [int] If the first integer value in the message is the same as one of the arguments of
routepass, the entire message is sent out the outlet that corresponds to that
argument. If the first integer value does not match any of the arguments, the
entire message is passed out the rightmost outlet.
float input [float] If the first floating-point value in the message is the same as one of the arguments
of routepass, the entire message is sent out the outlet that corresponds to that
argument. If the first floating-point value does not match any of the arguments,
the entire message is passed out the rightmost outlet.
list input [list] If the first item of the message is the same as one of the arguments of routepass,
the entire message is sent out the outlet that corresponds to that argument. If the
first item does not match any of the arguments, the entire message is passed out
the rightmost outlet.
anything input [list] If the first item of the message is the same as one of the arguments of routepass,
the entire message is sent out the outlet that corresponds to that argument. If the
first item does not match any of the arguments, the entire message is passed out
the rightmost outlet.

Information for box attributes common to all objects

Output
anything: The first item of any message received in the inlet is compared with the arguments. If it matches one of the arguments,
the full message is sent out the specified outlet. Otherwise, the message is passed out the rightmost outlet.
bang: If the first item of a message matches one of the arguments, but the message has no additional items, bang is sent out the
specified outlet.

Examples
The routepass object matches inputs, but passes the whole message (unlike route)

See Also
Name Description
bucket Pass numbers from outlet to outlet
forward Send messages to specified receive objects
gate Pass input to an outlet
join Combine items into a list
pack Create a list
receive Receive messages without patch cords
select Output bangs based on input matching
send Send messages without patch cords
sprintf Format a message of words and numbers
route Select outlet based on input matching
zl Process lists in many ways
Max Basic Tutorial 18: Data Max Basic Tutorial 18: Data Collections
Collections
router
Route messages to multiple locations

Description
Arguments
Name Units Type Opt Description
inlets int Sets the number of inlets
outlets int Sets the number of outlets

Messages
bang bang received in any but the leftmost inlet will be sent to all outlets that are
connected to that inlet.
int input [int] An integer received in any but the leftmost inlet will be sent to all outlets that are
connected to that inlet.
float input [float] floating-point number received in any but the leftmost inlet will be sent to all
outlets that are connected to that inlet.
list inlet [int] A list of three numbers received in the left inlet is interpreted as specifying an inlet
outlet [int] number, an outlet number, and a 0 or 1 specifying the state of a connection. A list
state [int] in this form changes the inlet and outlet connections of the router object.

A list received in any other inlet will be sent to all outlets that are connected to
that inlet.
anything input [list] Any Max message received in any but the leftmost inlet will be sent to all outlets
that are connected to that inlet.
disconnect inlet [int] The word disconnect, followed by two numbers that specify inlet and outlet
outlet [int] numbers, disconnects an inlet from an outlet.
dump arguments [list] Sends the state of the object's switching matrix out the right outlet as a series of
single line lists in the form inlet-number outlet-number state.
clear arguments [list] Clears the state of the switching matrix, All inlets are disconnected from all
outlets.
connect inlet [int] The word connect, followed by two numbers that specify inlet and outlet
outlet [int] numbers, connects an inlet to an outlet. Multiple inlets can be connected to
multiple outlets, and vice versa.
patch inlet [int] The word patch, followed by two numbers that specify inlet and outlet numbers,
outlet [int] connects an inlet to an outlet and disconnects all other inlets that are currently
connected to that outlet
print arguments [list] Prints the state of the switching matrix in the Max window.

Information for box attributes common to all objects

Output
anything: Any message received in any but the leftmost inlet will be routed to the outlet to which the inlet is currently connected.
The router objects passes messages only; it will not pass signals or Jitter matrices.
list: Out right outlet: a series of single-line lists (one for each inlet) in the form inlet-number outlet-number state is sent out
the right outlet of the router object in response to a dump message.

Examples
See Also
Name Description
matrixctrl Matrix switch control
Max Basic Tutorial 21: Max Basic Tutorial 21: Controlling Data Flow
Controlling Data Flow
Tutorial 13: Scissors and Glue Tutorial 13: Scissors and Glue
Tutorial 26: MIDI Control of Tutorial 26: MIDI Control of Video
Video
rslider
Display or change a range of numbers

Description
Set a value range from the lowest to highest value.

Arguments
None.

Messages
bang In left inlet: Sends out the minimum and maximum values of the currently
displayed range.
int minimum [int] In left inlet: The number sets the minimum limit of a range displayed as a colored
region on the rslider, and causes the minimum and maximum values of that range
to be sent out. A number that exceeds the limits of the rslider itself will be limited
to stay within the rslider.

The minimum and maximum values can also be set (and sent out) by dragging
with the mouse across a range in the rslider.
(inlet1) maximum [int] In right inlet: The number is stored as the maximum limit of the range displayed
in color on the rslider. A number that exceeds the limits of the rslider itself will
be limited to stay within the rslider.

The minimum and maximum values can also be set (and sent out) by dragging
with the mouse across a range in the rslider.
float minimum [float] Converted to int.
(inlet1) maximum [float] In right inlet: The number is stored as the maximum limit of the range displayed
in color on the rslider. A number that exceeds the limits of the rslider itself will
be limited to stay within the rslider.

The minimum and maximum values can also be set (and sent out) by dragging
with the mouse across a range in the rslider.
list minimum [int] In left inlet: The first two numbers in the list are used to set the minimum and
maximum [int] maximum values of the displayed range, and are sent out.
(mouse) Clicking on the rslider object and dragging sets the minimum and maximum
values and sends them out the object's outlets (or left outlet in list mode). or
setting attributes.
set minimum [int] In left inlet: The word set, followed by two numbers, sets the minimum and
maximum [int] maximum values of the currently displayed range, without sending them out the
outlets.
setminmax low [int] The word setminmax, followed by two numbers, sets the low and high range
high [int] values for the rslider object. The floatoutput attribute will automatically be set.

Attributes
Name Type g/s Description
bgcolor float Sets the background color of the rslider object in RGBA format.
bordercolor float Sets the border color of the rslider object in RGBA format.
drawline int Toggles the drawing of a center line on the rslider display. The default value is 1
def.:1 (on).
fgcolor float Sets the range color of the rslider object in RGBA format.
floatoutput int Toggles floating-point output from the slider object. The default is 0 (off).
def.:0
listmode int Toggles the list output mode. When it is on, the rslider object will output the min
def.:0 and max values as a list out the left outlet. Otherwise, the values are sent out the
right and left outlets. The default value is 0 (off).
min int Sets value that will be added to the rslider object's lower value before it is sent out
def.:0 the outlet.
mult float Sets a multiplier value. The rslider object's value will be multiplied by this number
def.:1. before it is sent out the outlet. The default value is 1.
orientation int Sets the rslider object to a horizontal or vertical data display.
def.:0 Automatic: (the default) sets the display dependent on the size of the slider -
longest side of the rectangle that describes the slider sets the orientation.
Horizontal
Vertical
'Automatic' = TEXT_HERE
'Horizontal' = TEXT_HERE
'Vertical' = TEXT_HERE
parameter_enable int Parameter Mode Enable
size float Sets the total range of the rslider. The rslider will range from 0 to one less than
def.:128. the specified size. A size message smaller than 1 will be automatically set to 2. By
default, the size of an rslider is 128.

Information about attributes available for Parameter-aware objects

Information for box attributes common to all objects

Menu Items
Name Description
Color Choosing the Color... menu item from the Object menu when the object is
selected opens a color picker, permitting adjustment to the appearance of the
rslider object.

Output
int: The maximum value of the displayed range is sent out the right outlet, and the minimum value is sent out the left outlet.
Output is triggered by a new minimum value (or a bang) received in the left inlet, or by clicking or dragging the mouse in the
rslider.

Examples

Output minimum and maximum values, to set the range of another object

See Also
Name Description
multislider Display data as sliders or a scrolling display
nslider Output numbers from a notation display
pictctrl Picture-based control
pictslider Picture-based slider control
slider Move a slider to output values
split Look for a range of numbers
Max Basic Tutorial 13: Movie Max Basic Tutorial 13: Movie Sequencing
Sequencing
rtin
Receive MIDI real time messages

Description
Receives and outputs MIDI real time messages transmitted from a specified MIDI input device.

Arguments
Name Units Type Opt Description
port symbol opt Specifies the port (a-z) from which to receive incoming MIDI real time messages.
If there is no argument, rtin receives from port a (or the first input port listed in
the MIDI Setup dialog.)

Messages
anything port [list] Performs the same function as port but without need for the word, "port".
(mouse) Double-clicking on an rtin object shows a pop-up menu for choosing a MIDI port
or device.
(MIDI) The rtin object receives its input from a MIDI real-time message received from a
MIDI input device.
port MIDI-port [symbol] The word port, followed by a letter a-z or the name of a MIDI input port or
device, sets the port from which the object receives incoming MIDI messages. The
word port is optional and may be omitted.

Information for box attributes common to all objects

Output
int: MIDI real time messages (MIDI clock, start, stop, and continue) received from the specified port are sent out the outlet.

Examples

MIDI real time messages can be used to synchronize Max with external events

See Also
Name Description
clocker Report elapsed time, at regular intervals
metro Output a bang message at regular intervals
midiin Output raw MIDI data
seq Sequencer for recording and playing MIDI data
savedialog
Open a dialog asking for a filename

Description
Opens a file dialog for selection or entry of a filename to write. savedialog takes a list of one or more file types and allows you to
save a file and choose a type for it.

Arguments
Name Units Type Opt Description
filetypes symbol opt Sets one or more file types that will be displayed as choices for the user. The
symbol fold specifies that the dialog box should let the user choose only folders.

Messages
bang Causes a standard Save As dialog box to appear, allowing the user to type in a
filename and choose a folder location. The resulting location and filename are
output as a symbol.
anything filetype [list] One or more four-letter type codes sets the list of types displayed in the dialog
box. Example type codes for files are TEXT for text files, maxb for Max binary
format patcher files, and AIFF for AIFF format audio files. The symbol fold
specifies that the dialog box should let the user choose only folders.
name filename [symbol] The word name, followed by a symbol, specifies a default file name.
set filetype [list] The word set, followed by a four-letter symbol (e.g., TEXT, MAXB) which specifies
a file type, sets the savedialog object to display the desired file type without
opening the dialog box. The chosen file type is sent out the middle outlet when the
user chooses Save in the dialog box.

Information for box attributes common to all objects

Output
bang: Out right outlet: If the user chooses Cancel in the dialog box, a bang is sent out.
symbol: Out left outlet: The absolute pathname of the file as a symbol. The output pathnames contain slash separators.

Absolute pathnames look like this:

"C:/Max Folder/extras/mystuff/mypatch.pat"

The conformpath object can be used to convert paths of one pathtype and/or pathstyle to another.
symbol: Out middle outlet: The four-letter symbol which specifies the filetype currently selected.

Examples

Select a folder or a specific file type for file saving


See Also
Name Description
conformpath Convert file paths styles
dialog Open a dialog box for text entry
filedate Report the modification date of a file
filein Read and access a file of binary data
filepath Manage and report on the Max search path
opendialog Open a dialog to ask for a file or folder
scale
Map values to an output range

Description
The scale object maps an input range of float or integer values to an output range. The output range can be larger or smaller than
the input range, can be inverted and can change numeric type. If specified, the mapping can also be exponential.

Arguments
Name Units Type Opt Description
input-low number opt Sets the low end of the expected input range. Incoming values are not clipped to
this range; rather, the input range is used to determine the value mapping
formula.
input-high number opt Sets the high end of the expected input range. Incoming values are not clipped to
this range; rather, the input range is used to determine the value mapping
formula.
output-low number opt This sets the low end of the output range, and will be the lowest output value if the
input value stays with its expected range.
output-high number opt This sets the high end of the output range, and will be the highest output value if
the input value stays with its expected range.
exponential float opt This optional fifth argument specifies the nature of the scaling curve. This
argument must be a floating-point number greater than 1, with larger values
leading to steeper exponential curves.

In classic mode a typical value for this argument is 1.06 and the number is
converted according to the following expression:
y = b e-a log c ex log c
where x is the input, y is the output, a, b, and c are the three typed-in arguments,
and e is the base of the natural logarithm (approximately 2.718282).

In non- classic (modern) mode the value for the scaling curve is converted
according to the following expression:

y = x^k

where x is the input, y is the output, and k is the curve value. If k = 1 then the
scaling is linear. Higher values of k will result in an exponential mapping, while
lower values of k will result in a logarithmic mapping. The value of k must be
greater than zero.

Note that prior to Max 6.0.4 the exponent was inverted. Thus, if you gave it an
exponent of 2 the object behaved like it had an exponent of 0.5, and if you gave it
an exponent of 0.5 it behaved like it had an exponent of 2. Patches from versions
prior to 6.0.4 may require updating to work properly.

Messages
bang Perform the scaling operation on the most recently received input value. If the
range values have been changed, the scaling will be based on the new range.
int input [int] The scaling function is performed on the incoming value. If any of the range types
are floating point, the value is converted into a float for the calculation.
float input [float] In left inlet: The scaling function is performed on the incoming value. If the input
range type is integer, the value is converted into an int for the calculation.

In second inlet: Sets the low end of the input range.


In third inlet: Sets the high end of the input range.

In fourth inlet: Sets the low end of the output range.

In fifth inlet: Sets the high end of the output range.

In sixth inlet: Sets the scaling curve value as described in the object arguments
section.
list input [list] A list of numbers sent to the left inlet will trigger the output of a list with the
results of scaling operation perforned on each item.

Attributes
Name Type g/s Description
classic int Classic mode uses exponential function that is backward compatible with old
IRCAM patchers.

Information for box attributes common to all objects

Output
float: When scale receives a value in its leftmost inlet, that value is scaled to the indicated output range of values.
int: If only four arguments are provided and all four are of type int, scale will output scaled values as integers. Otherwise output
is floating-point.

Examples

An example of how to scale an integer slider into a useful range of floating-point values

See Also
Name Description
expr Evaluate a mathematical expression
linedrive Scale numbers exponentially
zmap Maps input range of values to output range
Max Basic Tutorial 11: Procedural Max Basic Tutorial 11: Procedural Drawing
Drawing
screensize
Output the monitor size

Description
Reports the resolution to which the computer's monitor is currently set.

Arguments
None.

Messages
bang Triggers the output of the main screen size and total multi-monitor screen
bounding rectangle out the outlets.

Information for box attributes common to all objects

Output
list: Out left outlet: The bounding coordinates of the main screen: left is first, followed by top, right, and bottom.

Out right outlet: The bounding coordinates of all monitors. If there is only one monitor, the output will be the same as with the
left outlet.

Examples

screensize reports the coordinates of the main and total screen areas

See Also
Name Description
gestalt Retrieve system information
menubar Put up a custom menu bar
thispatcher Send messages to a patcher
zmap Maps input range of values to output range
Max Basic Tutorial 13: Movie Max Basic Tutorial 13: Movie Sequencing
Sequencing
select
Output bangs based on input matching

Description
Selectively outputs a bang in response to any input which matches its arguments and will output non-matching messages out its
right-most outlet.

Arguments
Name Units Type Opt Description
selectors anything opt The arguments can be a mix of ints, floats, or symbols. The number of arguments
determines the number of outlets in addition to the rightmost outlet. If there is no
argument, there is only one other outlet, which is assigned the integer number 0.
inlet int If there is a single int argument (or if there are no arguments) a second inlet is
created on the right. Numbers received in that inlet are stored in place of the
argument. If there is more than one argument, or if the only argument is not an
int, the right inlet is not created.

Messages
bang Performs the same function as anything. The bang message matches a 'bang'
symbol in the arguments.
int input [int] Performs the same function as anything.

Note: If an int is listed multiple times as an argument, a bang message will be


sent out the leftmost outlet only.
(inlet1) value [int] In right inlet: Replaces the value of the argument. The right inlet exists only if
there is a single int argument.
float input [float] Performs the same function as anything.

Note: If a float is listed multiple times as an argument, a bang message will be


sent out the leftmost outlet only.
anything input [list] All input will be selectively output either as a bang from one of its corresponding
outlets if it matches the object argument(s) or as it is out the object's right-most
outlet.
symbol input [symbol] Performs the same function as anything.

Information for box attributes common to all objects

Output
anything: If the number or symbol received in the left inlet does not match any of the arguments, it is passed out the rightmost
outlet.
bang: If the number or symbol received in the left inlet is the same as one of the arguments, a bang is sent out the outlet that
corresponds to that argument.

Examples
Arguments assign names or numbers to the outlets, and a bang is sent when the input matches them

See Also
Name Description
if Conditional statement in if/then/else form
match Watch for a message match, then output the message
route Select outlet based on input matching
== Compare numbers for equal-to condition
send
Send messages without patch cords

Description
send will transmit given messages to receive objects which are named by the same argument and will allow you to send any kind
of message between Patcher windows or within a window without using patch cords. A send object can be instantiated simply by
typing into an object box the short-form letter "s".

Arguments
Name Units Type Opt Description
name symbol Name the send object. All send objects that share the same name will send data
to any receive objects that share their name.

For information about using named objects in Max for Live, click here.

Messages
bang Performs the same function as anything.
int input [int] Performs the same function as anything.
float input [float] Performs the same function as anything.
list input [list] Performs the same function as anything.
anything input [list] A message received in the inlet is sent out the outlet of any receive object that has
the same name, even if the receive is in another loaded patch.
(mouse) Double-clicking on a send object opens all windows containing receive objects
with the same name, and also lists the instance numbers of patches hosted in a
poly~ object that share named receive objects.

Information for box attributes common to all objects

Output
anything: There are no outlets. A message received in the inlet of send is sent out the outlet of any receive with the same name,
even if the receive is in another loaded patch.

Examples

Virtual connections exist between all send and receive objects that share the same name

See Also
Name Description
forward Send messages to specified receive objects
message Send any message
pattrforward Send any message to a named object
pv Share data within a patch hierarchy
pvar Connect to a named object in a patcher
receive Receive messages without patch cords
value Share a number with other objects
Max Basic Tutorial 16: Remote Max Basic Tutorial 16: Remote Messaging
Messaging
seq
Sequencer for recording and playing MIDI data

Description
seq is a sequencer of raw MIDI bytes. You can control the speed of playback (only at the time you start it), read and write from
files, and record from live MIDI input. See also midiparse and midiformat which you may need to get to and from raw MIDI.

Arguments
Name Units Type Opt Description
filename symbol opt Specifies the name of a file to be read into seq automatically when the patch is
loaded.

Messages
bang Starts playing the sequence stored in seq.
int input [int] When seq is recording, numbers received in its inlet are interpreted as bytes of
MIDI messages (usually from midiformat or midiin). MIDI channel messages
and system exclusive messages can be recorded by seq, but seq does not respond
directly to MIDI real time messages such as start, stop, MIDI clock, etc.
float input [float] Converted to int.
append Starts recording at the end of the stored sequence, without erasing the existing
sequence.
delay onset-time (milliseconds) [int] The word delay, followed by a number, sets the onset time, in milliseconds, of the
first event in the recorded sequence. All events in the sequence are shifted so that
the first event occurs at the specified onset time.
dump Opens a standard Open Document dialog box, to select a saved sequence or
standard MIDI file. The selected file is opened as text in a new Untitled text
window, which can be edited and saved.
hook event-time-multiplier [float] The word hook, followed by a float, multiplies all the event times in the stored
sequence by that number. For example, if the number is 2.0, all event times will be
doubled, and the sequence will play back twice as slowly. Multiplications can even
be performed while the sequence is playing.
print Prints the first sixteen events of the recorded sequence in the Max window.
start tempo-multiplier [int] The word start by itself has the same effect as bang. The word start, followed by a
number, plays the stored sequence at a tempo determined by the number. The
message start 1024 indicates normal tempo. If the number is 512, seq plays the
sequence at half the original recorded speed, start 2048 plays it back at twice the
original speed, and so on.

The message start -1 starts the sequencer, but rather than follow Max's
millisecond clock, seq waits for a tick message to advance its clock. See the tick
message.
read filename [symbol] With no arguments, read calls up the standard Open Document dialog box, so that
a previously recorded sequence can be read into seq, replacing the current
sequence. With a symbol as an argument, read searches for a file with the
specified name to read into the seq object.

Note: The seq object reads and writes single track (format 0) standard MIDI files.
It can also read and write text files in which each line consists of a start time in
milliseconds (the time elapsed since the beginning of the sequence) followed by
the (space-separated) bytes of a MIDI message recorded at that start time. For
example,
0 144 60 112;

1000 144 60 0;

1500 192 31;

1500 144 60 112;

2500 144 60 0;

plays the note middle C on channel 1 for one second, then half a second later
changes to program number 31 and plays middle C again for one second.
tick After seq has received a start -1 message, it waits for tick messages to advance
its clock. In order to play the sequence at its original recorded tempo, seq must
receive 48 tick messages per second. This is equivalent to 24 tick s per quarter
note (the standard for a MIDI Clock message) at a tempo of 120MM. By using tick
messages to advance the sequencer, you can vary the tempo of playback or
synchronize seq with another timing source (such as incoming MIDI Clock
messages).
stop Stops the sequencer if it is recording or playing. A stop message need not be
received when switching directly from playing to recording, or vice-versa.
record Starts recording MIDI messages received in the inlet.
write filename [symbol] Calls up the standard Save As dialog box, so that a recorded sequence can be saved
as a separate file. If you want to edit the sequence with the text editor, check the
Save As Text option in the dialog box. With a symbol as an argument, write will
write a file with the specified name.

Information for box attributes common to all objects

Output
bang: Out right outlet: Indicates that seq has finished playing the current sequence. (The bang is sent out immediately before
the final event of the sequence is played.)
int: Out left outlet: When bang or start is received in the inlet, the sequence stored in seq is sent out the outlet in the form of
individual MIDI bytes, usually to be sent to midiparse or midiout.

Examples

Record and play back live performance, or play a pre-recorded sequence

See Also
Name Description
coll Store and edit a collection of data
follow Compare a live performance to a recorded performance
mtr Record and sequence messages
Max MIDI Tutorial 4: MIDI Basic Max MIDI Tutorial 4: MIDI Basic Sequencing
Sequencing
serial
Send and receive from a serial port

Description
Arguments
Name Units Type Opt Description
port symbol opt Specifies the serial port to be used by the serial object. If alphabetic shortcuts (a-
z) are used, a specifies the first logical serial port in the computer, and b- z are
used to specify additional ports.
portname symbol If actual portnames are used, the symbol is the name given by the Operating
System to your port. The print to the serial object (see above) can be used to
create a list of available portnames and alphabetic shortcuts. If the port chosen is
currently in use or unavailable when the serial object is instantiated, an error
message will be displayed and the object will not function. If no port is specified,
the default port is a.
rate int opt An optional argument may be used after the port name or alphabetic shortcut to
specify the baud rate of the serial port (the default rate is 4800 baud). Any value is
allowable (although not all ports can be set to all baud rates). Some common rates
are 300, 600, 1200, 1800, 2400, 3600, 7200, 9600, 19200, 38400, 57600 and
115200.
data int opt After the baud rate, the next arguments specifies the number of data bits for the
serial port (the default is 8 data bits). Other possible values are 5, 6 and 7.
stop int opt The next argument specifies the number of stop bits for the serial port. The default
is 1. Other possible values are 1.5 (Windows only) and 2.
parity int or symbol opt The next argument specifies the parity for the serial port (the default is no parity,
specified by 0 or no).Other possible values are odd, 1 (odd), even, and 2 (odd).

Messages
bang Sends each character received on the serial port since the last bang message out
the serial object's left outlet as an integer in the order that the characters were
received. Before output data is sent, the message read, followed by a number
specifying the number of bytes received is sent out the right outlet of the serial
object.
int input [int] Sends the number out the serial port accessed by the serial object. Numbers
outside the range 0-255 are wrapped to that range using a modulo operator. After
the data is sent, the message write, followed by a number specifying the number
of bytes sent is sent out the right outlet of the serial object.
float input [float] Converted to int.
list input [list] Sends each number in the list out the serial port, in order. Numbers outside the
range 0-255 are wrapped to that range using a modulo operator. After the data is
sent, the message write, followed by a number specifying the number of bytes sent
is sent out the right outlet of the serial object.
break Sends a break command to the serial port used by the serial object. After the
break has completed, the message break is sent out the object's right outlet.
close Closes an open serial connection, permitting use of the serial port by other
applications.
getport Sends the name or shortcut of the currently open serial port out the serial object's
right outlet, prepended by the word port.
port port [list] The word port, followed by a symbol, specifies the serial port to be used by the
object. If alphabetic shortcuts are used, a specifies the first logical serial port in
the computer. b - z specify additional ports. If actual portnames are used, the
symbol is the name given by the operating system to your port. See the print
message, above, for a way to list available portnames and alphabetic shortcuts. If
the port chosen is currently in use or unavailable when the port message is sent,
an error message will be displayed and the object will revert to its previously
chosen port, or won't function if there was none.
print Sends a list of available serial ports to the Max window, along with their alphabetic
shortcuts. The message port [portname] [portname]... is also sent from the
object's right outlet, with a list of available ports.
open Opens a new serial connection.
refresh Refreshes the list of known/available serial ports. See the print message for
additional information.
reset (Mac only) Resets the currently open serial port using the Basic Stamp
initialization sequence.

Attributes
Name Type g/s Description
autoopen int Toggles automatically opening the serial port.
baud int Sets the port's baud rate.
'300' = TEXT_HERE
'1200' = TEXT_HERE
'2400' = TEXT_HERE
'4800' = TEXT_HERE
'9600' = TEXT_HERE
'14400' = TEXT_HERE
'19200' = TEXT_HERE
'28800' = TEXT_HERE
'38400' = TEXT_HERE
'57600' = TEXT_HERE
'115200' = TEXT_HERE
bufsize int Sets the input buffer size used by the serial object.
chunk int Sets the data chunk size (data list length) for output.
databits int Sets the number of data bits (acceptable values are 5, 6, 7, or 8).
'5' = TEXT_HERE
'6' = TEXT_HERE
'7' = TEXT_HERE
'8' = TEXT_HERE
drain int (Mac only) Toggles drain enable. When enabled, communication waits until all
data has been transmitted to the terminal when writing. The default value is 0
(disabled).
dtr int Enables or disables the DTR (data terminal ready) function of the serial port used
by the serial object.
parity int Sets the parity for the port. The options are:

0: no parity
1: odd
2: even
'no' = TEXT_HERE
'odd' = TEXT_HERE
'even' = TEXT_HERE
serport int Used by the object Inspector only. Users should use the port message.
'Bluetooth-PDA-Sync' = TEXT_HERE
'Bluetooth-Modem' = TEXT_HERE
stopbits int Sets the number of stop bits used when communicating with the serial port.
'1' = TEXT_HERE
'2' = TEXT_HERE
xonxoff int Enables Xon/Xoff serial flow control.

Information for box attributes common to all objects

Output
(serial output): When a number or list is received in its inlet, serial sends the data out the specified serial port at the current
baud rate.
int: When serial receives a bang message and characters have been received in the serial port, the received characters are sent as
numbers in the order they were received.
list: When serial receives a bang message, characters have been received in the serial port, and chunking is enabled, the received
characters are sent as a list in the order the characters were received. The length of the list is determined by the argument to the
chunk message (see the message listing for chunk for more information).

Out right outlet: Reports error and status messages.

Examples

When the button is clicked, this patch resets the modem, begins polling for a response, and stops polling when a response has
been received

See Also
Name Description
match Watch for a message match, then output the message
spell Convert input to ASCII codes
vdp Control a videodisk player through a serial port
Max Comm Tutorial 2: Serial Max Comm Tutorial 2: Serial Communication
Communication
setclock
Create and control an alternative clock

Description
Allows the creation of alternatives to the standard millisecond clock. This includes several modes of timing that change timing
activities. Each setclock is associated with a name (its first argument), and this name may be passed as the argument to a "clock"
message to numerous objects that use timing in Max, such as metro, line, and pipe.

Arguments
Name Units Type Opt Description
name symbol Obligatory. The first argument is the name of the setclock object, by which timing
objects such as clocker, line, metro, pipe, and tempo can refer to the setclock.
Those timing objects -- once they have received the message clock followed by the
name of a setclock object -- use that setclock as their timing source instead of
Max's regular millisecond clock. The setclock object need not be in the same
patcher as the timing objects that refer to it. More than one setclock object may
exist with the same name; setclock objects with the same name share the same
clock time information. (Note: Different setclock objects that share the same
name argument can have different mode arguments typed in, but they will in fact
operate with the mode of whichever setclock was first loaded with that name.
Thus, setclock objects with the same name but different modes may behave
unpredictably, since the order in which they are loaded by Max is often unknown.)

The second (optional) argument describes the mode of clock operation this
setclock object will have. The possible modes for the second argument are:
mode symbol The word pass specifies passive mode. In this mode, the setclock object's current
clock time is set by a number received in the left inlet, and associated timing
objects will follow that clock time just as if it were a regularly progressing
millisecond clock. If no second argument is present, the mode is pass by default.

The word add specifies additive mode. A number received in the left inlet is added
to the current clock time to determine the new clock time.

The word mul specifies multiplicative mode. The number received in the left inlet
is used as a factor by which all associated timing objects will modify their time
settings. For example, a factor of 2.0 will cause all timing objects that are using
the setclock as their clock source to double their time values (that is, to halve
their speed). An alternative (and perhaps more truthful) way to conceptualize the
behavior of mul mode is to think of the incoming float as a divisor by which
setclock divides the speed at which its own clock time progresses. Thus, when it
receives the number 2.0 it divides its own clock speed by 2.0, causing the objects
which are following that clock to progress twice as slowly.

The word interp specifies interpolate mode. The number received in the left inlet
is gradually added to the current time of setclock, over a time period determined
by the amount of time elapsed since the previous number was received. During
that time period, setclock linearly interpolates to set its clock to the intermediate
values.
multiplier float If the second argument is mul, an optional third argument specifies a multiplier
for the time of all associated timing objects. If no third argument is present, the
multiplier is 1.0 by default.

Messages
bang In left inlet: Sends out the current time value, according to the setclock object's
own clock. Timing objects such as clocker, line, metro, pipe, and tempo can use
setclock as their clock source instead of Max's regular millisecond clock.
int timing [int] In left inlet: The meaning of the number depends on the second typed-in
argument, which identifies the setclock object's mode of operation. If the mode is
pass [ive] (the default mode), the number sets an absolute clock time which
timing objects may use by comparing it to their initial time value. If the mode is
add [itive], the number is added to the setclock object's current clock time. If the
mode is interp [olate], setclock will change its clock time incrementally by that
amount, over a time period determined by the time elapsed since the previous
number was received. (However, negative numbers cause an immediate decrease
in the clock time.) If the mode is ext [ernal], the number is simply ignored. If the
mode is mul [tiplicative], the number is used as a multiplier for associated timing
objects. For instance the number 0.5 halves the rate of increase (speed) of the
associated timing objects.

In right inlet: Sets the time interval, in milliseconds, at which the setclock will
report its clock information to associated timing objects. The default is 5
milliseconds.
float timing [float] Performs the same function as int.
(inlet1) interval [int] In right inlet: Sets the time update interval.
clock clock name [symbol] The word clock, followed by a word, specifies the name of the name of the
setclock object, by which timing objects such as clocker, line, metro, pipe, and
tempo can refer to the setclock.
(mouse) Double-clicking with the mouse will print status messages in the Max window.
set interval [float] The word set followed by a number of milliseconds sets the timing interval at
which the object will report its clock information to associated timing objects. The
information is reported to those associated objects immediately.
reset interval [float] The word reset followed by a number of milliseconds sets the timing interval at
which the object will report its clock information to associated timing objects. The
information is reported whenever the next report is due according to the set
interval.

Information for box attributes common to all objects

Output
int: When bang is received in the left inlet, setclock sends its current time reading out the outlet.

Examples

setclock becomes the clock for metro... setclock modifies the time for clocker

See Also
Name Description
clocker Report elapsed time, at regular intervals
metro Output a bang message at regular intervals
timer Report elapsed time between two events
<<
Bit shift to the left

Description
Shifts all bit values to the left. This has the effect of multiplying a number by a power of two, but is less expensive in computer
time.

Arguments
Name Units Type Opt Description
initial-value int opt Sets an initial value for the number of bits by which to shift leftward.

Messages
bang In left inlet: Performs the bit-shift with the numbers currently stored. If there is
no argument, << initially holds 0 as the number of bits by which to shift.
int input [int] In left inlet: All bits of the number, in binary form, are shifted to the left by a
certain number of bits. The resulting number is sent out the outlet.
(inlet1) amount-of-bitshift [int] In right inlet: The number is stored as the number of bits to left-shift the number
in the left inlet.
float input [float] See the int listing.
set set-input [int] Sets input to the object without causing output (bang will output it).
list input [int] In left inlet: The first number is bit-shifted to the left by the number of bits
shift-amount [int] specified by the second number.

Information for box attributes common to all objects

Output
int: The number in the left inlet is bit-shifted to the left by a certain number of bits. The number of bits by which to shift is
specified by the number in the right inlet. The output is the resulting bit-shifted number.

Examples

Same effect as multiplying by a power of 2

See Also
Name Description
* Multiply two numbers
>> Bit shift to the right
>>
Bit shift to the right

Description
Shifts all bit values to the right. This has the effect of dividing a number by a power of two, but is less expensive in computer
resources.

Arguments
Name Units Type Opt Description
initial-value int opt Sets an initial value for the number of bits by which to shift rightward.

Messages
bang In left inlet: Performs the bit-shift with the numbers currently stored. If there is
no argument, >> initially holds 0 as the number of bits by which to shift.
int input [int] In left inlet: All bits of the number, in binary form, are shifted to the right by a
certain number of bits. The resulting number is sent out the outlet.
(inlet1) shift-amount [int] In right inlet: The number is stored as the number of bits to right-shift the
number in the left inlet.
float input [float] See the int listing.
set set-input [int] Sets input to the object without causing output (bang will output it).
list input [int] In left inlet: The first number is bit-shifted to the right by the number of bits
shift-amount [int] specified by the second number.

Information for box attributes common to all objects

Output
int: The number in the left inlet is bit-shifted to the right by a certain number of bits. The number of bits by which to shift is
specified by the number in the right inlet. The output is the resulting bit-shifted number.

Examples

Same effect as dividing by a power of 2

See Also
Name Description
!/ Divide input from a number
<< Bit shift to the left
sin
Sine function

Description
Use the sin object to calculate and output the sine of any given number.

Arguments
Name Units Type Opt Description
initial-value float or int opt Sets the initial value for the sine function.

Messages
bang Calculates the sine of the number currently stored. If there is no argument, sin
initially holds 0.
int input [int] Input to the sine function in radians
float input [float] Input to the sine function in radians

Information for box attributes common to all objects

Output
float or int: The sine of the input in radians.

Examples

See Also
Name Description
asin Arc-sine function
asinh Hyperbolic arc-sine function
sinh Hyperbolic sine function
Max Basic Tutorial 11: Procedural Max Basic Tutorial 11: Procedural Drawing
Drawing
sinh
Hyperbolic sine function

Description
Use the sinh object to calculate and output the hyperbolic sine of any given number.

Arguments
Name Units Type Opt Description
initial-value float or int opt Sets the initial value for the hyperbolic sine function.

Messages
bang Calculates the hyperbolic sine of the number currently stored. If there is no
argument, sinh initially holds 0.
int input [int] Input to the hyperbolic sine function
float input [float] Input to the hyperbolic sine function

Information for box attributes common to all objects

Output
float: The hyperbolic sine of the input.
int: The hyperbolic sine of the input.

Examples

See Also
Name Description
asin Arc-sine function
asinh Hyperbolic arc-sine function
sin Sine function
slide
Smooth values logarithmically

Description
Filters an input value logarithmically between changes. It's particularly useful for envelope following and lowpass filtering to
smooth a stream of continuous data.

Arguments
Name Units Type Opt Description
slide-up float opt Specifies the slide up value. The default is 1.
slide-down-value float opt A second argument specifies the slide down value. The default is 1.

Messages
bang Performs the same function as float using the last input value.
int input [int] Converted to float.
float input [float] In left inlet: An input value to be filtered. When a new value is received, object
filters an input value logarithmically between changes using the formula

y (n) = y (n-1) + ((x (n) - y (n-1))/slide)

A given sample output from slide is equal to the last value plus the difference
between the last value and the input divided by the slide value. Given a slide value
of 1, the output will therefore always equal the input. Given a slide value of 10, the
output will only change 1/10th as quickly as the input. This can be particularly
useful for lowpass filtering or envelope following.
(inlet1) input [float] In middle inlet: Specifies the slide up value to be used when an incoming value is
greater than the current value.
(inlet2) input [float] In right inlet: Specifies the slide down value to be used when an incoming value is
less than the current value.
set input [int] The word set followed by a number will set the current input value to the given
number without causing output (bang can be used to cause successive output).
reset Resets the current output sample to 0.

Information for box attributes common to all objects

Output
float: The filtered input value.

Examples

slide performs logarithmic smoothing of an input

See Also
Name Description
expr Evaluate a mathematical expression
Max Data Tutorial 2: Data Scaling Max Data Tutorial 2: Data Scaling
slider
Move a slider to output values

Description
Resembles a sliding potentiometer, outputting numbers restricted to a specified range, offset by a specified number, and
multiplied by a specified number.

Arguments
None.

Messages
bang Sends out the number currently stored in the slider.
int input [int] The number received in the inlet is displayed graphically by slider, and is passed
out the outlet. Optionally, slider can multiply the number by some amount and
add an offset to it, before sending it out the outlet.
float input [float] Converted to int.
(mouse) Clicking and dragging with the mouse causes will change the position of the slider
and send a number value out the object's outlet.
set input [list] The word set, followed by a number, resets the value displayed by the slider,
without triggering output.
setminmax values [list] The word setminmax, followed by two numbers, sets the low and high range
values for the slider object. The floatoutput attribute will automatically be set.

Attributes
Name Type g/s Description
bgcolor float Sets the slider background color in RGBA format.
bordercolor float Sets the slider border color in RGBA format.
floatoutput int Toggles floating-point output from the slider object. The default is 0 (off).
def.:0
knobcolor float Sets the slider knob color in RGBA format.
min float Sets value that will be added to the slider object's value before it is sent out the
def.:0. outlet.
mult float Multiplier
def.:1.
orientation int Sets the slider object to a horizontal or vertical data display.
def.:0 Automatic: (the default) sets the display dependent on the size of the slider -
longest side of the rectangle that describes the slider sets the orientation.
Horizontal
Vertical
'Automatic' = TEXT_HERE
'Horizontal' = TEXT_HERE
'Vertical' = TEXT_HERE
parameter_enable int Parameter mode enable or disable
relative int Sets the way that the slider object responds to mouse clicks. In relative mode (the
def.:0 default) the slider keeps its relative position when you click - Moving the mouse
outputs higher or lower values in relation to that relative position. In absolute
mode, the slider will automatically jump directly to the clicked location.
'Absolute' = TEXT_HERE
'Relative' = TEXT_HERE
size float Value range
def.:128.
Legacy
brgba list (3 ints) brgba is a legacy RGB alias for the bgcolor RGBA attribute. See here for more
information.
frgba list (3 ints) frgba is a legacy RGB alias for the knobcolor RGBA attribute. See here for more
information.
rgba2 list (3 ints) rgba2 is a legacy RGB alias for the bordercolor RGBA attribute. See here for
more information.

Information about attributes available for Parameter-aware objects

Information for box attributes common to all objects

Menu Items
Name Description
Color Choosing the Color... menu item from the Object menu when the object is
selected opens a color picker, permitting adjustment to the appearance of the
slider object.

Output
int: Numbers received in the inlet, or produced by dragging on slider with the mouse, are first multiplied by the multiplier, then
have the offset added to them, then are sent out the outlet.

Although the numbers that can be output by dragging are limited by the range of the slider, numbers received in the inlet are
not limited before they are sent out the outlet.

Examples

Produce output by dragging onscreen... or display numbers passing through

See Also
Name Description
dial Output numbers using an onscreen dial
kslider Output numbers from an onscreen keyboard
multislider Display data as sliders or a scrolling display
nslider Output numbers from a notation display
pictctrl Picture-based control
pictslider Picture-based slider control
rslider Display or change a range of numbers
Max Basic Tutorial 7: Numerical Max Basic Tutorial 7: Numerical User Interfaces
User Interfaces
speedlim
Limit the speed of message throughput

Description
Limit the throughput speed of incoming messages to a fixed time limit. The time can be specified in milliseconds or using a
tempo-relative interval.

Arguments
Name Units Type Opt Description
delta- int, float, opt Sets an initial minimum time between outputs. Time can be specified in any of the
time symbol time formats used in Max. If there is no argument, the minimum time is 0
milliseconds.

Messages
bang Performs the same function as an anything message applied to the passing of
bang messages.
int input [int] In left inlet: Performs the same function as an anything message applied to the
passing of integers.

In right inlet: The number is stored as the minimum amount of time, in


milliseconds, between successive outputs.
float input [float] Performs the same function as an anything message applied to the passing of
floats..
list input [list] In left inlet: Performs the same function as an anything message applied to the
passing of lists.
In right inlet: A list may be used to specify time in one of the Max time formats.
anything input [list] In left inlet: The message is passed out the outlet, provided that a certain
minimum time has elapsed since the previous output. Otherwise, the message is
held until that amount of time has passed (or until it is overwritten by another
incoming message).

Attributes
Name Type g/s Description
defer float Turn this on to send output in the low-priority queue.
quantize atom Send output only on the specified time-boundary if appropriate. This is achieved
by making internal adjustments to the times used for sending output. The
quantization can be specified in the following time formats: bars.beats.units, ticks
or note values.
threshold atom Time threshold under which only one message may pass. Time can be specified in
any of the time formats used in Max.

Information for box attributes common to all objects

Output
anything: A message received in the left inlet is sent out the outlet, provided the specified minimum amount of time has elapsed
since the previous output. Otherwise, speedlim waits until that amount of time has passed, then sends out the last message it
has received since the previous output.

Examples
Used to reduce a heavy flow of numbers, or to turn a continuous flow into discrete steps

See Also
Name Description
delay Delay a bang
mousefilter Gate messages with the mouse
thresh Combine messages when received close together
timer Report elapsed time between two events
transport Control a master clock
Max MIDI Tutorial 3: MIDI Parsing Max MIDI Tutorial 3: MIDI Parsing
spell
Convert input to ASCII codes

Description
Accepts a numeric stream and outputs and outputs ASCII characters. Options arguments provide for forced-length messages.

Arguments
Name Units Type Opt Description
size int opt Sets the minimum output size. Any input that doesn't "spell" to the minimum
length is followed by enough fill characters (the default is the space character, 32
in ASCII) to satisfy the minimum requirement.
character int opt Specifies the fill character to use instead of 32. If you want to use '0' as a fill
character, use any negative number as a second argument to spell.

Messages
int input [int] The ASCII value of each of the digits of the number is sent out the outlet, one digit
at a time.
list input [list] Each int in the list is converted to ASCII as described above, and a space character
(32) is sent out between items in the list. Any float or symbol items in the list are
ignored.
anything input [list] If the message begins with a symbol, all int and symbol items in the message are
converted to ASCII one character at a time, and a space character (32) is placed
between them. Any float items in the list are ignored. If the message begins with a
float, both floats and symbols are ignored.
symbol input [symbol] The ASCII value of each letter, digit, or other character in the symbol is sent out
the outlet, one character at a time.

Information for box attributes common to all objects

Outputs
int: The ASCII representation of the input is sent out one character at a time.

Examples

Using the spell object, a modem command string or a synthesizer patch name can be translated from human terms into
computer terms, and sent out the serial port in ASCII representation

See Also
Name Description
atoi Convert ASCII characters to integers
itoa Convert integers to ASCII characters
key Report keyboard presses
keyup Report key information on release
message Send any message
sprintf Format a message of words and numbers
split
Look for a range of numbers

Description
Check if input can fall within a specified range. If it falls within that range, it sends the number out the left outlet and if it does
not, then it sends the number out the right outlet.

Arguments
Name Units Type Opt Description
minimum int or float The first argument sets the minimum value to be sent out the left outlet. If the first
argument is an int, then the split object will convert all float values to ints.
maximum int or float The second argument sets the maximum value to be sent out the left outlet. If the
first argument to split is an int, the output is int. If it is float, the output is float.
This is true regardless of the type of the input.

Messages
int input [int] In left inlet: If the number is within a specified range, it is sent out the left outlet.
Otherwise, it is sent out the right outlet.

In middle inlet: The number is stored as the minimum value in the range of
numbers looked for by split. If the number is an int, then the split object will
convert all float values to ints.

In right inlet: The number is stored as the maximum value in the range of
numbers looked for by split.
float input [float] In left inlet: If the number is within a specified range, it is sent out the left outlet.
Otherwise, it is sent out the right outlet.

In middle inlet: The number is stored as the minimum value in the range of
numbers looked for by split. If the number is an int, then the split object will
convert all float values to ints.

In right inlet: The number is stored as the maximum value in the range of
numbers looked for by split.

Information for box attributes common to all objects

Output
int: If the number received in the left inlet is greater than or equal to the specified minimum, and it is less than or equal to the
specified maximum, it is sent out the left outlet. Otherwise, it is sent out the right outlet.

Examples
Used to divert a certain range of numbers to a different destination

See Also
Name Description
route Select outlet based on input matching
select Output bangs based on input matching
<= Compare numbers as less than or equal to
>= Compare numbers for greater than or equal to condition
Max Basic Tutorial 19: Timing Max Basic Tutorial 19: Timing
spray
Distribute a value to a numbered outlet

Description
Accepts lists as input, where the first number is taken as the outlet number, and one or more values that follow are sent out that
outlet and those to its right, in right-to-left order. The argument sets the number of outlets (there is no set limit). The default
number of outlets is 2.

Arguments
Name Units Type Opt Description
outlets int opt The first argument sets the number of outlets. If there is no argument present, the
object has two outlets.
offset int opt The second argument sets an offset for the numbering of the outlets. If the second
argument is not present, the outlets are numbered beginning with 0.

Messages
int input [int] Posts an error-message in the Max window stating that spray requires a list.
list input [list] The first number in the list is a number that specifies the outlet number; the
second is an int or float value to send out that outlet. If there are additional
elements in the list, they are sent out the subsequent outlets to the right of the one
specified by the first number in the list. The list may contain only ints or floats;
symbols will be ignored.
offset shift [int] The word offset followed by a number will offset the output of the object by the
number of outlets given shifted to the left (a negative number will specify the
number of outlets offset to the right).

Information for box attributes common to all objects

Output
int: When a list of is received by spray, the first number is used to specify an outlet, and the second int or float is sent out that
outlet. Any additional numbers in the list are sent out subsequent outlets to the right.

Examples

Used to break up a list and send the items out specific outlets

See Also
Name Description
cycle Round-robin messages to outlets
funnel Tag data with its inlet number
gate Pass input to an outlet
listfunnel Index and output list elements
route Select outlet based on input matching
unjoin Break a list into messages
unpack Break a list into individual messages
sprintf
Format a message of words and numbers

Description
Uses the common C-language "printf" function inside Max. You can combine symbols, organize lists of numbers, or format
messages or menu items. For complete documentation, refer to a standard C library reference manual.

Arguments
Name Units Type Opt Description
symout symbol opt If the first argument is the word symout, the sprintf object outputs the string it
generates as a single symbol. Otherwise the output is a list of symbols and/or
numbers. The word symout itself is not included in the output of sprintf.
format symbol The arguments form a message to be sent out, in a format resembling the C
programming language. The arguments may be words, numbers, or changeable
arguments for incoming symbols (%s), ints (%ld), floats (%f), and ints that are to
be formatted as ASCII characters (%c). The number of inlets is determined by the
number of changeable arguments, with each inlet corresponding to a changeable
argument, in order.

Messages
bang In left inlet: Formats the message using the values currently stored.

Any of the above messages in the left inlet will format the message and send it out.
If no value has been received for a changeable number argument (%ld or %f), 0 will
be substituted for that argument. If no value has been received for a %s or %c
argument, that argument will be left blank.
int input [int] May be received in any inlet that corresponds to a %ld or %c argument. The
number will be stored in place of that argument. A %c argument will convert the
int to its ASCII character equivalent.
float input [float] May be received in any inlet that corresponds to a %f argument. The number will
be stored in place of that argument.
list input [list] In left inlet: Each item in the list is treated as if it had been received in a separate
inlet, up to the number of inlets.
anything input [list] Performs the same function as a list.
symbol input [symbol] May be received in any inlet that corresponds to a %s argument. The number will
be stored in place of that argument.

Information for box attributes common to all objects

Output
anything: The message specified by the typed-in argument(s) is formatted and sent out with substitutions made for the
changeable arguments.

Examples
Changeable arguments are replaced by values received in the inlets

See Also
Name Description
atoi Convert ASCII characters to integers
combine Combine multiple items into a single symbol
fromsymbol Convert a symbol into numbers/messages
itoa Convert integers to ASCII characters
key Report keyboard presses
keyup Report key information on release
message Send any message
regexp Use regular expressions to process input
spell Convert input to ASCII codes
tosymbol Convert messages, numbers, or lists to a single symbol
sqrt
Square root function

Description
Calculates and outputs the square-root of any given number.

Arguments
Name Units Type Opt Description
initial int or float opt An optional argument specifies the value whose square root is to be output.

Messages
bang Outputs the currently stored square root value.
int input [int] A given number will cause the object to output the square root of that number. A
negative input has no real solution, so it causes an output of NaN (Not a Number).
float input [float] A given number will cause the object to output the square root of that number. A
negative input has no real solution, so it causes an output of NaN (Not a Number).

Information for box attributes common to all objects

Output
float: The square root of the input.

Examples

See Also
Name Description
expr Evaluate a mathematical expression
standalone
Configure parameters for standalone applications

Description
The standalone object lets you set options for creating a standalone application from a Max patch, and is used in conjunction
with the Build Application/Collective... item found in the Edit menu. You should only have one standalone object in your top-
level patch.

Arguments
None.

Attributes
Name Type g/s Description
allwindowsactive int Controls the initial setting of All Windows Active when the standalone is
launched.
audiosupport int Causes Max to copy all audio drivers and other supporting files over to your
standalone.
cantclosetoplevelpatchers int When selected, this option renders it impossible to close the top-level patcher in
the standalone you build.
database int Database
extensions int When checked, the contents of the Cycling '74 extensions folder (located in the
Max application folder) will be included in your standalone.
midisupport int When checked, MIDI drivers and other supporting files required to use MIDI will
be included in your standalone.
noloadbangdefeating int When a patch is opened, the action of the loadbang object can be disabled if you
hold down the Command and Shift keys (Macintosh) or Control and Shift keys
(Windows). When checked, this option will make your standalone always perform
loadbang actions regardless of the state of the keyboard.
overdrive int Controls the initial setting of Overdrive when the standalone is launched.
preffilename symbol If you want to use your own preferences file to save default settings for your
standalone application instead of the default Max Preferences file, you can specify
the file name by entering it in the text box.
searchformissingfiles int When checked, Max will use the search path to look for files that are not included
in the collective inside your standalone. The primary reason to disable searching
for missing files is to test your standalone to see if it includes all the necessary files
to work if you move it to another machine.
statusvisible int Status window flag
usesearchpath int When checked, the standalone will create a search path consisting of all subfolders
of the folder containing the application. Leaving this option unchecked is
primarily of interest to Mac users, who might wish to put their standalone into the
Applications folder, but avoid the startup cost of adding all the subfolders of the
Applications folder to the search path. On Windows, the application is inside its
own folder, so there usually are an insignificant number of subfolders to worry
about.

Information for box attributes common to all objects

Examples
See Also
Name Description
stripnote
Filter out note-off messages

Description
Only pass note-on messages: those having any velocity above 0.

Arguments
None.

Messages
int pitch [int] The incoming number is treated as a pitch value. If the velocity value currently
held by stripnote is not 0, then the velocity is sent out the right outlet and the
pitch is sent out the left outlet.
(inlet1) velocity [int] In right inlet: The number is stored as a velocity to be paired with pitch numbers
received in the left inlet.
float pitch [float] Converted to int.
(inlet1) velocity [float] Converted to int.

Information for box attributes common to all objects

Output
int: Out left outlet: The pitch value received in the left inlet is sent out, provided the velocity is not 0.

Out right outlet: The velocity value of a note-on pair is sent out, provided it is not 0.

Examples

Repeated pitch values and 0 velocities caused by note-off messages can be filtered out

See Also
Name Description
makenote Generate a note-on/note-off pair
sustain Hold note-off messages for release
Max MIDI Tutorial 2: MIDI Note Max MIDI Tutorial 2: MIDI Note Management
Management
strippath
Separate filename from a full pathname

Description
Removes path information from a complete file path. strippath also tells you whether the resulting filename is in the search path
or not.

Arguments
None.

Messages
anything filepath [symbol] An absolute pathname as a symbol. An absolute pathname looks like this:

"MyDisk:/Max Folder/extras/filename"

Information for box attributes common to all objects

Output
int: Out right outlet: If the file was found within the current Max search path a 1 is sent out the right outlet. A 0 is sent
otherwise.
symbol: Out left outlet: The file name, with all path information preceding it removed.

Examples

strippath removes path information from a file pathname, and leaves the name of the file

See Also
Name Description
absolutepath Convert a file name to an absolute path
conformpath Convert file paths styles
dropfile Interface for file drag and drop
opendialog Open a dialog to ask for a file or folder
relativepath Convert an absolute to a relative path
savedialog Open a dialog asking for a filename
substitute
Substitute symbols within a message

Description
Matches messages to its own arguments; whenever it finds a match, will make the appropriate substitution.

Arguments
Name Units Type Opt Description
match anything opt The first number or symbol specifies the match, which identifies what should be
replaced in an incoming message. The default match value is 0.
replacement anything opt The second number or symbol specifies the replacement for the match. The default
replacement value is 0.
mode anything opt Any third number or symbol sets the "replace first message only" mode of the
substitute object. Only the first instance of the specified match will be replaced.

Messages
bang Same as anything.
int input [int] Same as anything.
float input [float] Same as anything.
list input [list] Same as anything.
anything input [list] In left inlet: The input is echoed to the output, but if the message received contains
an element matching the match symbol or number, the element is replaced by the
replacement symbol or number when the message is repeated to the output.

In right inlet: The substitute object accepts a message of two numbers or symbols
in its right inlet. The first number or symbol specifies the match, which identifies
what should be replaced in an incoming message.
set input [list] In left inlet: Same as anything.
In right inlet: Same as anything, except that the word set is ignored.

Information for box attributes common to all objects

Output
anything: Out left outlet: The input message is echoed to the output with elements matching the match symbol or number
replaced by the replacement number or symbol.
bang: Out right outlet: If no substitution occurred when sending out the incoming message, the original input message is passed
out the rightmost outlet.

Examples

substitute can translate messages output by one object to what's expected by another object

See Also
Name Description
route
Select outlet based on input matching
sprintf Format a message of words and numbers
zl Process lists in many ways
suckah
Get a pixel from the display

Description
Creates a click-able area that returns an RGB color, or can accept any screen coordinates to get the RGB values of that pixel.

Arguments
None.

Messages
list screen-x [int] A list of two integers specifying x and y offset values from the upper left corner of
screen-y [int] the screen will cause the suckah object to report the color at the specified screen
location in RGB format.
(mouse) Clicking on the suckah object causes it to report the color of the pixel at the
current mouse position to be reported in RGB format (i.e., as a list of three ints).

Attributes
Name Type g/s Description
boundmode int When enabled, the suckah object will only output color values within the bounds
def.:0 of the object's box. Coordinates outside of the object's bounds will be ignored.
compatibility int Toggles the output of the suckah object in old-style integer values in the range 0-
def.:0 255 (0) or Max 5 0.-1.0 floating-point values (1).
outputalpha int Toggles the output of 3-element RGB lists (0) or 4-element RGBA lists that
def.:1 include alpha channel values (1).

Information for box attributes common to all objects

Output
list: A list of three ints corresponding to the RGB value of the pixel selected by using the mouse or in response to a list of x and y
offsets will be sent out the suckah object's outlet.

Examples

See Also
Name Description
route Select outlet based on input matching
sprintf Format a message of words and numbers
zl Process lists in many ways
Tutorial 10: Chromakeying Tutorial 10: Chromakeying
suspend
Reports when application is suspended or resumed

Description
Reports Mac OS suspend/resume events. The behavior is emulated on Windows.

Arguments
None.

Information for box attributes common to all objects

Output
int: Out left outlet When the application is suspended (made to go into the background), a 1 is output. When the application is
resumed (restored to being in the foreground), a 0 is output.

Examples

suspend lets you activate/deactivate processes if Max is the foreground application

See Also
Name Description
active Send 1 when patcher window is active, 0 when inactive
gestalt Retrieve system information
sustain
Hold note-off messages for release

Description
Holds any notes with velocities of 0 until instructed to release them. This provides for sustain pedal-like behavior when working
with incoming MIDI notes.

Arguments
None.

Messages
int input [int] In left inlet: The number is the pitch value of a pitch-velocity pair. If the velocity
value currently held by sustain is not 0, then the pair is sent out immediately. If
the velocity is 0, the note-off is either sent out or held, depending on whether
sustain is turned on.
In middle inlet: The number is stored as a velocity to be paired with pitch
numbers received in the left inlet.
In right inlet: If the number is not 0, sustain is turned on, and all note-offs are
held. If the number is 0, sustain is turned off, and all note-offs are sent out
immediately.
float input [float] Converted to int.
list note/velocity pair [list] In left inlet: A two-item list consisting of a note-velocity pair can be input.
clear Clears the sustain object's internal memory. No note-off messages are output.
flush Output all held note-offs.

Attributes
Name Type g/s Description
repeatmode int Sets the behavior mode for handling repeated note-on messages. There are three
modes of behavior:

repeatmode 0: (Historical way) Playing the same note multiple times will not
retrigger the played note when the sustain pedal is pressed or after a sustain 1
message is received. This is the default state of the object.
repeatmode 1: (Re-trigger) Playing the same note multiple times will send a note
off message and retrigger the played note no matter what its sustain state is. The
sustain object will also keep track of the notes to stop when the sustain pedal is
released or a sustain 0 message is received.
repeatmode 2: (Stop last) Playing the same note multiple times will cause the
sustain object to keep a count of the number of times the note has been played,
holding and sending the accumulated note off messages when the sustain pedal is
released or a sustain 0 message is received.
'Historical Way' = TEXT_HERE
'Re-Trigger' = TEXT_HERE
'Stop Last' = TEXT_HERE
sustain int Enables (1) or disables (0) sustain mode. Setting this attribute or sending the
message sustain 1 or sustain 0 is equivalent to pressing or releasing the sustain
pedal.

Information for box attributes common to all objects

Output
int: Out left outlet: The pitch value of a pitch-velocity pair.

Out right outlet: The velocity value of a pitch-velocity pair.


Note-on pairs are always sent out immediately. If sustain is turned on, note-offs are held until it is turned off. Otherwise, note-
offs are sent out immediately.

Examples

Like the sustain pedal of a piano, sustain releases all held notes at one time

See Also
Name Description
flush Output MIDI note-offs for held notes
makenote Generate a note-on/note-off pair
stripnote Filter out note-off messages
swap
Swap position of two numbers

Description
Swaps the values of its inlets, preserving right-to-left ordering. The first outlet type is determined by its argument. The second
outlet's type is always an int.

Arguments
Name Units Type Opt Description
initial number opt Sets an initial value for the number which is to be sent out the left outlet. If there
is no argument, the initial value is 0. If there is an int argument or no argument,
an int is sent out the left outlet. (The number sent out the right outlet is always a
int.)

Messages
bang In left inlet: Swaps and sends out the numbers currently stored in swap.
int input [int] The number is sent out the right outlet, then the number in the right inlet is sent
out the left outlet.
(inlet1) input [int] The number is stored to be sent out the left outlet when a number is received in
the left inlet.
float input [float] The numbers are converted to int, unless there is a float argument, in which case
the number received in the right inlet is stored as a float.
(inlet1) input [float] The number is stored to be sent out the left outlet when a number is received in
the left inlet.
list left [number] In left inlet: The numbers are stored in swap. The first number is sent out the
right [number] right outlet, then the second number is sent out the left outlet.

Information for box attributes common to all objects

Output
float: If there is a float argument, the number sent out the left outlet is a float.
int: When a number is received in the left inlet, the number in each inlet is sent out the opposite outlet.

Examples

Numbers are sent out in reverse order from that in which they were received

See Also
Name Description
buddy Synchronize arriving data
fswap Swap position of two numbers
join Combine items into a list
pack Create a list
unjoin Break a list into messages
unpack Break a list into individual messages
Max Basic Tutorial 17: Data Max Basic Tutorial 17: Data Structures And Probability
Structures And Probability
swatch
Select and display RGB colors

Description
Provides 2-dimensional selection and display of colors, representing hue along the horizontal axis and luminance along the
vertical axis. A third color dimension, saturation, may be set by means of the saturation message.

Arguments
None.

Messages
bang bang message causes output of the RGBA values of the current color at the
selected (x,y) position on the 2-dimensional colorspace, taking into account the
current saturation value.
int red [int] In left inlet: A number between 0 and 255 sets the red color component and
triggers RGBA output.

Note: Unlike most Max objects, input to any one of the three inlets will re-calculate
the current color location on the swatch, and trigger output.
(inlet1) green [int] In middle inlet: A number between 0 and 255 sets the green color component and
triggers RGBA output.

Note: Unlike most Max objects, input to any one of the three inlets will re-calculate
the current color location on the swatch, and trigger output.
(inlet2) blue [int] In right inlet: A number between 0 and 255 sets the blue color component and
triggers RGBA output.

Note: Unlike most Max objects, input to any one of the three inlets will re-calculate
the current RGBA color location on the swatch, and trigger output.
float red [float] Converted to int.
(inlet1) green [float] Converted to int.
(inlet2) blue [float] Converted to int.
list red [int] A list of three numbers between 0 and 255 sets the three RGB color components
green [int] (red, green, blue), refreshes the display and causes RGBA output.
blue [int]
alpha opacity [float] The word alpha, followed by a floating-point number between 0 and 255, will set
the RGBA alpha (opacity) value.
hsl hue [int] The word hsl, followed by a list of three numbers between 0 and 255, sets the
saturation [int] color based on the given hue (x-axis), saturation, and luminance (y-axis) values.
luminance [int] The swatch object converts these values to RGBA color values, refreshes the
display, and causes output of the RGBA values.
(mouse) Clicking and dragging on the swatch object will calculate and output the RGBA
color at the selected (x, y) position on the 2-dimensional (hue-luminance)
colorspace, taking into account the current saturation value.
saturation saturation [number] The word saturation, followed by a number between 0 and 255 will change the
color saturation of the displayed 2-dimensional (hue, lightness) colorspace. It will
also re-calculate the new RGBA color at the selected (x, y) position and cause
output.
set red [int] The word set, followed by a list of three numbers between 0 and 255 sets the three
green [int] RGB color components (red, green, blue) and refreshes the display without causing
blue [int] RGBA output.
sethsl hue [int] The word sethsl, followed by a list of three numbers between 0 and 255, sets the
saturation [int] color based on the given hue (x-axis), saturation, and luminance (y-axis) values
luminance [int] and the refreshes the display. Unlike the hsl message the sethsl message does not
output the corresponding RGBA values.

Attributes
Name Type g/s Description
compatibility int Toggles the output of the swatch object in old-style integer values in the range 0-
def.:0 255 (0) or Max 5 0.-1.0 floating-point values (1).
parameter_enable int Parameter Mode Enable

Information about attributes available for Parameter-aware objects

Information for box attributes common to all objects

Output
int: Out right outlet: the current saturation value (calculated from an RGB list input, or output directly after a saturation
message)
list: Out left outlet: a list of three RGB (red, green, blue) color values

Examples

See Also
Name Description
colorpicker Select and output a color
panel Colored background area
Max JS Tutorial 3: JavaScript Max JS Tutorial 3: JavaScript Tasks, Arguments, and Globals
Tasks, Arguments, and Globals
switch
Accept messages from a specific inlet

Description
Arguments
Name Units Type Opt Description
inlets int opt Specifies the number of inlets, in addition to the leftmost inlet. If there is no
argument, there are two additional inlets.
initial int opt An optional second argument can be used to specify which inlet is initially open.
The default is 0 (i.e., none).

Messages
bang In left inlet: Sends out the number of the open inlet, or 0 if all inlets are closed.
int inlet [int] In left inlet: The number specifies an open inlet for receiving subsequent messages
to be sent out the outlet. All inlets other than the designated open one are closed.
If the number is 0, all inlets are closed.
float inlet [float] In left inlet: Converted to int.

Information for box attributes common to all objects

Output
anything: If the number in the left inlet is less than 0, its absolute value is used to determine which inlet to open. (-1 opens inlet
1, -2 opens inlet 2, etc.) If the absolute value of the number is greater than the number of existing inlets, messages are received
in the rightmost inlet.

Examples

'Listen' to only one inlet at a time, or ignore all inlets

See Also
Name Description
forward Send messages to specified receive objects
funnel Tag data with its inlet number
gate Pass input to an outlet
ggate Send input to one of two outlets
gswitch Select output from two inlets
receive Receive messages without patch cords
router Route messages to multiple locations
send Send messages without patch cords
Max Basic Tutorial 21: Max Basic Tutorial 21: Controlling Data Flow
Controlling Data Flow
sxformat
Prepare MIDI system exclusive messages

Description
Accepts, as arguments, a list of numbers which are sent out sequentially. In addition, you may use one or more "expr"-style
statements, which start with the word "is", which will be evaluated with the result being sent out. "is" statements need to be
separated by slashes.

Arguments
Name Units Type Opt Description
SysEx list Obligatory. The arguments are a list of numbers which represent the values of
individual bytes of a MIDI system exclusive message. The first number should be
240 (or 0xF0), the system exclusive status byte and the last number should be
247 (or 0xF7), the end byte. There can be any number of values for data bytes in
between.

Arguments for data bytes can also be in the form of a mathematical expression
(like the expressions in expr and if objects) to be evaluated before numbers are
sent out the outlet. The expressions can contain changeable arguments in the form
$i, followed immediately by an inlet number (for example, $i2). The changeable
arguments are replaced by numbers received in the specified inlet. Expressions
used in place of numbers should be preceded by the word is, and should be
separated from other arguments with a slash (/) on either side of the expression
(see example).

If the value of an evaluated expression is less than 0, no number is sent out in


place of that expression. This allows you to send variable-length system exclusive
messages.

Messages
bang In left inlet: Sends out the bytes of the formatted message, using the most recently
received numbers.
int input [int] In left inlet: The number replaces any $ i1 arguments in the object box, and the
entire list of arguments is evaluated and sent out the outlet, one-by-one.
(inlet1) input [int] In any other inlet besides left: The number is stored in place of the $i argument
that corresponds to that inlet, until a number is received in the left inlet.
(inlet2) input [int] In any other inlet besides left: The number is stored in place of the $i argument
that corresponds to that inlet, until a number is received in the left inlet.
(inlet3) input [int] In any other inlet besides left: The number is stored in place of the $i argument
that corresponds to that inlet, until a number is received in the left inlet.
(inlet4) input [int] In any other inlet besides left: The number is stored in place of the $i argument
that corresponds to that inlet, until a number is received in the left inlet.
(inlet5) input [int] In any other inlet besides left: The number is stored in place of the $i argument
that corresponds to that inlet, until a number is received in the left inlet.
(inlet6) input [int] In any other inlet besides left: The number is stored in place of the $i argument
that corresponds to that inlet, until a number is received in the left inlet.
(inlet7) input [int] In any other inlet besides left: The number is stored in place of the $i argument
that corresponds to that inlet, until a number is received in the left inlet.
(inlet8) input [int] In any other inlet besides left: The number is stored in place of the $i argument
that corresponds to that inlet, until a number is received in the left inlet.
(inlet9) input [int] In any other inlet besides left: The number is stored in place of the $i argument
that corresponds to that inlet, until a number is received in the left inlet.
list input [list]
In left inlet: The numbers in the list are used to replace the corresponding $i
arguments in the object box, then the list of arguments is evaluated and the
numbers are sent out one-by-one.

Information for box attributes common to all objects

Output
int: When a number is received in the left inlet, any expressions in the argument are evaluated and the numbers in the list are
sent out one at a time, as bytes of a MIDI system exclusive message, for transmission by midiout.

Examples

sxformat can send a complete MIDI system exclusive message, byte-by-byte, to midiout

See Also
Name Description
expr Evaluate a mathematical expression
midiout Transmit raw MIDI data
sysexin Receive MIDI system exclusive messages
sysexin
Receive MIDI system exclusive messages

Description
Receives MIDI system exclusive messages from a MIDI input device. It takes an optional argument for port selection. If a MIDI
system exclusive message is received, sysexin outputs raw MIDI as integers.

Arguments
Name Units Type Opt Description
port symbol opt Specifies the port (a-z) from which to receive incoming MIDI system exclusive
messages. If there is no argument, sysexin receives from port a (or the first input
port listed in the MIDI Setup dialog.)

Messages
anything port [list] Performs the same function as port but without need for the word, "port".
(mouse) Double-clicking on a sysexin object shows a pop-up menu for choosing a MIDI
port or device.
(MIDI) The sysexin object receives its input from a MIDI sysex message received from a
MIDI input device.
port port [symbol] The word port, followed by a letter a-z or the name of a MIDI input port or
device, sets the port from which the object receives incoming MIDI messages. The
word port is optional and may be omitted.

Information for box attributes common to all objects

Output
int: MIDI system exclusive messages received from the specified port are sent out the outlet, byte-by-byte.

Examples

Examine incoming System Exclusive messages

See Also
Name Description
midiin Output raw MIDI data
sxformat Prepare MIDI system exclusive messages
tab
Select values with tabs or multiple buttons

Description
The tab can be used to create multiple button and multiple column displays and interfaces.

Arguments
None.

Messages
bang bang message will retrigger the object's output.
int tab [int] The number specifies a tab item to be sent out, and causes tab to display that item
and send the index out the first outlet and the tab text out the second outlet. The
items are numbered starting at 0. A tab can also be chosen with the mouse.
float tab [float] Converted to int.
(mouse) Clicking on a tab button will highlight and set the selection and send the index out
the first outlet and the tab text out the second outlet.
next Selects the next index to the tab object and causes tab to display that item and
send the new index out the first outlet and the tab text out the second outlet. If the
last index is currently displayed, it wraps around to the first index.
prev Selects the previous index to the tab object and causes tab to display that item
and send the new index out the first outlet and the tab text out the second outlet. If
the first index is currently displayed, it wraps around to the last index.
set tab [list] The word set, followed by a number, specifies a tab item to be selected, and causes
tab to display that item, but does not cause any output.
setsymbol tab [list] The word setsymbol, followed by a symbol that specifies a tab item, causes tab to
display that item but does not send output.
symbol tab name [list] The word symbol, followed by a symbol that specifies a tab item, causes tab to
display that item and send the index out the first outlet and the tab text out the
second outlet.

Attributes
Name Type g/s Description
activesafe int When set to one, protects the currently active tab from text truncation.
def.:1
border int Sets the thickness, in pixels, of the object's border.
def.:0
bordercolor float Sets the border color in RGBA format.
borderoncolor float Sets the border color when a tab is clicked on in RGBA format.
button int Toggles button mode for the tab object.
def.:0
clicktabcolor float Sets the color when a tab is clicked on in RGBA format.
clicktextcolor float Sets the text color when a tab is clicked on in RGBA format.
gradient float Gradient
def.:0.
hovertabcolor float Sets the tab color displayed on mouseover in RGBA format.
hovertextcolor float Sets the text color displayed on mouseover in RGBA format.
htabcolor float Sets the tab color for selected items in RGBA format.
htextcolor float Sets the text color for selected tab items in RGBA format.
margin int Sets the text margin, in pixels, for tab text.
def.:4
mode int Sets the text tab layout mode. The modes are:
def.:0
0 separate tab entries are equally spaced. This is the default.
1 separate tab entries are proportionally spaced according to the text.
Note: to add multiple words, use the backslash before a space (e.g. "one\ down")
'Equal Spaced' = TEXT_HERE
'Proportional' = TEXT_HERE
multiline int Toggles allowing multiple lines of text in a tab. When set, you can resize the object
def.:1 to create multicolumn displays.
parameter_enable int Parameter Mode Enable
rounded float Sets the radius, in pixels for the tab object.
def.:14.
segmented int Segmented
def.:0
spacing_x float Sets the horizontal spacing for the tab object in pixels.
def.:4.
spacing_y float Sets the vertical spacing for the tab object in pixels.
def.:4.
tabcolor float Sets the tab color for unselected items in RGBA format.
tabs symbol Sets the tab text for each tab in the tab object.
def.:one two three
textcolor float Sets the text color for the tab object when the tab is unselected in RGBA format.
truncate int Sets the text truncation mode. Alignment modes are:
def.:1 0 no truncation
1 truncate from the right (e.g. abcdef... . This is the default
2 truncate from center (e.g. abcd...wxyz
'No truncation' = TEXT_HERE
'Truncate from the right' = TEXT_HERE
'Truncate from the middle' = TEXT_HERE
valign int Sets the vertical alignment mode. The modes are:
def.:1
0: Top
1: Center
2: Bottom
'Top' = TEXT_HERE
'Center' = TEXT_HERE
'Bottom' = TEXT_HERE

Information about attributes available for Parameter-aware objects

Information for box attributes common to all objects

Menu Items
Name Description
Color Choosing the Color... menu item from the Object menu when the object is
selected opens a color picker, permitting adjustment to the appearance of the tab
object.

Examples
The tab object can be used to create multiple column button/toggle displays and interfaces

See Also
Name Description
matrixctrl Matrix switch control
pictctrl Picture-based control
pictslider Picture-based slider control
textbutton A user interface button/toggle
ubutton Send a bang with a transparent button
table
Store and edit an array of numbers

Description
Arguments
Name Units Type Opt Description
name symbol opt The argument gives a name to the table. Max looks for a file of the same name to
load. If two or more table objects share the same names, they also share the same
values.

Messages
bang Same as a quantile message with a random number between 0 and 32,768 as an
argument. See the quantile message for more details.
int index [int] Retrieves the number by address from the table, and sends if out the left outlet.
(inlet1) value [int] Stores the value at the next index number received at the left inlet.
float index [float] Convert to int
list index [int] The second number is stored in at the address (index) specified by the first
value [int] number.
clear Set all values to 0
const value [int] Fill the table with a number
(mouse) The values stored in table can be entered and edited graphically with the mouse.
When a table object is first created in a patcher window, the table objects graphic
editing window is opened, and values can be entered by drawing with the mouse.
The editing window provides a palette of graphic editing tools. When the patcher
window is locked, the graphic editing window can be opened by double-clicking
with the mouse on the table object.
dump Sends all the numbers stored in the table out the left outlet in immediate
succession, beginning with address 0.
cancel Causes table to ignore a number received in the right inlet, so that the next
number received in the left inlet will output a number, rather than storing a
number at that address.
fquantile multiplier [float] Given a number between zero and one, multiplies the number by the sum of all the
numbers in the table. Then, table sends out the address at which the sum of the all
values up to that address is greater than or equal to the result.
getbits address [int] Gets the value of one or more specific bits of a number stored in the table, and
start [int] sends that value out the left outlet. The first argument is the address to query; the
bits [int] second argument is the starting bit location in the number stored at that address
(the bit locations are numbered 0 to 31, from the least significant bit to the most
significant bit); and the third argument specifies how many bits to the right of the
starting bit location should be sent out. The specified bits are sent out the outlet as
a single decimal integer.
goto index [int] Sets a pointer to the address specified by the number. The pointer is set at the
beginning of the table initially.
flags save-with-patcher [list] Changes the table objects saving options as found in the Inspector. The first
dont-save [list] argument affects the Save with Patcher option, and the second argument affects
the Dont Save option. If the argument is zero the option is unchecked, otherwise it
is checked.
inv value [int] Finds the first value which is greater than or equal to that number, and sends the
address of that value out the left outlet.
length Output the table size
max Retrieve the maximum stored value
min Retrieve the minimum stored value
load Places the table in load mode. In load mode, every number received in the left inlet
gets stored in the table, beginning at address 0 and continuing until the table is
filled (or until the table is taken out of load mode by a normal message). If more
numbers are received than will fit in the size of the table, additional numbers are
ignored.
open Opens the objects graphic editor window and brings it to the foreground. Double-
clicking on the table object in a locked patcher has the same effect.
next Sends the value stored in the address pointed at by the pointer out the left outlet,
then sets the pointer to the next address. If the pointer is currently at the last
address in the table, it wraps around to the first address.
normal Takes the table out of load mode and reverts it to normal operation. See the load
message for more details.
quantile number [int] Multiplies the incoming number by the sum of all the numbers in the table. This
result is then divided by 2^15 (32,768). Then, table sends out the address at which
the sum of all values up to that address is greater than or equal to the result.
prev Causes the same output as the next message, but the pointer is then decremented
rather than incremented. If the pointer is currently at the first address in the
table, it wraps around to the last address.
set start [int] Stores values in certain addresses. The first argument specifies an address. The
values [list] next number is the value to be stored in that address, and each number after that
is stored in a successive address.
setbits address [int] Changes the value of one or more specific bits of a number stored in the table. The
start [int] first argument is the address being referred to; the second argument is the starting
count [int] bit location in the number stored at that address (the bit locations are numbered 0
value [int] to 31, from the least significant bit to the most significant bit); the third argument
specifies how many bits to the right of the starting bit location should be modified,
and the fourth argument is the value (stated in decimal or hexadecimal form) to
which those bits should be set.
sum Output the sum of all values
read filename [symbol] Opens and reads data values from a file in Text or Max binary format. Without an
argument, read opens a standard Open Document dialog to choose a file. If the
file contains valid data, the entire contents of the existing table are replaced with
the file contents.
send receive-name [symbol] Sends the value stored at the incoming address to all receive objects with that
address [int] name.
refer name [symbol] Sets the receiving table object to read its data values from the named table.
wclose Close the graphic editing window
write Opens a standard save file dialog for choosing a name to write data values from
the table. The file can be saved in Text or Max binary format.

Attributes
Name Type g/s Description
embed int Toggles the ability to embed the table and save its data as part of the main patch.
def.:1 The default behavior is 1 (save the data).
name symbol Specifies the name of a table. You can also specify the name of a table object using
an argument. Max looks for a table of the s ame name which has been saved as a
separate file. If two or more table objects share the same names, they also share
the same values.
notename int Toggles Y axis display using MIDI note names.
def.:0
parameter_enable int Parameter Mode Enable
range int Specifies the range of values which can be displayed on the y axis of the editing
window. A newly created table has a range of 128, from 0 to 127.
signed int Toggles the ability to store and display signed integer values. A newly created table
def.:0 with signed values has a range of 128, from -128 to 127.
size int Specifies the number of values stored in the table. The default is 128 values,
indexed with numbers from 0 to 127.

Information about attributes available for Parameter-aware objects

Information for box attributes common to all objects

Output
bang: When the contents of a table have been changed by an edit in the graphic editing window, bang is sent out the right
outlet.
int: All numbers sent out by table are sent out the left outlet.

Examples

An array of any size and range can be stored, recalled, and modified

See Also
Name Description
capture Store values to view or edit
coll Store and edit a collection of data
funbuff Store pairs of numbers
histo Create a histogram of numbers received
itable Graphic display of a table
multislider Display data as sliders or a scrolling display
text Format messages as a text file
Max Basic Tutorial 17: Data Max Basic Tutorial 17: Data Structures And Probability
Structures And Probability
tan
Tangent function

Description
Use the tan object to calculate and output the tangent of any given number.

Arguments
Name Units Type Opt Description
initial-value float or int opt Sets the initial value for the tangent function.

Messages
bang Calculates the tangent of the number currently stored. If there is no argument, tan
initially holds 0.
int input [int] Input to the tangent function
float input [float] Input to the tangent function

Information for box attributes common to all objects

Output
float: The tangent of the input.
int: The tangent of the input.

Examples

See Also
Name Description
atan Arc-tangent function
atan2 Two-variable arc-tangent function
atanh Hyperbolic arc-tangent function
tanh Hyperbolic tangent function
tanh
Hyperbolic tangent function

Description
Use the tanh object to calculate and output the hyperbolic tangent of any given number.

Arguments
Name Units Type Opt Description
initial-value float or int opt Sets the initial value for the hyperbolic tangent function.

Messages
bang Calculates the hyperbolic tangent of the number currently stored. If there is no
argument, tanh initially holds 0.
int input [int] Input to the hyperbolic tangent function
float input [float] Input to the hyperbolic tangent function

Information for box attributes common to all objects

Output
float: The hyperbolic tangent of the input.
int: The hyperbolic tangent of the input.

Examples

See Also
Name Description
atan Arc-tangent function
atan2 Two-variable arc-tangent function
atanh Hyperbolic arc-tangent function
tan Tangent function
tempo
Output numbers at a metronomic tempo

Description
Produces metronomic output controllable in beats per minute, and with specifiable whole-note divisions.

Arguments
Name Units Type Opt Description
tempo int or float opt The first argument sets an initial tempo, from 5 to 300 beats per minute. If there
is no argument, the initial tempo is 120 beats per minute. The second argument is
the beat multiplier and is set to 1 by default. The third argument sets an initial
rhythmic value of the output, from a whole note (1) to a 64th note triplet (96). If
the argument is not present, the initial value is 16.

Messages
bang In left inlet: Starts the tempo object's metronome process, or restarts it if tempo
is already on.
int input [int] Converted to float.
float input [float] In left inlet: If the number is not 0, it has the same effect as bang. If the number is
0, it has the same effect as stop.

In 2nd inlet: The number is stored as the tempo, in beats per minute (quarter
notes per minute).

In 3rd inlet: The number is a beat multiplier, which can lengthen the amount of
time taken for one beat. It slows the tempo down by a factor. For example, a
multiplier of 2 will make tempo send out its output half as fast.

In right inlet: The number is the rhythmic value sent out by tempo, specified as a
fraction of a whole note. For example, the number 8 causes tempo to output
eighth notes, relative to the specified (quarter note) tempo. The numbers sent out
the outlet cycle continuously between 0 and the number 1 less than the rhythmic
value. The divisions of a whole note must be between 1 and 96.
clock name [symbol] The word clock, followed by the name of an existing setclock object, sets the
tempo object to be controlled by that setclock object rather than by Maxs
internal millisecond clock. The word clock by itself sets the tempo object back to
using Maxs regular millisecond clock.
stop In left inlet: Stops tempo.
tempo tempo [list] In left inlet: The word tempo, followed by a float, sets the current tempo to the
number.

Information for box attributes common to all objects

Output
int: When tempo is started it outputs numbers in a continuous cycle from 0 to the number 1 less than the specified rhythmic
value. The speed at which the numbers are sent out is determined by the tempo (quarter note beats per minute) and the
rhythmic value of the output (fraction of a whole note).

Examples
The tempo (60) defines the speed of a quarter note, division defines the pulse to be sent out

See Also
Name Description
clocker Report elapsed time, at regular intervals
metro Output a bang message at regular intervals
setclock Create and control an alternative clock
Max MIDI Tutorial 4: MIDI Basic Max MIDI Tutorial 4: MIDI Basic Sequencing
Sequencing
text
Format messages as a text file

Description
Collects and formats incoming messages as text to be output as lines of text.

Arguments
Name Units Type Opt Description
filename symbol Names a text file to be read in when the object is loaded.

Messages
int input [int] Stores the integer within text.
float input [float] Stores the float within text.
list input [list] Stores the list within text.
anything input [list] The message is stored in the text object, placed after any previously stored
messages, and is followed by a space.
clear Erases the contents of text.
cr Puts a carriage return at the end of the contents of text, to start a new line. If the
last character in text is a space, the carriage return replaces that space.
(mouse) Double-clicking with the mouse on the text object (when the patcher window is
locked) opens an editing window in which the contents of text can be viewed and
edited. The text object ignores messages to change its text while the editing
window is open. Unlike the capture object, changes made in the editing window
of text actually alter the contents of the object.
dump The word dump causes text to send its contents out of the object's left outlet.
editwith editor [symbol] The word editwith, followed by a symbol that specifies a text editor, will open the
file for editing using the specified editor.
filetype filetype-code (four letters) The word filetype, followed by a symbol, sets the file types which can be read and
[symbol] written into the text object. File types are specified using the standard four-letter
type code combination (e.g. filetype ffoo). The message filetype with no arguments
restores the default file behavior -- either Max binary or text file formats. File
types are mapped to filename extensions on Windows based on the messages to
max contained in the file max-fileformats.txt in the init folder, which is loaded on
startup. If you are defining your own filetype, you may want to include your own
text file in the init folder in order to specify a mapping between an extension and
your four-letter type code.
line index [int] The word line, followed by a number, causes text to send out the contents of that
line number (up to 256 characters) with the word set prepended (for setting the
contents of a message box). Lines are numbered beginning with 1; any line
number message less than 1 is converted to line 1. If a nonexistent line number is
requested, nothing is sent out.
open Opens the object's text window for editing. Double-clicking on the text object in a
locked patcher has the same effect. The text object ignores messages to change its
text while the editing window is open. Unlike the capture object, changes made in
the editing window of text actually alter the contents of the object.
read filename [symbol] The word read, followed by a symbol that specifies a filename, will read the
contents of a text file. If no filename or pathname is specified, the read message
will call up the standard Open Document dialog box, so that a text file can be
specified. Use the filetype message to use a custom filetype with this object.
query The word query sends a number that specifies the number of lines stored in the
text object out the object's right outlet.
t_symbol input [symbol] Stores the symbol within text.
tab Puts a tab stop at the end of the contents of text. If the last character in text is a
space, the tab stop replaces that space.
settitle window-name [symbol] The word settitle, followed by any word, sets the title of the text window. If you
want more than one word to appear as the default text, you must enclose the
words in double quotes or precede the spaces with a backslash (\).
symbol any symbol [symbol] The word symbol, followed by any word, stores that word at the end of the
contents of text. This is useful if you want to store a word that would otherwise be
understood as a specific message by text. For example, symbol clear stores the
word clear, followed by a space, at the end of the contents of text, rather than
erasing the contents.
wclose Closes the window associated with the text object.
write filename [symbol] The word write, followed by a symbol that specifies a filename, will save the
contents of text as a text file in the current default folder unless the file is
specified with an absolute pathname. If no filename or pathname is specified, the
write message will open up a standard Save As dialog box, so that the contents of
text can be saved in a separate text file. Use the filetype message to use a custom
filetype with this object.

Information for box attributes common to all objects

Output
bang: Out middle outlet: When a file has finished loading in response to a read message, a bang is sent out the middle outlet.
int: Out right outlet: In response to a query message, a number corresponding to the number of lines of text stored in the text
object is sent out the right outlet.
symbol: Out left outlet: When a line message is received, the text of the specified line number is sent out preceded by the word
set. The message can be used to set the contents of a message box (or can be sent to any other object for which that particular
set message is appropriate).

Examples

Collect messages as text, to paste elsewhere or to save as a separate file

See Also
Name Description
capture Store values to view or edit
filein Read and access a file of binary data
itable Graphic display of a table
spell Convert input to ASCII codes
sprintf Format a message of words and numbers
table Store and edit an array of numbers
textedit Enter text within a patcher
textbutton
A user interface button/toggle

Description
Arguments
None.

Messages
bang The behavior depends on the current mode settings.

mode 0 (button): A bang message will re-trigger the object's output.

mode 1 (trigger): A bang message will switch the object's state and trigger the
output.
int input [int] If the mode attribute is set to 0 (button), a bang is sent out the left outlet, and the
text message is displayed and set out the middle outlet.

If the mode attribute is set to 1 (toggle), and the number input is 1, textbutton is
set to 'on', a 1 is sent out the left outlet and the texton message is displayed and set
out the middle outlet.
If the number input is 0, textbutton is set to 'off', a 0 is sent out the left outlet and
the text message is displayed and set out the middle outlet.
float input [float] At float message is converted to int. See the int listing for usage.
(mouse) If the mode attribute is set to 0 (button), a mouse click on textbutton highlights it
for as long as the mouse is held down, sending a bang out the left outlet when the
mouse button is pressed down, and another bang out the left outlet when the
mouse button is released. The button text is also sent out the middle outlet on
mouse click.

If the mode attribute is set to 1 (toggle), and the initial state of the toggle is 0,
textbutton is set to 'on', a 1 is sent out the left outlet and the texton message is
displayed and set out the middle outlet.
If initial state of the toggle is 1, textbutton is set to 'off', a 0 is sent out the left
outlet and the text message is displayed and set out the middle outlet.
set set-input [int] If the mode attribute is set to 1 (toggle), the set message toggles the on or off state
without sending anything out the outlets. The word set, followed by any non-zero
number, sets toggle to on; set 0 sets it to off.
setsymbol button-text-item [list] If the mode attribute is set to 1 (toggle), the word setsymbol, followed by either
the texton or text symbol, causes the textbutton to display that symbol, but does
not cause any output. The symbol is case-sensitive.
symbol button-text-item [list] If the mode attribute is set to 1 (toggle), the word symbol, followed by either the
texton or text symbol, causes textbutton to display that symbol, switch to the
toggle state, and trigger the corresponding output.

Attributes
Name Type g/s Description
active int When active mode is set to 0, the textbutton object will not respond to mouse
def.:1 clicks, and the object is grayed out. This attribute is enabled by default.
align int Sets the text alignment.
def.:1 'Left' =
'Center' = TEXT_HERE
'Right' =
bgcolor float Sets the background color of the textbutton object when the button is in the "off"
state in RGBA format.
bgoncolor float Sets the background color of the textbutton object when the button is in the "on"
state in RGBA format.
bgovercolor float Sets the background color for the textbutton object on mouseover when the
button is in the "off" state in RGBA format.
bgoveroncolor float Sets the background color for the textbutton object on mouseover when the
button is in the "on" state in RGBA format.
blinktime int Specifies the duration (in milliseconds) that the textbutton object will flash when
def.:150 it is clicked upon or receives a bang message.
border int Sets the thickness, in pixels, of the textbutton object's border
def.:2
bordercolor float Sets the border color for the textbutton object when the button is in the "off"
state in RGBA format.
borderoncolor float Sets the border color for the textbutton object when the button is in the "on" state
in RGBA format.
fontlink int Toggles setting the size of the button to the currently selected font size and
def.:0 character width.
mode int Sets the button mode.
def.:0 'Button' =
'Toggle' =
outputmode int Sets the output mode. Output modes are:
def.:1
0: Send output on mouse down
1: Send output on mouse up (default)
'Mouse down' = TEXT_HERE
'Mouse up' = TEXT_HERE
parameter_enable int Parameter Mode Enable
rounded float Sets the amount in pixels by which to round the textbutton shape.
def.:14.
spacing_x float Sets the horizontal spacing for the textbutton object in pixels.
def.:4.
spacing_y float Sets the vertical spacing for the textbutton object in pixels.
def.:4.
text atom Sets the button label, and sets the the "off" state label when mode is set to 1
def.:Button (toggle).
textcolor float Sets the text color for the textbutton object when the button is in the "off" state in
RGBA format.
texton atom Text &quot;On&quot; Label
def.:Button On
textoncolor float Sets the text color for the textbutton object when the button is in the "on" state in
RGBA format.
textovercolor float Sets the text color for the textbutton object on mouseover when the button is in
the "off" state in RGBA format.
textoveroncolor float Sets the text color for the textbutton object on mouseover when the button is in
the "on" state in RGBA format.
tosymbol int Output as One Symbol
def.:1
truncate int Sets the text truncation mode. Alignment modes are:
def.:1
0: no truncation
1: truncate from the right (e.g. abcdef... . This is the default.
2: truncate from center (e.g. abcd...wxyz
'No truncation' = TEXT_HERE
'Truncate from the right' = TEXT_HERE
'Truncate from the middle' = TEXT_HERE
underline int The word underline, followed by a zero or one, toggles the underlining of text in
def.:0 the textbutton object. The default is 0 (no underlining).

Information about attributes available for Parameter-aware objects

Information for box attributes common to all objects

Menu Items
Name Description
Color Choosing the Color... menu item from the Object menu when the object is
selected opens a color picker, permitting adjustment to the appearance of the
textbutton object.

Examples

See Also
Name Description
matrixctrl Matrix switch control
message Send any message
pictctrl Picture-based control
pictslider Picture-based slider control
tab Select values with tabs or multiple buttons
ubutton Send a bang with a transparent button
textedit
Enter text within a patcher

Description
Provides a user interface within a patcher which can collect typed-in text from the computer-keyboard.

Arguments
None.

Messages
bang Outputs the typed or stored contents of the textedit object's buffer.
int input [int] Sets the contents of the textedit object's buffer while causing no output.
float input [float] Sets the contents of the textedit object's buffer while causing no output.
list input [list] Sets the contents of the textedit object's buffer while causing no output as long as
the list is comprised of numbers, otherwise, an error message is displayed.
(mouse) Clicking with the mouse on the textedit object (when the patcher window is
locked) will cause the textedit object to send either the letter or word selected out
its right outlet depending on the setting of the click mode (see the clickmode
message).
(typing) When the textedit object is highlighted, typing enters text into the text display
area and modifies its buffer, unless the object is set to read-only mode (see the
readonly message). The ASCII value of the character typed is sent out the middle
outlet.
append input [list] The word append, followed by a message, will append the message to the textedit
object's buffer without causing any output.
clear Erases the contents of the textedit object's buffer.
select Causes all text (if any) to be highlighted and sets the object to be the target of
keyboard events if the object is not in read-only mode.
set input [list] The word set, followed by any message, sets the contents of the textedit object's
buffer while causing no output.

Attributes
Name Type g/s Description
autoscroll int Toggles autoscrolling in the text display area. The message autoscroll 1 lets you
def.:1 scroll past the amount of text displayed in the textedit window when the number
of lines is set to 1 and the word wrapping is disabled (see the wordwrap message)
using either the cursor or by clicking and dragging in the textedit window. The
default is 0 (autoscroll disabled).
bangmode int When bangmode is set to "Bang Outputs Typed Text" (0 = default) then the
def.:0 textedit object will output the text currently being typed when banged. When set
to "Bang Outputs Entered Text" (1) then the textedit object will output the text
previously entered (will wait until text being typed is completed before sending the
new value).
'Bang Outputs Typed Text' = TEXT_HERE
'Bang Outputs Entered Text' = TEXT_HERE
bgcolor float Sets the background color of the textedit object in RGBA format.
border float Sets the size, in pixels, of the border of the textedit object. The default is 1.
def.:2.
bordercolor float Sets the border color of the textedit object in RGBA format.
clickmode int Sets the way that the textedit object responds to mouse clicks in the text display
def.:0 area. The message clickmode 0 will send an individual character clicked on out
the right outlet of the textedit object. Setting the object with the message
clickmode 1 will send the word the user clicks on. The default is 0 (select
characters).
'Output Character' = TEXT_HERE
'Output Word' = TEXT_HERE
keymode int Sets the way that the textedit object responds to carriage returns while typing
def.:0 characters into its text display area. The message keymode 0 allows for text input,
and displays carriage returns normally. Setting the object with the message
keymode1 causes the carriage return to output the entire contents of the current
buffer. The default is 0.
lines int Sets the number of lines in the textedit object display.
def.:0
outputmode int Sets whether the textedit object outputs its contents as a message (0) or as a
def.:0 single symbol (1). The message outputmode 0 causes the output of the object to
be sent out as messages. Setting the object with the message outputmode 1 will
output the buffer contents as a single symbol. The default is 0 (output as
messages).
parameter_enable int Parameter Mode Enable
readonly int Toggles the read only mode of the textedit object. The message readonly 1
def.:0 disables any user entry into the text box. Messages which operate on the current
contents of the textedit buffer such as clear, append, or separator are not
affected by the readonly message. The default is 0 (readonly mode off).
rounded float Sets the rounding radius, in pixels, for the corners of the textedit object.
def.:8.
separator symbol Designates a symbol as a line separator. and treats it as a carriage return when the
def.:nothing contents of the buffer are output. If the buffer contains the text "red green blue"
and the object receives the message separator green, the next bang received by
textedit will output red (carriage return) blue.
tabmode int Toggles the ability to cause the tab key to output the entire contents of the current
def.:1 buffer. The default is 1 (on).
wordwrap int Sets the way that the textedit object displays messages which are longer than the
def.:1 textedit display area. The message wordwrap 0 (default) will enable text
wrapping on word boundaries in the display area. The message clickmode 1
disables word-wrap.

Information about attributes available for Parameter-aware objects

Information for box attributes common to all objects

Output
symbol: Out left outlet: The currently stored contents of the textedit object's buffer preceded by the word text are output when
the object receives a bang message. If the textedit message has been set to enter text on a carriage return using the keymode 1
message, a carriage return will also output the typed text and the buffer contents.
symbol: Out middle outlet: The ASCII value of the typed key.
symbol: Out right outlet: The word or letter in the textedit object's text box that the user has clicked on.

Examples
Collect text to store in a coll object

See Also
Name Description
dialog Open a dialog box for text entry
jit.cellblock Two-dimensional storage and viewing
text Format messages as a text file
Max Comm Tutorial 3: UDP Max Comm Tutorial 3: UDP Networking
Networking
thispatcher
Send messages to a patcher

Description
Allows modification of a patcher window with Max messages.

Arguments
None.

Messages
anything message [list] See "Patcher Messages" and "Scripting Messages" discussion.
end Used internally.
savewindow flag [int] The word savewindow, followed by a non-zero number, means that any unusual
window settings caused by window flags messages to thispatcher will be saved
as part of the patch the next time the patch is saved. The message savewindow 0
means that changes to the window caused by window flags messages to
thispatcher will not be retained when the patch is saved; the prior patcher
window settings are saved. If no savewindow message has been received, the
patcher will be saved with a normal window appearance.

Information for box attributes common to all objects

Patcher Behavior and Display


The script message: The script message to thispatcher permits dynamic control over object creation, deletion, sizing and
positioning, and patching. The word script is followed by a keyword that indicates a function. Following the keyword are
arguments that specify what objects are to be affected by the message.

In the discussion of each script message that follows, the syntax indicates required arguments for the message after the keyword
in angle brackets. An example of each message is also provided.

A variable-name is a symbol that names either a new or existing object. You can set variable names by choosing Name... from the
Object menu, or with certain scripting messages such as new and select.

Patcher Messages
clean: The clean message resets the patch's dirty bit in the window so that you won't be asked to save changes in the patch.
dirty: The clean message is the opposite of the clean method; it sets the patch's dirty bit in the window.
dispose: *USE AT YOUR OWN RISK* - Closes the patcher or destroys the subpatcher that the thispatcher object is contained in.
front: The front message brings the window that contains the thispatcher object to the front. If the patcher is not open, the
message opens the patch and brings it to the front.
loadbang: The loadbang message will send the loadbang message to all objects in the patch - including the loadbang object
itself.
path: The path message will send the full pathname of the patcher that contains the thispatcher object out the right outlet of the
thispatcher object.
title: The title message, followed by a symbol, will change the title displayed in the patcher window.
write: The word write, followed by an optional symbol that specifies a filename, saves the patcher window with that filename to
disk. If no file name is specified, a standard File Dialog will be presented for the user to manually choose a file name.

Scripting Messages
bringtofront: Bring an object to the front of the layer it's currently in.

Syntax: script bringtofront <variable-name>

Example: script bringtofront visigoth


If visigoth is in the foreground layer, this message moves it to the front of the foreground layer. Otherwise it moves it to the front
of the background layer.
class: Assigns a variable name to the first instance of a specified class with matching arguments

Syntax: script class <variable-name> <class-name> <arguments (optional)>

Example: script class rubadub + 4

Assigns the name rubadub to the first instance found of + with argument 4 in the patcher.
connect: Connects two objects together with a patch cord

Syntax: script connect <outlet-variable-name> <outlet-index> <inlet-variable-name> <inlet-index>

Example: script connect fooboo 0 bobo 0

Connects the left outlet of the object with the variable name fooboo to the left inlet of the object with the variable name bobo.

Note: Adding the keyword hidden (e.g., script hidden connect fooboo 0 bobo 0) creates hidden connections.
connectcolor: Modify the color of an existing patch cord, setting it to one of Max's 16 standard colors.

Syntax: script connectcolor <outlet-variable-name> <outlet-index> <inlet-variable-name> <inlet-index> <color>

Example: script connectcolor rover 0 dover 2 12

Changes the color of the connection between the left outlet of the rover object with the 3rd inlet of the dover object to the color
stored at index 12.
delete: Deletes an object in a patcher window.

Syntax: script delete <variable-name>

Example: script delete footog

Deletes the object associated with the variable name footog.


disconnect: Disconnect two objects connected by a patch cord

Syntax: script disconnect <outlet-variable-name> <outlet-index> <inlet-variable-name> <inlet-index>

Example: script disconnect fooboo 0 bobo 0

This message undoes the connection between the left outlet of fooboo and the left inlet of bobo.
hidden: Specifies that an object (or connection) will be hidden when created.

Example: script hidden new footog toggle 101 93 15 0

Creates a hidden object associated with the variable name footog. The hidden keyword can also be used when specifying
connections between objects.
hide: Hide a visible object.

Syntax: script hide <variable-name>

Example: script hide visigoth

Hides the object named visigoth


ignoreclick: Set an object not to respond to mouse clicks.

Syntax: script ignoreclick <variable-name>


Example: script ignoreclick visigoth

Makes the object named visigoth ignore mouse clicks.


move: Move an object to an absolute position relative to the current top-left corner of a patcher window. Note that the 0,0 point
is underneath the icon bar.

Syntax: script move <variable-name> <top> <left>

Example: script move molly 0 100

Moves the object named molly to the left edge of the window, 100 pixels down from the top.
new: Creates a new object in a patcher window and gives it a name.

Syntax: script new <variable-name> <creation message>

Example: script new footog toggle 101 93 15 0

Creates a new toggle object 15 pixels square at 101 93 and assign it to the variable footog.

The format of the arguments (after the class name) to the script new message are based on the legacy Max file format.
newdefault: Creates a new named object with default properties in a patcher window.

Syntax: script newdefault <variable-name> <creation message>

Example: script newdefault thatgraph 10 10 filtergraph~

Creates a new filtergraph~ object at its default size at 10 10 and assign it to the variable thatgraph.

Example: script newdefault buffy 200 100 pack foo bar bap

Creates a new pack object instantiated with the arguments foo bar bap at 200 100 and assign it to the variable buffy.
nth: Assigns a variable name to the nth instance of a specified class

Syntax: script nth <variable-name> <class-name> <index>

Example: script nth yoyo toggle 1

Assigns the name yoyo to the first toggle found in the patcher.

The order of objects in a patcher is determined by the front-to-back ordering. Objects in back of the patcher that draw behind
other objects are first in the search order.
offset: Move an object a distance from its current position. Positive distances move the object down and to the right, negative
distances move it up and to the left.

Syntax: script offset <variable-name> <delta-x> <delta-y>

Example: script offset molly 30 -40

Moves the object named molly 30 pixels to the right and 40 pixels up.
offsetfrom: Move an object a set distance from another object.

Syntax: script offsetfrom <variable-name-to-move> <target-variable-name> <top-left-flag> <delta-x> <delta-


y>

The top-left-flag is 1 if the distance is relative to the top-left corner of the object, and 0 if it is relative to the bottom-right corner.

Example: script offsetfrom molly panther 1 -100 -120


Moves the object named molly 100 pixels to the left of the left side of the object named panther, and 120 pixels above the top of
the object named panther.
respondtoclick: Set an object to respond to mouse clicks.

Syntax: script respondtoclick <variable-name>

Example: script respondtoclick visigoth

Makes the object named visigoth respond to mouse clicks.


selected: Assigns a variable name to the first object found that is selected

Syntax: script selected <variable-name>

Example: script selected impo

Assigns the name impo to the first object found that is selected. Obviously this script message only works when the patcher is
unlocked, since no object can be selected in a locked patcher.

For all three connection messages described below, inlets and outlets are specified by index, with 0 denoting the leftmost inlet or
outlet. The first variable specified is the object whose outlet you are connecting or disconnecting and the second variable is the
one whose inlet you are connecting. Messages can then flow from outlet to inlet.
send: Send a message to an object. This message is the same as using a message box with a semicolon or a send object, but you
use the object variable name feature of scripting to specify the object that will receive the message -- using script send to
communicate with a named receive object does not work. The message can only be sent to an object within the patcher as the
thispatcher object receiving the script send message.

Syntax: script send <variable-name> <message>

Example: script send foobert 666

The object with the variable name foobert receives an int 666 message. If foobert were a number box, its displayed value would
change to 666.
sendbox: Send a message to an object box. This message is identical to send except that it sends the message to an object's box
rather than the object referred to by the box. There is currently only one object, bpatcher, in which the object and box are
different objects. The box is a bpatcher, and the object is a patcher. What can you tell a bpatcher to do? One example is the
boxborder message, which is equivalent to sending the border message to a thispatcher object in a patcher inside a bpatcher.
Peek inside the Inspector patch for bpatcher for other ideas.

Syntax: script sendbox <variable-name> <message>

Example: script sendbox bpbp boxborder 0

If bpbp names a bpatcher object, this script message would tell it not to draw its border.
sendtoback: Move an object to the back of the layer it's currently in.

Syntax: script sendtoback <variable-name>

Example: script sendtoback visigoth

If visigoth is in the foreground layer, this message moves it to the back of the foreground layer. Otherwise it moves it to the back
of the background layer. Note that objects that are "in the back" are the first objects to be found by the variable assignment
messages nth and class.
show: Show a hidden object.

Syntax: script show <variable-name>

Example: script show visigoth


Makes the object named visigoth visible.
size: Change an object's size. There are some objects that have restrictions on their size, but they generally do not protect
themselves against sizes they don't expect, so use this message with some caution. For instance the toggle object expects to be a
square. It may not draw properly if it's made into a rectangle.

Syntax: script size <variable-name> <width> <height>

Example: script size togipoo 30 30

Changes the object named togipoo to be 30 by 30 pixels.

Sending Messages to Objects

Output
symbol: Out right outlet: The full pathname of the folder or volume containing the patcher's file in response to the path message.
If the patcher has not been saved, there is no output.
window: Out left outlet: When the message window getsize is received, thispatcher sends out the words window size
followed by the screen coordinates (in pixels from the top left corner of the screen) of the left, top, right, and bottom limits of the
window. When the message window gettitle is received, the message window title or window notitle is sent out, depending on
whether the window has a title bar. When the message window getflags is received, thispatcher sends out the words window
flags followed by the visibility of the scroll bars and grow box (grow or nogrow), the close box (close or noclose), and the
zoom box (zoom or nozoom).

Examples

Automatic window control, file saving, or patcher reset are possible with thispatcher... Windows can have any size, location,
and appearance, set within the patch itself

See Also
Name Description
bpatcher Embed a subpatch with a visible UI
bgcolor Set background color
join Combine items into a list
pack Create a list
patcher Create a subpatch within a patch
pattrforward Send any message to a named object
pcontrol Open and close subwindows
pvar Connect to a named object in a patcher
sprintf Format a message of words and numbers
Max Interface Tutorial 1: Max Interface Tutorial 1: bpatchers
bpatchers
thresh
Combine messages when received close together

Description
Collects items into a list if they appear within a certain specifiable amount of time. Each time an item arrives, the time is reset.

Arguments
Name Units Type Opt Description
threshold int opt Sets an initial value for the threshold time. If no argument is present, the initial
value is 10 milliseconds.
threshold-time float opt Converted to int.

Messages
int input [int] In left inlet: Numbers are combined into a list if received within a certain time of
each other. When the time between incoming numbers is greater than the
specified threshold, the list is sent out the outlet, and a new list is started.
(inlet1) threshold [int] In right inlet: The number is stored as the time, in milliseconds, to wait before
sending out the compiled list of numbers. If no new number is received in the left
inlet within that time, the list is sent out and a new list is started.
float input [float] In left inlet: Numbers are combined into a list if received within a certain time of
each other. When the time between incoming numbers is greater than the
specified threshold, the list is sent out the outlet, and a new list is started.

In right inlet: The number is stored as the time, in milliseconds, to wait before
sending out the compiled list of numbers. If no new number is received in the left
inlet within that time, the list is sent out and a new list is started.
list input [list] In left inlet: The entire list is appended to the list stored in thresh.

Information for box attributes common to all objects

Output
list: Each number received in the left inlet is appended to a list stored by thresh. If a certain time passes without a new number
being received, thresh sends out the list and starts a new list.

Examples

If threshold time is exceeded without a new number being received, thresh sends out what it holds

See Also
Name Description
bondo
Synchronize a group of messages
buddy Synchronize arriving data
iter Break a list into individual messages
join Combine items into a list
pack Create a list
quickthresh Fast chord detection
zl Process lists in many ways
timepoint
Bang at a specific time

Description
Outputs a bang when the clock reaches a specific time. The clock has to be moving forward in order for the bang to be output.

Arguments
Name Units Type Opt Description
time int, float, symbol Sets the initial time at which to send a bang. Time can be specified in any of the
time formats used in Max. The bang will only be sent when the transport is
running.

Messages
int time [int] Set the time in ticks at which to trigger a bang.
float time [float] Set the time in ticks at which to trigger a bang.
list time [list] A list may be used to specify time in one of the Max time formats.
anything time [list] Set the time in any of Max's time units at which to trigger a bang.

Attributes
Name Type g/s Description
time atom Sets the initial time at which to send a bang. Time can be specified in any of the
time formats used in Max. The bang will only be sent when the transport is
running.
transport symbol The name of a transport with which to associate. By default the global transport is
used.

Information for box attributes common to all objects

Examples

See Also
Name Description
metro Output a bang message at regular intervals
translate Convert between different units of time.
transport Control a master clock
when Report the current transport time
timer
Report elapsed time between two events

Description
timer starts keeping time when a bang is sent to the left inlet. When a bang is sent to the right inlet, timer outputs the time
elapsed and resets the timer to zero. The right outlet can report elapsed time in milliseconds or one of the Max time format
options, with the exception of notevalues.

Arguments
None.

Messages
bang In left inlet: Starts or restarts the timer.

In right inlet: Sends out the time elapsed since the timer was started.
clock setclock-name [symbol] Use the clock message to specify a named setclock object for timing rather than
by Maxs internal millisecond clock. The word clock by itself sets the timer object
back to using Maxs regular millisecond clock.

Attributes
Name Type g/s Description
format symbol Set the time format to use for output (defult = milliseconds). Output may also be
specified in one of the Max time format options with the exception of notevalues.
'ticks' = TEXT_HERE
'ms' = TEXT_HERE
'bars.beats.units' = TEXT_HERE
'samples' = TEXT_HERE
'hz' = TEXT_HERE
'notevalues' = TEXT_HERE
'hh:mm:ss' = TEXT_HERE
transport symbol The name of a transport object with which to associate. By default, the global
transport is used. This is used in the output format conversion. The transport does
not need to be running for the conversion.

Information for box attributes common to all objects

Output
float: Out left outlet: When a bang is received in the right inlet, the time elapsed (in milliseconds) since the timer was started is
sent out the outlet.

Out right outlet: When a bang is received in the right inlet, the time elapsed (in the time format specified by the format
attribute) since the timer was started is sent out the outlet.

Examples
Report time between bang messages... A single event can report time, then restart timer

See Also
Name Description
clocker Report elapsed time, at regular intervals
cpuclock Retrieve the CPU time
delay Delay a bang
pipe Delay numbers, lists or symbols
setclock Create and control an alternative clock
transport Control a master clock
Max Basic Tutorial 19: Timing Max Basic Tutorial 19: Timing
*
Multiply two numbers

Description
Multiplies two numbers together, and outputs the result upon receiving input in the left inlet.

Arguments
Name Units Type Opt Description
initial int or float opt Sets the initial value, to be multiplied by a number received in the left inlet. A float
argument causes the numbers to be multiplied as floats.

Messages
bang Performs the multiplication with the numbers currently stored. If there is no
argument, * initially holds 0 as a multiplier.
int input [int] The number is multiplied by the number in the right inlet, and the result is sent
out the outlet.
(inlet1) multiplier [int] In right inlet: The number is stored for multiplication with a number received in
the left inlet.
float input [float] Converted to int before multiplication, unless * has a float argument.
set input [int] The word set, followed by a number, sets the inlet's input without causing output.
list input [list] In left inlet: The first number is multiplied by the second number, and the result is
sent out the outlet.

Information for box attributes common to all objects

Output
float: Only if there is an argument with a decimal point.
int: The product of the two numbers received in the inlets.

Examples

Multiplied as ints... Floats are truncated before multiplication... ...unless there is a float argument

See Also
Name Description
Max Basic Tutorial 6: Simple Max Basic Tutorial 6: Simple Math in Max
Math in Max
togedge
Report zero/non-zero transitions

Description
Output bangs for 0-to-1 transitions out the left outlet, and bangs the right outlet for 1-to-0 transitions. Outlets alternate output
when bangs are received.

Arguments
None.

Messages
bang Switches the value stored in togedge from 0 to non-zero, or vice versa, and
reports the change by sending a bang out one of the outlets.
int input [int] The number is stored in togedge. If it is not 0, and the previously stored number
was 0, togedge sends a bang out the left outlet. If the number is 0, and the
previously stored number was not 0, togedge sends a bang out the right outlet.
Otherwise, togedge sends no output.

Information for box attributes common to all objects

Output
bang: Out left outlet: If the stored value is changed from 0 to not 0.

Out right outlet: If the stored value is changed from not 0 to 0.

Examples

Used as a detector of on/off status, or to switch back and forth between two triggers

See Also
Name Description
change Filter out repetitions of a number
led Display on/off status
toggle Switch between off and on (0/1)
toggle
Switch between off and on (0/1)

Description
toggle sends a 0 as output when it is turned off and a 1 as output when it is turned on (when giving input, a non-zero number will
turn it on, a 0 will turn it off, and a bang will alternate the state of the toggle).

Arguments
None.

Messages
bang Switches toggle on if it is off; switches it off if it is on.
int input [int] The number is sent out the outlet. If the number is not 0, toggle displays an X,
showing it is on. If it is 0, toggle is blank, showing it is off.
float input [float] Converted to int. See int listing.
(mouse) A mouse click on toggle switches the object on if it is off and off if it is on.
set set-input [int] Switches the toggle on or off without sending anything out the outlet. The word
set, followed by any non-zero number, sets toggle to on; set 0 sets it to off.

Attributes
Name Type g/s Description
bgcolor float Sets the background color for the object in RGBA format.
bordercolor float Sets the border color of the object in RGBA format.
checkedcolor float Sets the "X" color for the object in RGBA format.
parameter_enable int Parameter Mode Enable

Information about attributes available for Parameter-aware objects

Information for box attributes common to all objects

Menu Items
Name Description
Color Choosing the Color... menu item from the Object menu when the object is
selected opens a color picker, permitting adjustment to the appearance of the
toggle object.

Output
int: A number received in the inlet is sent out the outlet. A bang or a mouse click sends 1 or 0 out the outlet, depending on
whether toggle is being turned on or off.

Examples

Used as an onscreen controller, or to display the on/off status of numbers passing through

See Also
Name Description
led Display on/off status
matrixctrl Matrix switch control
pictctrl Picture-based control
radiogroup Radio button/check box user interface
tab Select values with tabs or multiple buttons
textbutton A user interface button/toggle
togedge Report zero/non-zero transitions
ubutton Send a bang with a transparent button
Max Basic Tutorial 4: Metro and Max Basic Tutorial 4: Metro and Toggle
Toggle
tosymbol
Convert messages, numbers, or lists to a single symbol

Description
tosymbol accepts any message, number, or list, and converts it into a single symbol. The symbol has a maximum length of 2048
characters.

Arguments
None.

Messages
bang See the anything listing
int input [int] See the anything listing
float input [float] See the anything listing
list input [list] See the anything listing
anything input-for-conversion [list] The tosymbol object accepts any message, number, or list for an input, and sends
a single symbol out its output. The symbol can have a maximum length of 2048
characters.

Attributes
Name Type g/s Description
separator symbol Specifies the separator character or symbol to be used when concatenating. The
message separator with no arguments removes all spaces when creating a symbol
(e.g., 1 2 3 4 becomes 1234). When used with slash or colon separators, the
separator attribute can be used to construct pathnames (e.g., ./patches myjunk
myfile becomes ./patches/myjunk/myfile). The default separator is a space.

Information for box attributes common to all objects

Output
symbol: A single symbol consisting of the concatenated messages, numbers, or lists. If the output symbol contains any spaces or
special characters, it will be surrounded by double quotes.

Examples

Convert any input into a symbol

See Also
Name Description
conformpath Convert file paths styles
fromsymbol Convert a symbol into numbers/messages
regexp Use regular expressions to process input
zl Process lists in many ways
touchin
Receive MIDI aftertouch values

Description
Outputs from MIDI aftertouch (channel pressure) messages received from a MIDI input device.

Arguments
Name Units Type Opt Description
port symbol opt Specifies the port (a-z) from which to receive incoming aftertouch messages. If
there is no argument, touchin receives on all channels from all ports.
device symbol opt The name of a MIDI input device may be used as the first argument to specify the
port.
port-channel list A letter and number combination (separated by a space) indicates a port and a
specific MIDI channel on which to receive aftertouch messages. Channel numbers
greater than 16 will be wrapped around to stay within the 1-16 range.
channel int A number alone can be used in place of a letter and number combination. The
exact meaning of the channel number argument depends on the channel offset
specified for each port in the MIDI Setup dialog.

Messages
anything port [list] Performs the same function as port without need for the word, "port".
(mouse) Double-clicking on a polyin object shows a pop-up menu for choosing a MIDI port
or device.
(MIDI) The touchin object receives its input from a MIDI aftertouch message received
from a MIDI input device.
port port [symbol] The word port, followed by a letter a-z or the name of a MIDI input port or
device, sets the port from which the object receives incoming pitch bend messages.
The word port is optional and may be omitted.

Information for box attributes common to all objects

Output
int: If a specific channel number is included in the argument, there is only one outlet. The output is the incoming aftertouch
value, from 0-127, on the specified channel and port.

If there is no channel number specified by the argument, touchin will have a second outlet, on the right, which will output the
channel number of the incoming aftertouch message.

Examples

Aftertouch messages can be received from everywhere, a specific port, or a specific port and channel

See Also
Name Description
touchout Transmit MIDI aftertouch messages
midiin Output raw MIDI data
touchout
Transmit MIDI aftertouch messages

Description
Transmits MIDI aftertouch values to a MIDI device.

Arguments
Name Units Type Opt Description
port symbol opt Specifies the port (a-z) for transmitting MIDI aftertouch messages. Channel
numbers greater than 16 received in the right inlet will be wrapped around to stay
within the 1-16 range. If there is no argument, touchout initially transmits out
port a, on MIDI channel 1.
port-channel list A letter and number combination (separated by a space) indicates a port and a
specific MIDI channel on which to transmit aftertouch messages. Channel
numbers greater than 16 will be wrapped around to stay within the 1-16 range.
device symbol opt The name of a MIDI output device may be used as the first argument to specify the
port.
channel int A number alone can be used in place of a letter and number combination. The
exact meaning of the channel number argument depends on the channel offset
specified for each port in the MIDI Setup dialog.

Messages
int input [int] In left inlet: The number is transmitted as an aftertouch value on the specified
channel and port. Numbers are limited between 0 and 127.
(inlet1) channel [int] In right inlet: The number is stored as the channel number on which to transmit
the aftertouch messages.
float input [float] Converted to int.
anything port [list] Performs the same function as port without need for the word, "port".
(mouse) Double-clicking on a touchout object shows a pop-up menu for choosing a MIDI
port or device.
port port [symbol] The word port, followed by a letter a-z or the name of a MIDI input port or
device, sets the port from which the object receives incoming pitch bend messages.
The word port is optional and may be omitted.

Information for box attributes common to all objects

Output
(MIDI): There are no outlets. The output is a MIDI aftertouch message transmitted directly to the object's MIDI output port.

Examples

Letter argument transmits to only one port... Otherwise, number specifies both port and channel
See Also
Name Description
touchin Receive MIDI aftertouch values
midiout Transmit raw MIDI data
translate
Convert between different units of time.

Description
Converts from any of the fixed or relative Max time values to any other fixed or relative time value.

Arguments
Name Units Type Opt Description
input-format symbol opt The first argument sets the input format to expect. These arguments are a shortcut
for setting the attributes of this object which do the same thing. Time can be
specified in any of the time formats used in Max.
output-format symbol opt The second argument sets the format to output. These arguments are a shortcut
for setting the attributes of this object which do the same thing. Time can be
specified in any of the time formats used in Max.

Messages
bang The last time passed in is converted into the output type specified. Where
appropriate, the input type of the last time passed in will be re-assessed by
checking the in attribute.
int time [int] The time value passed-in is converted into the output type specified. Where
appropriate, the input type will be assessed by checking the in attribute.
float time [float] The time value passed-in is converted into the output type specified. Where
appropriate, the input type will be assessed by checking the in attribute.
list time [list] The time value passed-in is converted into the output type specified. Where
appropriate, the input type will be assessed by checking the in attribute.
anything time [list] The time value passed-in is converted into the output type specified. Where
appropriate, the input type will be assessed by checking the in attribute.

Attributes
Name Type g/s Description
in symbol The input format is used to determine the value sent to this object when the value
alone is not enough. For example, a simple number could represent milliseconds,
hertz, ticks, seconds, etc. This attribute is used to disambiguate such cases.
'ticks' = TEXT_HERE
'ms' = TEXT_HERE
'bars.beats.units' = TEXT_HERE
'samples' = TEXT_HERE
'hz' = TEXT_HERE
'notevalues' = TEXT_HERE
'hh:mm:ss' = TEXT_HERE
listen int Toggles the output of new values for the current input to the translation when the
transport tempo changes. The default is 1 (on).
mode symbol Sets the mode for time values. The translate object can output time values in
either position relative to the system start value of 1.1.0 or interval , where a value
of 1.1.0 would indicate one bar, one beat, and no units (2400 ticks at 4/4 in the
default resolution).
Note: this attribute may not apply, depending on the type of unit conversion.
'interval' = TEXT_HERE
'position' = TEXT_HERE
out symbol Set the time format to use for output.
'ticks' = TEXT_HERE
'ms' = TEXT_HERE
'bars.beats.units' = TEXT_HERE
'samples' = TEXT_HERE
'hz' = TEXT_HERE
'notevalues' = TEXT_HERE
'hh:mm:ss' = TEXT_HERE
transport symbol The name of a transport object with which to associate. By default, the master
transport is used.

Information for box attributes common to all objects

Examples

See Also
Name Description
metro Output a bang message at regular intervals
timepoint Bang at a specific time
transport Control a master clock
when Report the current transport time
transport
Control a master clock

Description
Starts and stops the passage of time for objects linked to a transport. If given a name, the transport object will control a time
context of the given name, otherwise it will control Max's master transport. The transport object reports time consistent with the
time formats used in Max.

Arguments
None.

Messages
bang Report current state
int input [int] In left inlet: toggle whether or not the transport is running on or off
In right inlet: set the current position of the transport in ticks
float input [float] In left inlet: toggle whether or not the transport is running on or off
In right inlet: set the current position of the transport in ticks
list position [list] Set the current position of the transport using a time unit.
(mouse) Double-clicking on the transport object opens the GlobalTransport window.
dump Causes a report of the current state of the transport to be sent to the Max Window.
getclocksources Causes a list of active clock sources to be sent out the right outlet.
timesig beats [list] Set the time signature for this transport using two numbers. The default is 4 4.
value [list]

Attributes
Name Type g/s Description
clocksource symbol The current timing source for the transport. The default source is Max's internal
clock but other timing sources such as ReWire may also be used.
name symbol There can be multiple named transports running simultaneously. By default, a
transport will be associated with Max's global transport. If a name is provided then
a new transport is created with that name and can be referenced using this
attribute.
resetbarcount int Toggles whether the bar/beat/unit counter advances to the beginning of the next
measure when a time signature change is received. By default, this is disabled (0).
tempo float Sets the tempo in beats-per-minute for this transport.

Information for box attributes common to all objects

Examples

See Also
Name Description
metro Output a bang message at regular intervals
translate Convert between different units of time.
timepoint Bang at a specific time
when Report the current transport time
Max Basic Tutorial 19: Timing Max Basic Tutorial 19: Timing
trigger
Send input to many places

Description
Outputs any input received in order from right to left and formatted according to the object-argument specified.

Arguments
Name Units Type Opt Description
formats symbol opt The number of arguments determines the number of outlets. Each outlet sends out
either int, float, bang, list, or symbol, as identified by symbol arguments (i, f, b, l,
or s). If there are no arguments, there are two outlets, both of which send an int.
constant anything opt When an int, float, or symbol is specified, the value is output as a constant.

Messages
bang Causes either a bang, an integer 0, a float 0., a list 0, or an empty symbol to be
sent out of each outlet.
int input [int] The number is sent out each outlet in the form designated by the typed-in
arguments: either an int, a float, a list, a symbol (although empty), or a bang.
float input [float] The number is sent out each outlet in the form designated by the typed-in
arguments: either an int, a float, a list, a symbol (although empty), or a bang.
list input [list] The list is sent out any outlet with the letter l assigned to it. Out other outlets, the
list is converted and sent out as integer 0, float 0., the empty symbol "", or bang.
anything input [list] Anything can be output according to the format specified (same as list but
interpreted as a symbol).

Information for box attributes common to all objects

Output
bang: Anything received in the inlet will be converted to bang before being sent out a b outlet.
float: A number received in the inlet is sent out each outlet, in order from right to left. The number will be converted to int, float,
list, symbol, or bang before being sent out, depending on the argument that corresponds to each outlet. A symbol, list, or bang
received in the inlet will be converted to integer 0 by an i outlet, and to float 0. by an f argument.
int: A number received in the inlet is sent out each outlet, in order from right to left. The number will be converted to int, float,
list, symbol, or bang before being sent out, depending on the argument that corresponds to each outlet. A symbol, list, or bang
received in the inlet will be converted to integer 0 by an i outlet, and to float 0. by an f argument.
list: A list received in the inlet will be sent out unchanged by an l outlet. Anything else will be converted to the single-item list 0
before being sent out.
symbol: A symbol received in the inlet will be sent out unchanged by an s outlet. Anything else will be converted to the null
symbol "" before being sent out. Note: The only object that recognizes this null symbol is print, which valiantly prints the empty
message in the Max window. Other objects will either ignore this null symbol or print an error message in the Max window.

Examples

Order is normally right-to-left... Any other order can be specified by trigger


See Also
Name Description
bangbang Output a bang from many outlets
jstrigger Execute Javascript instructions sequentially
message Send any message
Max Basic Tutorial 5: Message Max Basic Tutorial 5: Message Order and Debugging
Order and Debugging
Max Basic Tutorial 6: Simple Max Basic Tutorial 6: Simple Math in Max
Math in Max
trough
Output a number if it is less than previous numbers

Description
Compares an input value to the stored value and, if it's smaller it sends the input to the output and sets it as the new trough.

Arguments
Name Units Type Opt Description
value float opt The initial value stored in trough is 128. Providing a float argument will cause
trough to operate on floating-point values instead of integers.

Messages
bang In left inlet: Sends the currently stored minimum value out the left outlet.
int input [int] In left inlet: If the input is less than the value currently stored in trough, it is
stored as the new minimum value and is sent out.
(inlet1) trough [int] In right inlet: The input is stored in trough as the new minimum value, and is
sent out.
float input [float] In left inlet: If the input is less than the value currently stored in trough, it is
stored as the new minimum value and is sent out.
(inlet1) trough [float] In right inlet: The input is stored in trough as the new minimum value, and is
sent out.

Information for box attributes common to all objects

Output
int: Out left outlet: New minimum values are sent out. (Numbers received in the right inlet are always the new minimum value.)

Out middle outlet: If the number received is a new minimum value, the output is 1. If the number received in the left inlet is not
a new minimum value, the output is 0.

Out right outlet: If the number received is a new minimum value, the output is 0. If the number received in the left inlet is not a
new minimum value, the output is 1.

Examples

Find the smallest in a series of numbers... Number in right inlet always sets a new trough

See Also
Name Description
minimum Output the smallest value
peak Output larger numbers
< Compare numbers for less than condition
Max Data Tutorial 2: Data Scaling Max Data Tutorial 2: Data Scaling
ubutton
Send a bang with a transparent button

Description
Creates a transparant click-able region that can be placed over graphics or other objects. Produces a bang message when clicked.

Arguments
None.

Messages
bang The ubutton object can operate in one of two modes. When the ubutton is in
button mode (the default mode), it responds to a bang in its inlet by becoming
highlighted briefly and sending a bang out its left outlet. When ubutton is in
toggle mode, a bang in its inlet causes it to become (and stay) highlighted and
send a bang out its right outlet; or, if it is already highlighted, it becomes
unhighlighted and sends a bang out its left outlet.
int input [int] If ubutton is waiting for a particular number (its Stay-on Value) and the incoming
number matches it, the button is highlighted but nothing is sent out. If the
incoming number does not match the number that ubutton is waiting for, the
button is unhighlighted (or remains that way). If ubutton has a Stay-on Value of
0, int is the same as bang.
float input [float] Converted to int.
anything input [list] Converted to bang.
(mouse) In "button" mode, a mouse click on ubutton highlights it for as long as the mouse
is held down, sending a bang out the right outlet when the mouse button is
pressed down, and another bang out the left outlet when the mouse button is
released. In "toggle" mode, a mouse click behaves the same as a bang. When the
mouse is clicked, ubutton will send a 1 out the right outlet if the cursor is inside of
the ubutton object's rectangle, and 0 if it is not. It will also send these messages
when the mouse button is released. When the object is in "Track Mouse While
Dragging" mode, these messages are sent continuously while the mouse button is
held down after a click.
set input [int] If ubutton is in toggle mode, set 1 sets the ubutton object's toggle (highlights it)
and set 0 clears the ubutton object's toggle (unhighlights it). Other integer
arguments for set will send the number to ubutton, for comparison to its Stay-on
Value, without causing any output.

Attributes
Name Type g/s Description
dragtrack int The word dragtrack, followed by a non-zero number, enables "Track Mouse
def.:0 While Dragging" mode. In this mode, positional and inside/outside messages
(described above for mouse clicks) are sent continuously while the mouse button is
held down after a click. dragtrack 0 disables this behavior, which is off by default.
Dragging the mouse will continue to generate these message pairs until the mouse
button is released. Drag tracking is off by default. It can also be enabled in the
ubutton object's Inspector.
hilite int Toggles the display of a highlight when ubutton is clicked.
def.:1
hltcolor float Sets the Highlight Color in RGBA format.
stay int Selects the button mode. The modes are:
def.:0 0 the ubutton object is in normal button mode. It does not look for any particular
number.
(any non-zero number) the object is in button mode and waits for the specified
non-zero number. When that number is received in the inlet, no output is sent,
but ubutton stays highlighted until some other message (or a mouse click) is
received.
toggle int Selects the toggle mode. The modes are:
def.:0 0 button mode
(any non-zero number) toggle mode
'Button' = TEXT_HERE
'Toggle' = TEXT_HERE

Information for box attributes common to all objects

Output
bang: Out 1st outlet: In button mode (with a Stay-on Value of 0), any input causes ubutton to flash and send a bang out the left
outlet. A bang is also sent out the left outlet when the mouse button is released.

If the ubutton object is in toggle mode and is already highlighted, any input causes ubutton to become unhighlighted and send a
bang out its left outlet.
bang: Out 2nd outlet: In button mode (with a Stay-on Value of 0), a mouse click sends a bang when the mouse button is
pressed.

If the object is in toggle mode, any input causes ubutton to become highlighted and send a bang out the outlet. If it is already
highlighted, it becomes unhighlighted and no bang is sent.
int: Out right outlet: When the mouse button is clicked and released, a 1 is sent out this outlet if the cursor is inside of the
ubutton object's rectangular area. If the "Track Mouse While Dragging" option is enabled using the Inspector or the dragtrack
message, a 0 will be output if the cursor moves outside of the ubutton object's rectangular area while the mouse button is
pressed.
list: Out 3rd outlet: When the mouse button is clicked and released, the ubutton object sends out a list composed of two
numbers which specify the coordinates for the cursor position expressed as an offset, in pixels, from the upper left-hand corner
of the ubutton object rectangle. If the "Track Mouse While Dragging" option is enabled using the Inspector or the dragtrack
message, new coordinates will be reported as the mouse is moved until the mouse button is released.

Examples

When ubutton is placed on comments or pictures, they can

See Also
Name Description
button Blink and send a bang
fpic Display a picture from a graphics file
led Display on/off status
matrixctrl Matrix switch control
pictctrl Picture-based control
radiogroup Radio button/check box user interface
tab Select values with tabs or multiple buttons
textbutton A user interface button/toggle
udpreceive
Receive messages over a network

Description
Receives messages transmitted over a network using the User Datagram Protocol (UDP).

Arguments
Name Units Type Opt Description
port int Specifies the local port that the udpreceive object will use to listen for incoming
messages.
full-packet symbol opt The udpreceive object and its counterpart the udpsend object provide support for
third-party Max objects that work with the Open Sound Control (OSC) protocol
developed by the Center for New Music and Audio Technologies (CNMAT) at the
University of California, Berkeley. An optional symbol argument (it can be any
symbol) specifies that the udpreceive object should pass on UDP buffers as OSC
'FullPacket' messages instead of decoding them and outputting them as Max
messages.

Messages
maxqueuesize maximum [int] The word maxqueuesize, followed by an integer, sets the maximum number of
incoming messages that can be in the queue at any given time (default="2048)."
The work queue will grow as needed until this maximum limit is reached. In high-
traffic or high-speed situations, you may need to increase the maximum queue size
to avoid dropped messages.
port port [int] The word port, followed by a number, sets the local port that the udpreceive
object will use to listen for incoming messages.

Attributes
Name Type g/s Description
quiet int When enabled, status notifications to the Max window are suppressed.

Information for box attributes common to all objects

Output
anything: All OSC-compatible UDP messages received at the port number of the host computer (designated by argument or the
port message) are sent out the outlet.

Examples

Look ma! No hands!!!

See Also
Name Description
udpsend Send messages over a network
Max Comm Tutorial 3: UDP Max Comm Tutorial 3: UDP Networking
Networking
udpsend
Send messages over a network

Description
Transmits messages over a network using the User Datagram Protocol (UDP).

Arguments
Name Units Type Opt Description
host symbol Specifies the host destination to which messages will be sent over a network. Host
destinations can be specified either by name (e.g., localhost) or by IP address (e.g.,
127.0.0.1).
port int Specifies the remote port that the udpsend object will use when sending
messages.

Messages
bang Sends the bang message over the network using UDP.
int message [int] Sends an int message over the network using UDP.
float message [float] Sends a float message over the network using UDP.
list message [list] Sends a list message over the network using UDP.
anything message [list] Sends the given message over the network using UDP.
FullPacket behavior [int] The udpsend object and its counterpart the udpreceive object provide support for
number [int] third-party Max objects that work with the Open Sound Control (OSC) protocol
developed by the Center for New Music and Audio Technologies (CNMAT) at the
University of California, Berkeley. The FullPacket message toggles support for the
'FullPacket' message used by the CNMAT Open Sound Control externals or the
Max udpreceive object--when set, the udpsend object will send UDP buffers in
the form of OSC 'FullPacket' messages.
host host [symbol] The word host, followed by a symbol, specifies the host destination to which
messages will be sent. Host destinations can be specified either by name (e.g.,
localhost) or by IP address (e.g., 127.0.0.1).
maxqueuesize maximum [int] The word maxqueuesize, followed by an integer, sets the maximum number of
incoming messages that can be in the queue at any given time (default="2048)."
The work queue will grow as needed until this maximum limit is reached. In high-
traffic or high-speed situations, you may need to increase the maximum queue size
to avoid dropped messages.
maxpacketsize maximum [int] The word maxpacketsize, followed by an integer, sets the size, in bytes, of the
largest UDP packet that you can send (default="5096)." Since this value is related
to the largest Max message you can possibly send, you may need to increase this
value if you are sending very long Max messages.
port port [int] The word port, followed by a number, specifies the remote port that the udpsend
object will use to send outgoing messages.

Information for box attributes common to all objects

Output
(UDP): There are no outlets. Max messages received by the udpsend object are serialized and sent over the network as OSC-
compatible UDP packets.

Examples
Look Ma! No Hands!!!

See Also
Name Description
udpreceive Receive messages over a network
Max Comm Tutorial 3: UDP Max Comm Tutorial 3: UDP Networking
Networking
umenu
Create and fill a pop-up menu

Description
Displays text as a pop-up menu. Selections can be made manually, or set incoming numbers. Outputs both selection number and
selection text.

Arguments
None.

Messages
bang Sends out the currently displayed menu item.
int index [int] The number specifies a menu item to be sent out, and causes umenu to display
that item. The items are numbered starting at 0. A menu item can also be chosen
from a umenu with the mouse, as with any pop-up menu.
float index [float] Converted to int.
(drag) When a file folder is dragged from the Max 5 File Browser to a umenu object, the
folder's contents will be loaded into as menu choices.

When a file folder is dragged from the Max 5 File Browser to a blank space in an
unlocked patcher window, a umenu object containing the folder's contents loaded
will be created.
append message [list] The word append, followed by any message, appends that message as the new last
item in the menu.
checkitem index [int] The word checkitem, followed by an item number and 1 or 0, places (1) or
checked [int] removes (0) a check mark next to the item number.
clear Removes all items from the umenu.
delete indices [list] The word delete, followed by one or more numbers that correspond to items in
the list, deletes the item or items from the umenu.
clearchecks The word clearchecks removes check marks for all items.
count Sends the number of items in the umenu out the right outlet, preceded by the
word count.
enableitem indes [int] The word enableitem, followed by a number that specifies a menu item and a 1 or
enable [int] 0, enables or disables the specified item number. Disabled menu items cannot be
selected, but their text and item number are sent from the rightmost outlet if the
mouse is released while above them, prefixed by the symbols disabled_eval and
disabled_item, respectively.
gettoggle Reports the current value of the umenu object's toggle state (1 or 0, for on or off),
from the right outlet, preceded by the word toggle.
insert index [int] The word insert, followed by a number and a message, inserts the message at the
message [list] address specified by the number, incrementing all equal or greater addresses by 1
if necessary.
mode display [int] The word mode, followed by a number in the range 0-3, sets the appearance and
behavior of the umenu object. The normal pop-up menu style is 0 (the default).
Scrolling mode (2) lets you scroll through the individual menu items by dragging
the mouse up or down, displaying one item at a time. Label mode (2) shows the
text of the selected menu item with no border around it, and does not respond to
the mouse. Toggle mode (3) sets a button style. Clicking on the object in mode 3
causes it to alternate between an active and inactive state. When changing from
inactive to active, the object sends the message toggle 1 from its rightmost outlet,
and changes to the color set using the togcolor attribute. When changing from
active to inactive, the object sends the message toggle 0 from its rightmost outlet,
and changes to the color set using the bgcolor attribute. Whether activating or
deactivating, the object also sends its current message from the middle outlet and
its current item number from the left outlet.
(mouse) Clicking with the mouse lets you select a menu item to be sent out, and causes
umenu to display that item.
next Selects the next menu item and causes the umenu object to display that item. This
message will ignore disabled or separator menu items.
populate If the umenu object has a valid folder path as its prefix, the populate message
will cause the menu to re-populate its items list, based on the current contents of
the specified path (and filtered by the types list). After population is complete, the
number of items added to the umenu object will be output from the right outlet,
preceded by the word populate.
prev Selects the previous menu item and causes the umenu object to display that item.
This message will ignore disabled or separator menu items.
set item [list] The word set, followed by a number or symbol, specifies a menu item to be
displayed by umenu, but does not send it out the outlet. If the set argument is a
symbol, set searches for a menu item which begins with the symbol.
setcheck character [int] (Macintosh only) The word setcheck, followed by a number that specifies the
decimal representation of a UTF-8 character (e.g. 8226 for a bullet or 62 for a
greater than symbol), sets the character used to be the check mark. The word
setcheck with no argument specifies the default square root checkbox.
setitem index [int] The word setitem, followed by an item number and any message, sets the
message [list] specified menu item to that message.
setsymbol menu item [symbol] The word setsymbol, followed by a message, specifies a menu item to be
displayed by name without triggering any output.
setrgb fore-red [int] The word setrgb, followed by six numbers between 0 and 255 that specify RGB
fore-green [int] values, uses the first three numbers to set the foreground (text) color and the
fore-blue [int] second three numbers to set the background (fill) color.
back-red [int]
back-green [int]
back-blue [int]
settoggle state [int] The word settoggle, followed by a one or zero, sets the umenu object to the
specified state if it is in toggle mode and performs output as if the object were
clicked on (the symbol toggle, followed by a zero or one, indicating the toggle
state). Without an argument, the message simply toggles the object's state and
triggers output.
showchecked This message operates as follows. If the currently displayed item is checked, do
nothing. Otherwise, starting at the first item in the menu, find one that is checked
and set the menu to display that item. If there isn't one, do nothing.
symbol item [symbol] Identical to the set message with a symbol argument, except that the found item
number is sent out (and the text of the item is sent out the right outlet, if the
Evaluate Item Text feature is enabled).
toggle state [int] The word toggle, followed by a one or zero, sets the umenu object to the specified
state if it is in toggle mode and performs output as if the object were clicked on
(the symbol toggle, followed by a zero or one, indicating the toggle state).
Without an argument, the message simply toggles the object's state and triggers
output.

Attributes
Name Type g/s Description
align int Sets the text alignment mode. Alignment modes are:
def.:0 0 left (the default)
1 center (1)
2 right alignment (2)
'Left' = TEXT_HERE
'Center' = TEXT_HERE
'Right' = TEXT_HERE
arrow int Toggles the drawing of the arrow and frame on the right-hand side of the umenu
object.
arrowbgcolor float Sets the color of the umenu object's arrow frame in RGBA format.
arrowcolor float Sets the color of the umenu object's up/down arrows in RGBA format.
arrowframe int Toggles the drawing of the frame on the right-hand side of the umenu object.
arrowlink int Toggles linking the colors used in the background and the arrow frame. When set
to 1 (the default) the same background color will be used as the arrow and frame.
When set to 0, the arrow background color is used.
autopopulate int Toggles the automatic population of an umenu object with folder contents
def.:0 (default = 0). The automatic population will occur when it receives a valid folder
path as the argument to a prefix message, or at patcher load, if a valid prefix is
stored with the object. See the prefix, populate, and types message descriptions for
more information.
bgcolor float Sets the background color of the umenu object object in RGBA format.
bgcolor2 float Sets the pop-up background color of the umenu object object in RGBA format.
depth int Sets the folder recursion depth used by the umenu object when populating from a
def.:0 valid file path.
discolor float Sets the disabled text color of the umenu object objects menu item in RGBA
format.
framecolor float Sets the frame color (i.e., the lit part of a 3D menu item) of the umenu object
objects menu item in RGBA format.
hltcolor float Sets the highlight color of the umenu object objects menu item in RGBA format.
items atom The items attribute, which is only accessible using the umenu object's Inspector,
lets you enter the items which you want to appear on the menu by typing into a
dialog box. Menu items are separated by by commas (e.g., red, orange, yellow,
green).
labelclick int Toggles Label Click mode on or off. In this mode, when the object is in Label
def.:0 mode, you can click in the object's rectangle and the current value of the menu is
sent out the left outlet. In addition, the text of the current item is shown
underlined.
menumode int Sets the appearance and behavior of the umenu object. The modes are:
def.:0
0: Normal mode - the normal pop-up menu (default).
1: Scrolling mode - lets you scroll through the individual menu items by dragging
the mouse up or down, displaying one item at a time.
2: Label mode - shows the text of the selected menu item with no border around it,
and does not respond to the mouse.
3: Toggle mode - Clicking on the object in mode 3 causes it to alternate between
an active and inactive state. When changing from inactive to active, the object
sends the message toggle 1 from its rightmost outlet, and changes to the color set
using the togcolor attribute. When changing from active to inactive, the object
sends the message toggle 0 from its rightmost outlet, and changes to the color set
using the bgcolor attribute. Whether activating or deactivating, the object also
sends its current message from the middle outlet and its current item number
from the left outlet.
Control-clicking allows you to change the current state of a umenu object in toggle
mode.
'Normal' = TEXT_HERE
'Scrolling' = TEXT_HERE
'Label' = TEXT_HERE
'Toggle' = TEXT_HERE
parameter_enable int Parameter Mode Enable
pattrmode int Sets the method used by the umenu object object to report its internal state to the
def.:0 pattr object. When the argument is 0 (default), the umenu object reports its
internal state by number (e.g. item 3 of the list of items). When the argument is 1,
the umenu object reports its internal state by symbol (e.g. item 'carrots' of the list
of items).
prefix symbol Sets a menu-wide prefix, which can be concatenated or prepended to all menu
def.: item text before output. If the prefix is a valid folder path, the populate and types
messages can be used to automatically fill the umenu object with a list of files in
the folder. See the entries for those messages for more information. Sending a
prefix message without any argument clears the currently stored prefix.
prefix_mode int Sets the output behavior of the prefix mode. The modes are:
def.:0
0: concatenate mode; the prefix is added to the front of the outgoing message
without a space.
1: prepend mode; the prefix is added to the front of the outgoing message list as a
discrete symbol.
2: ignore mode; the prefix is not used for output.
'Concatenate' = TEXT_HERE
'Prepend' = TEXT_HERE
'Ignore' = TEXT_HERE
rounded int Sets the radius, in pixels for the umenu object.
def.:8
showdotfiles int Toggles the display of files whose names begin with a dot (.). The default is off.
def.:0
textcolor float Sets the text color of the umenu object object in RGBA format.
textcolor2 float Sets the pop-up text color of the umenu object object in RGBA format.
togcolor float Sets the toggle color of the umenu objects menu item in RGBA format.
truncate int Toggles the location of the truncation of text in the umenu object when the text is
def.:1 too long. The default is 1 (truncate the end of the text on the right-hand side). A
value of 2 will cause the text to truncate in the middle in the same manner as the
textbutton object.
'Truncation full words' = TEXT_HERE
'Truncate from the right' = TEXT_HERE
'Truncate from the middle' = TEXT_HERE
types symbol Sets a file type filter for use by the populate message. Up to 64 file types may be
entered as a list. By default, no file types are filtered.
underline int Toggles the underlining of text in the umenu object. The default is 0 (no
def.:0 underlining).

Information about attributes available for Parameter-aware objects

Information for box attributes common to all objects

Menu Items
Name Description
Color Choosing the Color... menu item from the Object menu when the object is
selected opens a color picker, permitting adjustment to the appearance of the
umenu object.

Output
anything: Out middle outlet: The text of the selected menu item is sent out as a message.

Out right outlet: The count, gettoggle, and populate, messages will cause status messages to be sent out the right outlet.
int: Out left outlet: The number of the selected menu item is sent out. Menu items are numbered beginning with 0.
Examples

Used to send commands ...or to display text associated with numbers received

See Also
Name Description
coll Store and edit a collection of data
fontlist List system fonts
Max Basic Tutorial 13: Movie Max Basic Tutorial 13: Movie Sequencing
Sequencing
universal
Send messages to all objects of the same type

Description
Sends a input message to all instances of the same class of object in a patcher. The order in which the messages arrive is not
defined.

Arguments
Name Units Type Opt Description
mode int opt If a 1 is present as an argument, universal will send messages it receives to objects
of the specified class in subpatchers of its patcher as well as in the patcher
containing the universal object.

Messages
bang Sends a bang to all instances of the same class of object within the patcher.
int input [int] Sends an int to all instances of the same class of object within the patcher.
float input [float] Sends a float to all instances of the same class of object within the patcher.
list input [list] Sends a list to all instances of the same class of object within the patcher.
anything input [list] Sends anything to all instances of the same class of object within the patcher.
send input [list] To send messages to certain objects whose class names are also reserved Max
message names (such as int and float), you need to start the message with the
send message. send can be used with any class.

Information for box attributes common to all objects

methodnote
Output
None: The object has no outlets, but objects receiving the message(s) it sends may have some form of output from their outlets.
However, the order in which the message is sent to various objects is not guaranteed. This is also true when using the send and
receive objects.

Examples

Send a message to all objects of the same class at once

See Also
Name Description
forward Send messages to specified receive objects
receive Receive messages without patch cords
send Send messages without patch cords
value Share a number with other objects
unjoin
Break a list into messages

Description
Separates a list's elements by group, and send each group of items out a separate outlet.

Arguments
Name Units Type Opt Description
outlets int Specifies the number of outlets (in addition to the rightmost outlet, which is
always present).

Messages
int input [int] The number is sent out the left outlet.
float input [float] The number is sent out the left outlet.
list input [list] Items from the input list are separated into lists containing the number of
elements specified by the outsize attribute and sent out the outlet corresponding
to their group position in the list. Any remaining items are sent out the right
outlet.
anything input [list] Performs the same function as list.

Attributes
Name Type g/s Description
outsize int Defines the number of items to be sent out the outlets.
def.:1

Information for box attributes common to all objects

Examples

See Also
Name Description
join Combine items into a list
pack Create a list
pak Output a list when any element changes
unpack Break a list into individual messages
unpack
Break a list into individual messages

Description
Breaks a list into its elements, and sends each item out a separate outlet.

Arguments
Name Units Type Opt Description
list-elements any opt The number of outlets is determined by the number of arguments. The arguments
can be any combination of ints, floats, and symbols. The argument specifies the
output of the unpack object's outlets; the input type is forced to the outlet type
that is defined. If no argument is typed in, unpack will have two int outlets.

Messages
bang Causes each stored item of a list to be sent out the corresponding outlet.
int input [int] The number is sent out the left outlet.
float input [float] The number is sent out the left outlet.
list input [list] Each item in the list (up to the number of outlets) is sent out the outlet
corresponding to its position in the list.
anything input [any] Performs the same function as list.

Information for box attributes common to all objects

Output
float: If the outlet has been initialized with a float argument, then an int or a symbol from the input list will be converted to float
before being sent out that outlet.
int: Each item of the list received in the inlet is sent out the corresponding outlet. The first item in the list is sent out the leftmost
outlet, and so on.
symbol: A symbol in the input list will be sent out the corresponding outlet if that outlet has been initialized with a symbol
argument.

Examples

Each item in a list can be sent to a different place

See Also
Name Description
iter Break a list into individual messages
listfunnel Index and output list elements
join Combine items into a list
pack Create a list
pak
Output a list when any element changes
spray Distribute a value to a numbered outlet
unjoin Break a list into messages
zl Process lists in many ways
Max Basic Tutorial 9: Mouse Max Basic Tutorial 9: Mouse Drawing
Drawing
urn
Generate random numbers without duplicates

Description
Outputs random numbers and keeps track of each number that has been generated. When all numbers up to the maximum (set
via an argument or the right inlet) have been output, a bang is send out the right outlet.

Arguments
Name Units Type Opt Description
limit int opt The number of possible values for the random number generator. If no argument
is typed in, there will be only 1 possible number.
seed int opt A second argument is used to set a "seed" value for the random generator. If no
argument is specified, the time value will be used to initialize the seed.

Messages
bang In left inlet: Sends out a previously unchosen random number from 0 to one less
than the specified maximum limit.
int limit [int] In right inlet: Clears the list of already chosen numbers, and specifies the number
of possible values for the random number generator. The random numbers will
range from 0 to one less than this maximum limit.
(inlet1) limit [int] Clears the list of already chosen numbers, and specifies the number of possible
values for the random number generator. The random numbers will range from 0
to one less than this maximum limit.
clear In left inlet: Clears the list of already chosen numbers.
seed seed [int] In left inlet: The word seed, followed by a number, provides a "seed" value for the
random generator, which causes a specific (reproducible) sequence of pseudo-
random numbers to occur. The number 0 uses the time elapsed since system
startup (an unpredictable value) as the seed, ensuring an unpredictable sequence
of numbers. This unpredictable seed is used by default when the urn object is
created. However, once all numbers have been chosen, the sequence will repeat.
Therefore, in order to achieve a non-repeating sequence of numbers, you will need
to send the urn object the seed 0 message each time you send it the clear
message.

Information for box attributes common to all objects

Output
bang: Out right outlet: When all numbers in the current range have been generated, urn sends a bang out the right outlet instead
of a number out the left outlet.
int: Out left outlet: If there are numbers within the current range that have not been sent out since the last clear message was
received, urn generates a random number between 0 and one less than the maximum.

Examples
Choose random numbers without repeating a choice

See Also
Name Description
decide Choose randomly between 1 and 0
deferlow Defer the execution of a message (always)
drunk Output random numbers within a step range
random Generate a random number
uzi
Send many bang messages

Description
Outputs a specified number of bang messages quickly. uzi is designed for rapid-fire output of a large number of bang messages.

Arguments
Name Units Type Opt Description
initial int opt Sets an initial number of bang messages to be sent out in response to a bang in
the left inlet. If no argument is present, uzi is initially set to send out one bang.
base int opt An optional second argument sets the base value for the right outlet count. The
base value defaults to 1 when no second argument is given.

Messages
bang In left inlet: Begins sending out bang messages as fast as possible, one after
another. The number of bang messages to send is determined by the last number
received in either inlet.
int input [int] In left inlet: Sets the number of bang messages to send, then begins sending them
out as fast as possible, one after another.
(inlet1) bangs-without-output [int] In right inlet: Sets the number of bang messages to send, without causing output.
break Same as pause.
continue Same as resume.
offset start [int] The word offset followed by a number of bangs will set the object to output a
count of bangs which is offset by the given number (the number is subtracted from
the previously assigned number of bangs to equal the new total number of bangs).
pause In left inlet: Causes uzi to stop in the midst of sending its output. (Since uzi sends
its output as fast as possible, this message must be triggered in some way by the
output of uzi itself.) uzi keeps track of how many bang messages it has sent, and
if it receives the pause message before sending out all its bang messages, it can
then be caused to send out the rest of its bang messages with a resume or
continue message.
resume In left inlet: If uzi has been stopped by a pause message in the midst of sending
its output, resume causes it to send out the rest of its output.

Information for box attributes common to all objects

Output
bang: Out left outlet: When uzi receives a bang or int in its left inlet, a certain number of bang messages are sent out as fast as
possible, one after another. The number of bang messages is determined by the most recent number received in either inlet.

Out middle outlet: After the last bang is sent out its left outlet, uzi sends one bang out its middle outlet. This can be used as a
signal that all the bang messages have been sent, much like the "carry" outlet on the counter object.
int: Out right outlet: The number of each bang is sent out. Numbering begins from 1 (or from the base value specified by the
optional second argument) each time an int or bang is received in the left inlet. If uzi is being restarted with a resume or
continue message, numbering begins wherever it left off.

Examples
Count as fast as possible using uzi... Count at a specific rate, not using uzi... Use uzi to perform many calculations quickly

See Also
Name Description
bline Generate ramps using bang
counter Keep count based on bang messages
line Generate timed ramp
metro Output a bang message at regular intervals
Max Basic Tutorial 17: Data Max Basic Tutorial 17: Data Structures And Probability
Structures And Probability
value
Share a number with other objects

Description
Shares a name with other value objects, with others of the same name linked. If you send any one a message (number, list, or
anything else) it is set for all of them. You can get the contents out of a particular value object by sending it a bang.

Arguments
Name Units Type Opt Description
name symbol Gives a name to value.
initial anything opt Additional arguments after the naming symbol initialize the contents of value. If
no additional arguments are present, value contains nothing.

Messages
bang Sends out the stored message.
int input [int] Performs the same function as anything.
float input [float] Performs the same function as anything.
list input [list] Performs the same function as anything.
anything input [list] The message is stored, to be shared by all other value objects with the same name,
even if they are in another patch. A message received in any other value object
that has the same name will change the stored value.
(mouse) Double-clicking on a value object opens all windows containing value objects with
the same name.
symbol input [symbol] Performs the same function as anything.

Information for box attributes common to all objects

Output
any message: bang in the inlet causes the stored message to be sent out.

Examples

One value (or any type of message) is shared between all value objects that share the same name

See Also
Name Description
float Store a decimal number
int Store an integer value
pv Share data within a patch hierarchy
pvar Connect to a named object in a patcher
send Send messages without patch cords
receive Receive messages without patch cords
Max Basic Tutorial 16: Remote Max Basic Tutorial 16: Remote Messaging
Messaging
vdp
Control a videodisk player through a serial port

Description
The vdp object works with serially-controlled videodisk players (remember them?) that are compatible with the Pioneer 4200 or
8000 standard. Each command received by the vdp object sends a stream of numbers out the object's left outlet, intended to be
connected to the serial object. The description of each command discusses what effect the command has on the player, not the
exact character stream sent by vdp.

Because videodisc players have relatively buffer-less serial interfaces, vdp places each command it receives in a queue, and sends
it out only when the player has finished executing its most recent command. This "feature" may cause a delay between the time a
command is sent to the vdp object and the time it is actually sent out the serial port.

Any message received in the right inlet will behave exactly as if it had been received in the left inlet, except that it will be put at the
front of the queue, to be the very next command sent out to the player.

Arguments
None.

Messages
int frame-number [int] In left inlet: Same as play from a specified frame number to the end of the disc.

In middle inlet: vdp expects responses from the player to be fed from the serial
object into its middle inlet. When vdp sees "received" (the letter R followed by the
return character) from the player, it sends the next command from its queue of
pending commands. The example shows how to connect the vdp and serial objects
together.
chapter In left inlet: Asks the player what its current chapter number is and sends the
response (received in the middle inlet) out the middle-right outlet.
clear In left inlet: Removes any pending commands from the queue and resets the
object.
cmd ASCII-primitive-command- In left inlet: The cmd message can be used to send "primitive" commands
code [list] consisting of ASCII codes to the video disk player. Commands usually consist of
two-letter codes preceded by numeric arguments. For example, searching to frame
5000 could be accomplished with the message cmd 5000 SE. Refer to the owner's
manual of your player for details. The cmd message is particularly useful with the
Pioneer 8000 player, since it has a number of special features not supported by
the regular messages of the vdp object.
control action-ID [int] In left inlet: The word control, followed by a number, tells the videodisc player to
perform one of the following operations:

Number Operation
0 --------- Initialize and reset player
1 --------- Eject disk
2 --------- Audio off
3 --------- Audio 1 on
4 --------- Audio 2 on
5 --------- Stereo on
6 --------- Picture on
7 --------- Picture off
8 --------- Display frame numbers on
9 --------- Display frame numbers off
11 ------- Frame access mode
12 ------- Time access mode
13 ------- Chapter access mode
fps playback-speed (frames-per-
In left inlet: Sets the playing speed. The fps message is followed by a number
second) [list] (frames per second) or an adjective. The following adjectives and numbers are
equivalent (at least for the Pioneer 4200):

slowest 1
slower 10
slow 15
normal 30
fast 60
faster 90
fastest 120
frame In left inlet: Asks the player what its current frame number is and sends the
response (received in the middle inlet) out the middle-right outlet.
name In left inlet: Asks the player what the current name is and sends the response
(received in the middle inlet) out the middle-right outlet.
play first-frame [int] In left inlet: With no arguments, play starts playing at the current speed from the
last-frame [int] current location to the end of the disk (or until the player receives another
speed [int] command). With one argument (a frame number), play searches to the specified
frame number and begins playing to the end of the disk. With two arguments, play
searches to the location specified by the first number and plays until the disc
reaches the second frame number.
scan forward/backward [list] In left inlet: Initiates a "fast forward" or "rewind" operation. scan forward moves
forward, scan backward moves backward.
search start-frame-number [int] In left inlet: The first argument indicates a frame number to search to. The second,
display-flag (0 or non-zero) optional argument, if non-zero, instructs the player to keep the picture on while
[int] searching. If searching a great distance from the current location, the player may
not be able to keep from blanking the screen. Once the player arrives at the
desired frame, it will display the (still) image from that frame.
step previous/next-step (-1 or 1) In left inlet: Followed by -1, step pauses the player (if playing) and displays the
[int] previous frame. Followed by 1, step pauses the player (if playing) and displays the
next frame.
stop In left inlet: Pauses the player.
restrict start-frame-number [int] The word restrict followed by a starting frame-number and an ending frame-
end-frame-number [int] number will restrict all future messages to perform their actions restricted
between the two frames.
setskip number-of-skipped-frames In left inlet: Followed by a number, sets the number of frames to jump (forward or
[int] backward) from the current frame location when using the skip message.
skip backward/forward-flag (-1 or In left inlet: Followed by -1, skips backward by a number of frames specified in
1) [int] the setskip message. Followed by 1, skips forward by a number of frames
specified in the setskip message.

Information for box attributes common to all objects

Output
bang: Out middle-left outlet: After sending a command out its left outlet, vdp begins "polling" the serial object for a response
from the player by sending bang messages out this outlet approximately every 20 milliseconds, until vdp receives a "received"
signal from the player in its right inlet. (A bang sent to a serial object causes any characters received in that serial port to be sent
out the serial object's outlet.)
int: Out left outlet: A stream of characters, coded instructions to the videodisc player, for each command. These numbers are
intended to be sent to the left inlet of a serial object.
int: Out middle-right outlet: Current frame number, received from the player in response to a frame message.
int: Out right outlet: Not implemented.

Examples
Basic configuration of vdp and serial objects... 'Scrubbing' with a slider or MIDI controller

See Also
Name Description
serial Send and receive from a serial port
vexpr
Evaluate a math expression for a list

Description
Performs mathematical calculations using C language-style mathematical operations. Operates on inputs that are lists rather than
collections of single values.

Arguments
Name Units Type Opt Description
expression list The argument to the vexpr object is a mathematical expression composed of
numbers, arithmetic operators such as + or *, comparisons such as < or >, C
functions such as min () or pow (), names of table objects, and changeable
arguments ($i, $f, and $s) for ints, floats, and symbols received in the inlets.
constant number Numbers can be used as constants in the mathematical expression.
format symbol Changeable arguments that specify data formats associated with an inlet are
described using a combination of a data type ($i or $f) and an inlet number
(example: $i2). The argument will be replaced by numbers received in the
specified inlet.
table symbol Changeable arguments that specify accessing data from a table are described using
the argument $s and an inlet number which is replaced by the name of a table to
be accessed. The argument should be immediately followed by a number in
brackets specifying an address in the table. (Examples: $s2[7] or $s3[$i1].)
(other) symbol The vexpr object understands the following arithmetic operators: +, -, *, /, %.
Other operators are ~ (one's complement), ^ (bitwise exclusive or), &, &&, |, ||,
and ! (not).

Many C language math functions can be understood by vexpr. A function must be


followed immediately by parentheses containing any arguments necessary to the
function. If the function requires a comma between arguments, the comma must
be preceded by a backslash (\) so that Max will not be confused by it. For example:
(pow ($i1\,2) + $f2).

C language functions understood by vexpr are: abs, min, max, sin, cos, tan, asin,
acos, atan, atan2, sinh, cosh, tanh, int (convert to integer), float (convert to float),
pow, sqrt, fact (factorial), exp (power of e to x), log10 (log), ln or log (natural log),
and random. Additional functions can be added by means of external code
resources placed in Max's startup folder.

Messages
bang Evaluates the expression and sends out the results, using the most recently
received lists of numbers.
int number [int] An int or float received in any inlet is treated as a single-item list.
float number [float] An int or float received in any inlet is treated as a single-item list.
list numbers [list] The items of each list are used individually, in order from left to right, to replace
the changeable argument in a series of evaluations of the expression. When a list is
received in the left inlet, the expression is first evaluated using the first item of
each list, then using the second item of each list, etc. The series of results of these
evaluations is then sent out as a list.

Attributes
Name Type g/s Description
scalarmode int The word scalarmode, followed by a non-zero number, sets the scalar mode of
operation. In scalar mode, sending a list of length 1 (i.e., a single value) will cause
that value to be applied to each element of the other list. The message
scalarmode 0 disables scalar mode.

Information for box attributes common to all objects

Output
float: If the input in one of the inlets was a single number rather than a list, and the expression is evaluated as a float value, then
a single result is sent out as a float rather than a list.
int: If the input in one of the inlets was a single number rather than a list, and the expression is evaluated as an integer value,
then a single result is sent out as an int rather than a list.
list: When a list is received in the left inlet, vexpr uses the first item of the lists it has received in each of its different inlets, puts
those items in place of the changeable arguments in the expression, and evaluates the expression. It then does the same with the
second item in each list, and so on until it has used the last item of the shortest list. It then sends out all of the different results as
a single list.

Examples

Perform the same calculation on a whole list of input values

See Also
Name Description
expr Evaluate a mathematical expression
round Round to a value
Max Data Tutorial 5: List Max Data Tutorial 5: List Processing
Processing
when
Report the current transport time

Description
Outputs the current time of a transport in ticks and bars/beats/units.

Arguments
Name Units Type Opt Description
transport symbol The name of the transport for connection. Defaults to the global default transport.

Messages
bang Equivalent to anything.
int input [int] Equivalent to anything.
float input [float] Equivalent to anything.
list input [list] Equivalent to anything.
anything input [list] Any list or message causes the current time expressed in bars/beats/units to be
sent out the left outlet, and the current time in ticks to be sent out the right outlet.

Attributes
Name Type g/s Description
transport symbol The name of a transport object with which to associate. By default, the master
transport is used.

Information for box attributes common to all objects

Examples

See Also
Name Description
metro Output a bang message at regular intervals
translate Convert between different units of time.
timepoint Bang at a specific time
transport Control a master clock
xbendin
Interpret extra precision MIDI pitch bend values

Description
Acts as a 14-bit pitch bend filter/processor and xbendin2 serves as a 2-byte pitch bend filter/processor.

Arguments
Name Units Type Opt Description
channel int opt The number specifies a MIDI channel on which to recognize pitch bend messages.
If there is no argument, xbendin recognizes pitch bend messages on all channels,
and the channel number is sent out the extra outlet on the right.
xbendin2 symbol opt Normally, xbendin sends pitch bend values out the left outlet as 14-bit values. If
the object is called xbendin2, however, there will be an additional outlet. The
most significant data byte of the message is sent out the leftmost outlet, and the
least significant data byte is sent out the second outlet.

Messages
int input [int] The numbers are individual bytes of a MIDI message stream, received from an
object such as midiin or seq. MIDI pitch bend messages are recognized by
xbendin, and the pitch bend data is sent out in full precision.

Information for box attributes common to all objects

Output
int: The pitch bend value is sent out the left outlet of xbendin as a single 14-bit value. If the object is called xbendin2, there is
an additional outlet. The most significant 7 bits are sent out the leftmost outlet, and the least significant (extra precision) 7 bits
are sent out the second outlet. If there is no channel number specified as an argument (omni on), xbendin will have an extra
outlet on the right, which will output the channel number of the incoming pitch bend message.

Examples

Pitch bend values are sent out as a single number or as two separate bytes

See Also
Name Description
bendin Output MIDI pitch bend values
midiin Output raw MIDI data
xbendout Format extra precision MIDI pitch bend messages
xbendout
Format extra precision MIDI pitch bend messages

Description
Formats messages which occupy both bytes of the MIDI pitch bend message. xbendout2 allows you to send the pitch bend data
as two bytes from 0-127.

Arguments
Name Units Type Opt Description
xbendout2 symbol If the object is called xbendout2, there will be three inlets. The most significant
byte of the pitch bend message is received in the left inlet, and the least significant
(extra precision) byte is received in the middle inlet.
channel int opt The number sets an initial value for the MIDI channel of the pitch bend messages.
If there is no argument, the initial channel number is 1.

Messages
bang Sends out a MIDI pitch bend message using the numbers currently stored in
xbendout.
int input [int] The number is a 14-bit pitch bend value to be formatted into a complete MIDI
pitch bend message by xbendout.
(inlet1) channel [int] In right inlet: The number is stored as the MIDI channel for the pitch bend
message sent out by xbendout. Channel numbers greater than 16 will be wrapped
around to stay within the 1-16 range.
(inlet2) channel [int] The number is stored as the MIDI channel for the pitch bend message sent out by
xbendout. Channel numbers greater than 16 will be wrapped around to stay
within the 1-16 range.
list value [int] The first number is a 14-bit pitch bend value, and the second number is the
channel [int] channel. Both numbers are stored and are formatted into a MIDI pitch bend
message which is sent out the outlet.

Information for box attributes common to all objects

Output
int: When a pitch bend value is received in the left inlet, the complete MIDI pitch bend message is sent out the outlet, byte-by-
byte.

Examples

14-bit pitch bend value is formatted into a MIDI message, which is sent out byte-by-byte
See Also
Name Description
bendout Send MIDI pitch bend messages
midiout Transmit raw MIDI data
xbendin Interpret extra precision MIDI pitch bend values
xnotein
Interpret MIDI note messages with release velocity

Description
Arguments
Name Units Type Opt Description
channel int opt Specifies a channel number on which to look for incoming MIDI note-on and note-
off messages. Channel numbers greater than 16 will be wrapped around to stay
within the 1-16 range. If there is no argument, xnotein recognizes note-on and
note-off messages on all MIDI channels, and the channel number of the message
is sent out the rightmost outlet.

Messages
int input [int] The numbers are individual bytes of a MIDI stream from midiin. Whereas a note-
on with a velocity of 0 is most commonly used to indicate a note-off, xnotein also
recognizes the MIDI note-off command, and outputs its release velocity.

Information for box attributes common to all objects

Output
int: Out left outlet: The pitch value of the incoming note-on or note-off message.

Out 2nd outlet: The key-down or key-up velocity of a note-on or a note-off message.

Out 3rd outlet: The number is the indicator of whether the incoming MIDI message is a note-on or a note-off. If the incoming
message is a note-on, the output is 1. If the incoming message is a note-off--or a note-on with a velocity of 0--the output is 0.

If no channel number is specified as an argument, xnotein has a 4th outlet on the right. The channel number of incoming
messages is sent out the rightmost outlet.

Examples

Both note-on and note-off messages are interpreted, with a key-down or key-up velocity

See Also
Name Description
notein Receive MIDI note messages
midiin Output raw MIDI data
xnoteout Format MIDI note messages with release velocity
xnoteout
Format MIDI note messages with release velocity

Description
Arguments
Name Units Type Opt Description
channel int opt Sets an initial value for the MIDI channel of the outgoing messages. Channel
numbers greater than 16 will be wrapped around to stay within the 1-16 range. If
there is no argument, the initial channel number is 1.

Messages
bang Sends out a MIDI message using the numbers currently stored in xnoteout.
int input [int] In left inlet: The number is used as the pitch value for a note-on or note-off
message, and the message is sent out the outlet byte-by-byte.

In left-middle inlet: The number is stored as the velocity for either a note-on or a
note-off message. If no number has been received yet, the velocity for note-ons is
64, and the velocity for note-offs is 0.

In right-middle inlet: The number is stored as the indicator of whether outgoing


messages should be note-ons or note-offs. If the number is not 0, xnoteout will
send out a note-on message. If the number is 0, xnoteout will send out a note-off
message with a release velocity. If no number has been received yet, it is initially 1
(note-on).

In right inlet: The number is stored as the channel for the MIDI message sent out
by xnoteout. Channel numbers greater than 16 will be wrapped around to stay
within the 1-16 range.
(inlet1) ARG_NAME_0 [int] TEXT_HERE
(inlet2) ARG_NAME_0 [int] TEXT_HERE
(inlet3) ARG_NAME_0 [int] TEXT_HERE
list pitch [int] The first number is the pitch value, the second number is the velocity, the third
velocity [int] number is the note-on/note-off indicator (non-zero for note-on, 0 for note-off),
note-flag [int] and the fourth number is the channel. The numbers are stored by xnoteout, and a
channel [int] MIDI note-on or note-off message is sent out.

Information for box attributes common to all objects

Output
int: When a pitch value is received, a complete MIDI note-on or note-off message is sent out the outlet, byte-by-byte. Whereas a
note-on with a velocity of 0 is most commonly used to indicate a note-off, xnoteout sends out the MIDI note-off command and
uses the specified velocity as a release velocity.

Examples
The numbers are formatted into a MIDI note-on or note-off message, which is sent out byte-by-byte

See Also
Name Description
noteout Transmit MIDI note messages
midiout Transmit raw MIDI data
xnotein Interpret MIDI note messages with release velocity
zl
Process lists in many ways

Description
Performs several kinds of list processing functions. You set the function with an argument, and can change the function
performed with the mode message. The behavior of the zl object's inlets and outlets vary according to the selected mode.

Arguments
Name Units Type Opt Description
length int opt An optional integer arg sets the maximum list length for all modes of operation for
the zl object. The default list length is 256.
mode symbol The words change, compare, delace, ecils, group, iter, join, lace, len, lookup,
median, mth, nth, queue, reg, rev, rot, scramble, sect, slice, sort, stack,
stream, sub, sum, thin, union, or unique are used as optional arguments to set
the mode of the zl object. See the mode message for descriptions of the different
modes.
function-int int opt For the following modes of operation, an additional number may be used as an
argument to specify the functionality of a given mode:

ecils: Specifies the number of list items beginning at the end of the input list to be
sent out the right outlet of the zl object.

group: Specifies a number of the most recently stored list items to be output.

iter: The currently stored contents of the zl object will be output as a series of lists
consisting of the number of items specified by this value.

mth: Specifies the order of an element in the input list (using 0 as the index of the
first element of the list) and outputs that element of the list.

nth: Specifies the order of an element in the input list in numerical form (i.e.,
1="the" index of the first element of the list) and outputs that element of the list.

rot: Specifies the number of places to rotate the currently stored list. Positive
values for rotate the list right, and negative values rotate left.

slice: Specifies the number of list items to be sent out the left outlet of the zl
object.

stream: Specifies the length of the output list. The object will collect this number
of items input through the left inlet. After the list-length is complete, the list will
be output the left outlet. A 1 or a 0 will be output from the right outlet depending
on whether the list-length has been defined or not. A 1 signifies that the list-
length has been defined and that the object is now collecting the stream.
function-list list opt For the following modes of operation, an additional list may be used as an
argument to specify the functionality of a given mode:

filter: The object will accept a list in as an argument. A list in the left inlet will
cause the object to immediately output a version of the input-list that does not
contain the elements specified in the argument list. The object will also output a
list of the indices of all filtered list items. A list in the right inlet will set the list of
items to be filtered without causing output.

lookup: The object will accept a list in as an argument. A number in the right inlet
will cause the object to output the element located at the list index specified by the
number received in the left inlet. (if 6.2 3 5.6 5.3 3.8 2.4 is received in the right
inlet, a 2 received in the left inlet will cause the object to output 5.6 out of the left
output).

reg: In this mode, the object functions as a register that holds a list. The object
will accept a list as an argument to set the initial stored content of the object.

Messages
bang In left inlet: A bang message will output the most recent list or value calculated.
Many modes of the zl object take inputs through their right inlet which will only
set the input without triggering output. In these cases, a subsequent bang received
in the left inlet will trigger the output.
int input [int] In right inlet: Some modes of zl accept an int in the right inlet and behave as
follows:

ecils: Specifies the number of list items beginning at the end of the input list to be
sent out the right outlet of the zl object. Any remaining list elements beyond the
number specified by this inlet are sent out the left outlet of the object.

group: Specifies a number of the most recently stored list items to be output.

iter: The currently stored contents of the zl object will be output as a series of lists
consisting of the number of items specified by this value. The final list output may
be shorter than the number, depending on the stored contents of the object.

mth: Specifies the order an element in the input list (using 0 as the index of the
first element of the list) and outputs that element of the list.

nth: Specifies the order an element in the input list in numerical form (i.e., 1=the
index of the first element of the list) and outputs that element of the list.

rot: Specifies the number of places to rotate the currently stored list. Positive
values for rotate the list right, and negative values rotate left.

slice: Specifies the number of list items to be sent out the left outlet of the zl
object. Any remaining list elements beyond the number specified by this inlet are
sent out the right outlet of the object.

sort: Specifies the sorting order. sort -1 sorts the input list in descending order,
and the sort message with any other value sorts the input list in ascending order.

stream: Specifies the output list length.


float input [float] Performs the same function as int but with floats.
list input [list] In left inlet: The behavior of the zl object to lists received in the left inlet varies
according to the mode of the object, as described under the mode message.
anything input [list] Allows for the recognition of lists that begin with symbols.
mode mode [symbol] The word mode, followed by one of the symbols change, compare, delace, ecils,
setting [int] group, iter, join, lace, len, lookup, median, mth, nth, queue, reg, rev, rot,
scramble, sect, slice, sort, stack, stream, sub, sum, thin, union, or unique
sets the current mode of the zl object. The modes are:

change: accepts a list in both inlets. A list in the left inlet will trigger output while
a list in the right inlet will only set the input without causing output. The object
will output the input list only if it is different from the list which was last received.
If it is different, the new list is sent out the left outlet along with a 1 out the right
outlet. If the list is not different, nothing is sent out the left outlet while a 0 is sent
out the right outlet.

compare: accepts a list in both inlets. A list in the left inlet will trigger output
while a list in the right inlet will only set the input without causing output. If the
lists in both inlets are the same, a 1 is sent out the left outlet. If the two lists differ,
a 0 is sent out the left outlet and a list of the indices for those elements of the lists
that differ are sent out the right outlet.

delace: accepts a list in the left inlet and will output a list out of both outlets
which consists of every other element in the input list (if the input list is 6.2 3 5.6
5.3 3.8 2.4 the left output list is 6.2 5.6 3.8 and the right output list is 3 5.3
2.4).

ecils: is used to divide a list into two lists. This mode takes an additional number
argument which specifies the size, in elements, of a list. This value can also be
specified as an input in the right inlet in this mode. A list received in the left inlet
will be split into two lists -- the first list contains the number of items specified by
the argument beginning from the end of the list and counting backward toward
the first list element, and is sent out the right outlet. Any remaining list elements
are sent out the left outlet of the object. Note: Lists are sent out the right outlet
first.

group: takes an additional number argument which specifies the size, in elements,
of a list. A list received in the left inlet will be stored and the length of the list is
compared to a number received in the right inlet or an argument to the zl object.
If the list of items is longer than the number specified by the right inlet or
argument, a list of items of the length specified by the number is sent out the left
outlet. Any remaining symbols or list elements are stored.

iter: takes an additional number argument which specifies the size, in elements, of
a list. A symbol list of items received in the left inlet will be stored and sent out the
left outlet as a series of lists consisting of the number of items specified by
argument or by a number received in the right inlet. The final list output may be
shorter than the specified number of items, depending on the stored contents of
the zl object.

join: accepts a list in both inlets and sends a list out the left outlet which is the
combination of both input lists.

lace: accepts a list in both inlets and will output a list out the left outlet populated
with items from both input lists interlaced with each other (if the left input list is
6.2 5.6 3.8 and the right input list is 3 5.3 2.4 the output list is 6.2 3 5.6 5.3
3.8 2.4).

len: accepts a list in the left inlet and outputs number of elements in the list out
the left outlet.

lookup: accepts a list in the right inlet. Following receipt of this list, a number in
the left inlet will cause the object to output the element located at the list index
specified by the number received in the left inlet.(if 6.2 3 5.6 5.3 3.8 2.4 is
received in the right inlet, a 2 received in the left inlet will cause the object to
output 5.6 out of the left output).

median: accepts a list of numbers and will output the median of those numbers.

mth: works exactly like mode nth mode, except the list index numbering begins
with 0 as opposed to 1.

nth: accepts a list in the left inlet and outputs the nth element of the list out the
left outlet.

queue: functions as a first-in-first-out (FIFO) stack; it outputs the oldest message


received.
reg: functions as a register that holds a list. A list received in the left inlet is sent
out the left outlet immediately. A list received in the right inlet is stored. A bang
sends the stored list out the left outlet.

rev: accepts a list in its left inlet and sends the list out the left outlet in reverse
order.

rot: is used to rotate the contents of a list. An additional argument is used to


specify the number of places a list item is to be rotated - positive numbers rotate
the list to the right, and negative numbers rotate left. This value can also be
specified as an input in the right inlet in this mode.

scramble: accepts a list in either inlet. A list in the left inlet will cause the object
to immediately output a scrambled version of the input-list (a list containing the
same elements as the input-list but in a randomized order). A list in the right inlet
will set the input-list without causing output (a subsequent bang received in the
left inlet will cause a randomized version of the right-input list to be sent out the
object's left outlet).
sect: accepts a list in both inlets and sends a list out the left outlet that contains
the elements common to both lists.

slice: is used to divide a list into two lists. This mode takes an additional number
argument which specifies the size, in elements, of a list. This value can also be
specified as an input in the right inlet in this mode. A list received in the left inlet
will be split into two lists - the first list contains the number of items specified by
the argument, and is sent out the left outlet. Any remaining list elements are sent
out the right outlet of the object. Note: Lists are sent out the right outlet first.

sort: is used to sort the contents of a list. An additional argument is used to


specify the sorting order. sort -1 sorts the input list in descending order, and the
sort message with any other value sorts the input list in ascending order. This
value can also be specified as an input in the right inlet in this mode.

stream: accepts a number in the right inlet which specifies the length of the
output list. Following the receipt of this number, the object will collect this
number of items input through the left inlet. After the list-length is complete, the
list will be output the left outlet. A 1 or a 0 will be output from the right outlet
depending on whether the list-length has been defined or not. A 1 signifies that
the list-length has been defined and that the object is now collecting the stream.

sub: accepts a list in both inlets and sends the output position for each occurrence
of right list in the left list out the left outlet.

stack: functions as a last-in-first-out (LIFO) stack; it outputs the most recently


received message.

stream: will output the last N items in a list, where N is user-specifiable.

sum: accepts a list of numbers and will output the sum of those numbers.

thin: accepts a list in the left inlet and will output a list containing all the elements
of the input list which are not duplicates.

union: accepts a list in both inlets and sends a list out the left outlet that contains
the contents of both input lists. If the left and right inlets contain any items in
common, only one symbol will be output.

unique: accepts a list in both inlets and will output a list out the left outlet
populated with items from the left-input-list which were not present in the right-
input-list.
zlclear Reinitializes the zl object.

Attributes
Name Type g/s Description
zlmaxsize int Set the maximum list length for all modes of operation for the zl object. This is the
equivalent to using an argument to the object, but allows the list length to be
changed dynamically. The default list length is 256.

Information for box attributes common to all objects

Output
list: Out left outlet:

In change mode, the input list only if it is different from the list which was last received. If it is different, the new list is sent out
the left outlet. If the list is not different, nothing is sent out the left outlet.

In delace mode, a list which consists of every other element in the input list starting with the first element (if the input list is 6.2
3 5.6 5.3 3.8 2.4 the left output list is 6.2 5.6 3.8).

In ecils mode, a list containing the number of elements specified by the number argument starting at the end of the list and
counting toward the beginning.

In filter mode, a list with elements matching the filtering list removed.

In group mode, a list containing the number of elements specified by the number argument.

In iter mode, a number of lists having the number of elements specified by the number argument. The final list output may be
shorter than the specified number of items, depending on the stored contents of the zl object

In join mode, a list containing all the elements of the lists received in both inlets.

In lace mode, a list populated with items from both input lists interlaced with each other (if the left input list is 6.2 5.6 3.8 and
the right input list is 3 5.3 2.4 the output list is 6.2 3 5.6 5.3 3.8 2.4).

In len mode, a number which corresponds to the number of list items.

In lookup mode, the list element located at the list index specified by the number received in the left inlet.(if 6.2 3 5.6 5.3 3.8
2.4 is received in the right inlet, a 2 received in the left inlet will cause the object to output 5.6 out of the left output).

In median mode, the median of the input-list.

In mth mode, the mth element of the list (where 0 is the index of the first element of the list).

In nth mode, the nth element of the list.

In queue mode, the oldest element received.

In reg mode, the input or the most recently stored input value received in the right inlet.

In rev mode, the input list in reverse order.

In rotate mode, the input list rotated to the right or left according to the positive or negative specified by the number argument.

In scramble mode, a scrambled version of the input-list (a list containing the same elements as the input-list but in a
randomized order).

In sect mode, a list containing all the elements common to the lists received in both inlets.
In slice mode, a list containing the number of elements specified by the number argument.

In stack mode, the most recently received message.

In stream mode, the stream or list consisting of the element to be collected a specified number of times.

In sum mode, the sum of the input-list.

In thin mode, a list containing all the elements of the input list which are not duplicates.

In union mode, a list containing the items from both lists without repeating items common to both lists. If the left and right
inlets contain any items in common, only one symbol will be output.

In unique mode, a list populated with items from the left-input-list which were not present in the right-input-list.
list:

Out the right outlet:

In change mode, if the input-list is different from the last one received, a 1 is sent out the right outlet. If the list is not different,
nothing is sent out the left outlet while a 0 is sent out the right outlet.

In delace mode, a list which consists of every other element in the input list starting with the second element (if the input list is
6.2 3 5.6 5.3 3.8 2.4, the right output list is 3 5.3 2.4).

In ecils mode, a list containing any list elements before the numbered element specified by the number argument.

In filter mode, a list of the index numbers of list elements not filtered out.

In mth mode, a list containing all list elements except for the list element specified by the number argument (where 0 is the index
of the first element in the list).

In nth mode, a list containing all list elements except for the list element specified by the number argument (where 1 is the index
of the first element in the list).

In slice mode, a list containing any list elements beyond the numbered element specified by the number argument.

In sect mode, a bang will be sent out the right outlet if the two input lists contain no common elements.

In sub mode, the number of list elements specified by the number argument in the left input list is sent out the right outlet of the
object. If an optional second argument is used to specify a value which will replace the number specified by the input value, the
resulting list is sent out the right outlet of the zl object.

In stream mode, a 1 or a 0 will be output from the right outlet depending on whether the list-length has been defined or not. A 1
signifies that the list-length has been defined and that the object is now collecting the stream.

In change mode, if the input-list is different from the last one received, the new list is sent out the left outlet along with a 1 out
the right outlet. If the list is not different, nothing is sent out the left outlet while a 0 is sent out the right outlet.

Examples
zl is the Swiss Army Knife for lists

See Also
Name Description
fromsymbol Convert a symbol into numbers/messages
join Combine items into a list
maximum Output the highest value
minimum Output the smallest value
mean Calculate a running average
pack Create a list
regexp Use regular expressions to process input
swap Swap position of two numbers
thresh Combine messages when received close together
tosymbol Convert messages, numbers, or lists to a single symbol
unjoin Break a list into messages
unpack Break a list into individual messages
Max Data Tutorial 5: List Max Data Tutorial 5: List Processing
Processing
Tutorial 11: Lists and Matrices Tutorial 11: Lists and Matrices
zmap
Maps input range of values to output range

Description
Maps an input range of values and to an output range of values. Similar to scale, but clips values to the ranges, and does not
allow inverted scaling.

Arguments
Name Units Type Opt Description
minimum-input number The minimum input value. If the low values is higher than the corresponding high
value, the two values are reversed to preserve the high-low relationship.
maximum-input number The maximum input value. If the low values is higher than the corresponding high
value, the two values are reversed to preserve the high-low relationship.
minimum-output number The minimum output value. If the low values is higher than the corresponding
high value, the two values are reversed to preserve the high-low relationship. The
zmap object will clip to the boundaries of the output range.
maximum-output number The maximum output value. If the low values is higher than the corresponding
high value, the two values are reversed to preserve the high-low relationship. The
zmap object will clip to the boundaries of the output range.

Messages
int input [int] Converted to float.
float input [float] In left inlet: The incoming value is scaled according to the mapping provided by
the arguments, or values received in the other inlets.
Note: The preservation of the high-low relationship is different from the behavior
of the scale object, which lets you do reverse scaling. Also, note that the zmap
object will clip to the boundaries of the output range.
(inlet1) minimum-input [float] In second inlet: Sets the low input value. If the value is higher than the high input
value, the two values are reversed to preserve the high-low relationship.
(inlet2) maximum-input [float] In third inlet: Sets the high input value. If the value is lower than the low input
value, the two values are reversed to preserve the high-low relationship.
(inlet3) minimum-output [float] In fourth inlet: Sets the low output value. If the value is higher than the high
output value, the two values are reversed to preserve the high-low relationship.
(inlet4) maximum-output [float] In right inlet: Sets the high output value. If the value is higher than the high
output value, the two values are reversed to preserve the high-low relationship.
list input [list] In left inlet: A list of numbers sent to the left inlet will trigger the output of a list
consisting of the results of performing the specified scaling operation on each item
in the input list.

Information for box attributes common to all objects

Output
float: When zmap receives a value in its leftmost inlet, that value is scaled to the indicated output range of values.

Examples
An example of how to map an integer slider into a useful range of floating-point values and back again

See Also
Name Description
scale Map values to an output range
expr Evaluate a mathematical expression
MSP Reference
2d.wave~
Two-dimensional wavetable

Description
2d.wave~ is similar to wave~, but with an additional axis. A given ms range of an audio file will be divided into n rows. Y phase
input will determine which row(s) will be used for playback.

Arguments
Name Units Type Opt Description
buffer-name symbol Obligatory. Names the buffer~ object whose sample memory is used by 2d.wave~
for its stored waveform. Note that if the underlying data in a buffer~ changes, the
signal output of 2d.wave~ will change, since it does not copy the sample data in a
buffer~. 2d.wave~ always uses the first n channels of a multi-channel buffer~,
where n is the number of the 2d.wave~ object's output channels. The default
number of channels, set by the third argument to the 2d.wave~ object, is 1.
start and end- number opt After the buffer~ name argument, you can type in values for the start and end
points points of the waveform, as millisecond offsets from the beginning of a buffer~
object's sample memory. By default the start point is 0 and the end point is the
end of the sample. If you want to set a non-zero start point but retain the sample
end as the waveform end point, use only a single typed-in argument after the
buffer~ name. If a signal is connected to the start point (middle) inlet, the initial
waveform start point argument is ignored. If a signal is connected to the end point
(right) inlet, the initial waveform end point is ignored. The number of channels in
the buffer~ file and the number of rows to be used may also be specified.
number-of- int opt Sets the number of output channels, which determines the number of outlets that
output-channels the 2d.wave~ object will have. The maximum number of channels is 8. The
default is 1. If the audio file being played has more output channels than the
2d.wave~ object, higher-numbered channels will not be played. If the audio file
has fewer channels, the signals coming from the extra outlets of 2d.wave~ will be
0.

Messages
int start and end-points [int] In 3rd or 4th inlets: Numbers can be used instead of signal objects to control the
start and end points of the waveform, provided a signal is not connected to the
inlet that receives the number.
float start and end-points [float] In 3rd or 4th inlets: Numbers can be used instead of signal objects to control the
start and end points of the waveform, provided a signal is not connected to the
inlet that receives the number.
(mouse) Double-clicking on the 2d.wave~ object will open a window that displays the
audio file loaded in the buffer associated with the object.
set buffer-name [symbol] The word set, followed by a symbol, sets the buffer~ used by 2d.wave~ for its
start-point [float] stored waveform. The symbol can optionally be followed by two values setting new
end-point [float] waveform start and end points. If the values are not present, the default start and
end points (the start and end of the sample) are used. If signal objects are
connected to the start and/or end point inlets, the start and/or end point values
are ignored.
rows number-of-divisions [int] The word rows, followed by an int, sets the number of rows a given range of an
audio file will be divided into. The phase input signal value received in the 2nd
inlet of 2d.wave~ determines which row(s) are used for playback. The default
value is 0.
signal In left inlet: Input signal values progressing from 0 to 1 are used to scan a
specified range of samples in a buffer~ object. The output of a phasor~ can be
used to control 2d.wave~ as an oscillator, treating the range of samples in the
buffer~ as a repeating waveform. However, note that when changing the
frequency of a phasor~ connected to the left inlet of 2d.wave~, the perceived
pitch of the signal coming out of 2d.wave~ may not correspond exactly to the
frequency of phasor~ itself if the stored waveform contains multiple or partial
repetitions of a waveform. You can invert the phasor~ to play the waveform
backwards.

In 2nd inlet: Input signal values progressing from 0 to 1 are used to determine
which of the row(s) specified by the rows message will be used for playback. You
can invert the phasor~ to reverse the order in which rows are played.

In 3rd inlet: The start of the waveform as a millisecond offset from the beginning
of a buffer~ object's sample memory.

In 4th inlet: The end of the waveform as a millisecond offset from the beginning of
a buffer~ object's sample memory.

Information for box attributes common to all objects

Output
signal: The portion of the buffer~ specified by the 2d.wave~ object's start and end points is scanned by signal values ranging
from 0 to 1 in the 2d.wave~ object's inlet, and the corresponding sample value from the buffer~ is sent out the 2d.wave~
object's outlet. If the signal received in the object's inlet is a repeating signal such as a sawtooth wave from a phasor~, the
resulting output will be a waveform (excerpted from the buffer~) repeating at the frequency corresponding to the repetition of
the input signal.

Examples

Loop through part of a sample, treating it as a variable-size wavetable

See Also
Name Description
buffer~ Store audio samples
groove~ Variable-rate looping sample playback
phasor~ Generate sawtooth signals
play~ Position-based sample playback
wave~ Variable size wavetable
MSP Tutorial 15: Variable-length MSP Tutorial 15: Variable-length Wavetable
Wavetable
abs~
Absolute value of a signal

Description
Use the abs~ object to take any given signal and output only the absolute (non-negative) translation of that signal (i.e. a rectified
waveform). All negative values in the input signal are converted to positive values in the output.

Arguments
None.

Messages
signal The abs~ object takes an input signal and output only the absolute (non-negative)
translation of that signal - all negative values in the input signal are converted to
positive values in the output.

Information for box attributes common to all objects

Output
signal: A signal consisting of samples which are the absolute (i.e., non-negative) value of the samples in the input signal.

Examples

Convert negative signal values to positive signal values

See Also
Name Description
avg~ Signal average
acos~
Signal arc-cosine function

Description
Use the acos~ object to calculate and output a signal that is the arc-cosine function of each sample of the input signal.

Arguments
None.

Messages
signal Input to arc-cosine function

Information for box attributes common to all objects

Output
signal: The arc-cosine of the input in radians.

Examples

Using acos~ to create an inverse linear ramp in radians

See Also
Name Description
acosh~ Signal hyperbolic arc-cosine function
cos~ Signal cosine function (0-1 range)
cosh~ Signal hyperbolic cosine function
cosx~ Signal cosine function
acosh~
Signal hyperbolic arc-cosine function

Description
Use the acosh~ object to calculate and output a signal that is the hyperbolic arc-cosine function of each sample of the input
signal.

Arguments
None.

Messages
signal Input to hyperbolic arc-cosine function

Information for box attributes common to all objects

Output
signal: The hyperbolic arc-cosine of the input.

Examples

See Also
Name Description
acos~ Signal arc-cosine function
cos~ Signal cosine function (0-1 range)
cosh~ Signal hyperbolic cosine function
cosx~ Signal cosine function
adc~
Audio input and on/off

Description
adc~ is the audio-to-digital converter for a signal-processing patch which can be used to route signal inputs from external devices
or inputs into your patch. It can also be used to turn MSP's signal-processing on or off entirely.

Arguments
Name Units Type Opt Description
inputs int opt You can create a adc~ object that uses one or more audio input channel numbers
between 1 and 512. These numbers refer to logical channels and can be
dynamically reassigned to physical device channels of a particular driver using
either the Audio Status window, its I/O Mappings subwindow, or an adstatus
object with an input keyword argument. If the computer's built-in audio hardware
is being used, there will be two input channels available. Other audio drivers
and/or devices may have more than two channels. If no argument is typed in,
adc~ will have two outlets, initially set to logical input channels 1 and 2.

Messages
int on/off-flag [int] A non-zero number turns on audio processing in all loaded patches. 0 turns off
audio processing in all loaded patches.
list input-channel- list comprised of integers sets the logical input channels for each signal inlet.
designations [list]
(mouse) Double-clicking on adc~ opens the Audio Status window.
open Opens the Audio Status window.
set logical-output-channel The word set, followed by two numbers, sets the logical input channel for one of
[int] the object's signal outlets. The first number specifies the outlet number, where 1 is
logical-input-channel the leftmost outlet. The second number specifies the logical input channel (from 1
[int] to 512). If the second number is 0, the outlet sends out the zero signal.
start Turns on audio processing in all loaded patches.
startwindow Turns on audio processing only in the patch in which this adc~ is located, and in
subpatches of that patch. Turns off audio processing in all other patches.
stop Turns off audio processing in all loaded patches.
wclose Closes the Audio Status window if it is open

Information for box attributes common to all objects

Output
signal: The signal arriving at the computer's input is sent out, one channel per outlet. If there are no typed-in arguments, the
channels are 1 and 2, numbered left-to-right; otherwise the channels are in the order specified by the arguments.

Examples
Audio input for processing and recording

See Also
Name Description
adstatus Report and control audio driver settings
ezadc~ Audio input and on/off button
ezdac~ Audio output and on/off button
dac~ Audio output and on/off
MSP: Audio Input and Output MSP: Audio Input and Output
MSP Tutorial 13: Recording and MSP Tutorial 13: Recording and Playback
Playback
adoutput~
Access audio driver output channel

Description
Use the adoutput~ object to record the current audio output or to feed it back into your patcher. The output of adoutput~ is
delayed by one signal vector with respect to the actual output.

Arguments
Name Units Type Opt Description
audiodriver-output- int opt The arguments specify output channels of the current audiodriver. There is no
channels limit to the number of channels you can specify. By default, adoutput~ creates
two outlets and assigns the audio output from channels 1 and 2 of the current
audiodriver to them. Note that these channel numbers are not the same as the
logical channel numbers used by the dac~ and adc~ objects, but represent the
"physical" outputs of the driver after any remapping has taken place. You configure
the relationship between logical dac~ channels and the audiodriver's real channels
with the I/O Mappings subwindow of the Audio Status window.

Messages
set outlet-index [int] The word set, followed by two numbers, assigns an audio driver output channel to
audiodriver-output-channel-index a signal outlet of the adoutput~ object. The first number is the index of the outlet,
[int] where a value of 0 refers to the left outlet. The second number is the index of the
audio driver output device channel where 1 refers to the first channel. If the
second number is 0, the specified outlet is turned off and outputs a zero signal.

Information for box attributes common to all objects

Output
signal: Each outlet of adoutput~ outputs a signal from the assigned audiodriver channel, delayed by the number of samples of
the current signal vector size.

Examples

Capture the output of physical DAC channels to record/re-process the output of your patch

See Also
Name Description
adstatus Report and control audio driver settings
dac~ Audio output and on/off
adsr~
ADSR envelope generator

Description
Use the adsr~ object when you need a sample-accurate Attack-Decay-Sustain-Release signal envelope which can be controlled by
signals. In some situations, a combination of the function and line~ objects may be a useful alternative.

Arguments
Name Units Type Opt Description
attack float opt A floating-point value specifies the initial values for the attack parameter.
decay float opt A floating-point value specifies the initial values for the decay parameter.
sustain float opt A floating-point value specifies the initial values for the sustain parameter.
release float opt A floating-point value specifies the initial values for the release parameter.

Messages
int trigger/ADSR-parameters In left inlet: Like an adsr~ object triggered by a signal input, a floating-point value
[int] triggers an envelope with the given amplitude. The envelope will sustain until a
zero is input to trigger the release stage, or until another non-zero float retriggers
the envelope.

In second inlet: sets the envelope's attack time, in milliseconds.

In third inlet: sets the envelope's decay time, in milliseconds.

In fourth inlet: sets the envelope's sustain level, as a factor of the amplitude. For
example, a value of 2 means the sustain level will be twice the value of the
amplitude height.

In fifth inlet: sets the envelope's release time, in milliseconds.


float trigger/ADSR-parameters In left inlet: Like an adsr~ object triggered by a signal input, an int value triggers
[float] an envelope with the given amplitude. The envelope will sustain until a zero is
input to trigger the release stage, or until another non-zero int retriggers the
envelope.

In second inlet: sets the envelope's attack time, in milliseconds.

In third inlet: sets the envelope's decay time, in milliseconds.

In fourth inlet: sets the envelope's sustain level, as a factor of the amplitude. For
example, a value of 2 means the sustain level will be twice the value of the
amplitude height.

In fifth inlet: sets the envelope's release time, in milliseconds.


list attack [float] In left inlet: A list of 4 floating-point numbers will assign the values for the attack,
decay [float] decay, sustain and release portions of the ADSR-envelope consecutively.
sustain [float]
release [float]
anything attack [float] In left inlet: Performs the same function as list.
decay [float]
sustain [float] Any other inlet: A list may be used to specify time in one of the Max time
release [float] formats.
signal In left inlet: Any non-zero value will trigger an envelope with that value as its
amplitude. Like an adsr~ triggered by an input float, a zero value represents
"note-off" and will begin the release stage. Unlike the event-triggered model, a
signal-triggered adsr~ must receive a zero before it will retrigger.

In second inlet: sets the envelope's attack time, in milliseconds.

In third inlet: sets the envelope's decay time, in milliseconds.

In fourth inlet: sets the envelope's sustain level, as a factor of the amplitude. For
example, a value of 0.5 means the sustain level will be half of the amplitude
height.

In fifth inlet: sets the envelope's release time, in milliseconds.

Attributes
Name Type g/s Description
attack atom Sets the attack of the ADSR-envelope in milliseconds.
decay atom Sets the decay of the ADSR-envelope in milliseconds.
legato int Given as input, the word legato, followed by a 0 or a non-zero number, disables
or enables legato mode. If legato mode is enabled, the envelope will not drop to
zero in the event of a retrigger while the envelope is active - instead, the envelope
ramps to the new amplitude over the attack period.
maxsustain float Given as input, the word maxsustain, followed by a float, sets the maximum
amount of time that the envelope will remain in the sustain stage. A negative
number sets no maximum; the envelope will remain forever in the sustain stage
until a note-off is received. To create a simple three-stage sustainless envelope (an
ADR), you can use the message maxsustain 0.0.
release atom Sets the release of the ADSR-envelope in milliseconds.
retrigger float Given as input, the word retrigger, followed by a float, sets the amount of time
taken to ramp down to zero in the event of a retrigger while the envelope is active
(the default is 10 milliseconds). This ramping prevents clicking.
sustain float Sets the sustain of the ADSR-envelope in milliseconds.

Information for box attributes common to all objects

Output
message: The right outlet sends mute messages suitable for managing internal poly~ instance muting with the thispoly~ object.
message: The fourth outlet responds to query messages for the various attributes (i.e. getattack).
signal: Left outlet: the envelope.

Middle outlet: signals the beginning of an envelope by sending 1 when in the attack, decay, or sustain stages and 0 otherwise
(release, retrigger, or inactive). You can use this outlet in conjunction with the sah~ object to synchronize pitch (or other
information) with the beginning of an envelope with sample accuracy.

Examples
Use adsr~ to manage the polyphony and muting for a sampler or synthesizer patch internal to a poly~ object

See Also
Name Description
function Graphically edit a breakpoint function
line~ Linear ramp generator
techno~ Signal-driven step sequencer
transport Control a master clock
zigzag~ Linked list function editor
adstatus
Report and control audio driver settings

Description
Use the adstatus object to control Max audio settings.

Arguments
Name Units Type Opt Description
Controllable- symbol The first argument is a symbol that specifies the setting to be controlled by the
settings: adstatus object. Some settings require an additional integer argument. The
possible settings are:

cpu: Reports current CPU utilization.


cpulimit: Reports and sets the CPU utilization limit as a percentage from 0-100.
driver: Lists the available audio drivers and allows the current one to be changed.
info: Reports the number of function calls and signals used in the top level
input (Requires an additional argument specifying a logical channel number (used
by the adc~ object) between 1 and 512): Lists the available audio driver input
channels and allows the current setting to be changed.
iovs: Reports the available I/O vector sizes of the current audio driver and
latency: If supported by the audio driver, reports the input and output latencies of
the driver in samples.
numinputs: Reports the number of input channels of the current audio driver.
numoutputs: Reports the number of output channels of the current audio driver.
optimize: Turns the optimization flag on or off. On the Macintosh, this is used to
control the use of Altivec (G4 processor) optimizations.
option (Requires an additional argument specifying the option number (starting at
1): If the current audio driver uses the numbered option, reports the available
choices for setting the value of the option.
optionname (Requires an additional argument specifying the option number
(starting at 1): If the current audio driver uses the numbered option, the name of
the option is reported.
output (Requires an additional argument specifying a logical channel number
(used by the dac~ object) between 1 and 512): Lists the available audio driver
output channels and allows the current setting to be changed.
overdrive: Controls the setting of overdrive mode (where the scheduler runs in a
sigvs: Reports the available signal vector sizes and allows the current signal vector
size setting to be changed.
sr: Reports the available sampling rates and allows the current sampling rate
setting to be changed.
switch: Turns the DSP on or off.
takeover: Controls the setting of scheduler in audio interrupt mode.
timecode: If supported by the audio driver, reports the current timecode value.

Messages
bang In left inlet: Reports the current state of the setting. In many cases, messages are
sent out the adstatus object's left outlet to set a pop-up menu object to display the
current setting with a set message. In these cases, the numerical value of the
setting is sent out the adstatus object's right outlet. The exact behaviors are listed
in the Output section below.
int input [int] In left inlet: Changes the setting. In most cases, the number will correspond to the
index of the menu item whose value was set by the bang message to adstatus.
(inlet1) input [int] In right inlet: If the adstatus object is used with the input, iovs, output, sigvs, sr
settings, an int in the right inlet sets the value numerically rather than by using a
menu index (see the reset or loadbang messages). For all other settings, a
number in the right inlet behaves identically to one in the left inlet.
float input [float] In left inlet: Changes the setting. In most cases, the number will correspond to the
index of the menu item whose value was set by the bang message to adstatus.
loadbang In left inlet: Reports the state of the setting upon loading the patch. In many cases,
messages are sent out the adstatus object's left outlet to set a pop-up menu object
to display the current setting with a set message. In these cases, the numerical
value of the setting is sent out the adstatus object's right outlet. The exact
behaviors are listed in the Output section below.
override flag [int] In left inlet: The word override, followed by a 1, turns on override mode for the
setting associated with the object. When override mode is enabled, any change to
the setting is not saved in the MSP Preferences file. The message override 0 turns
override mode off. By default, override is off for all settings. However, some
settings are specific to audio drivers and may not be saved by the driver.
set logical-channel-number In left inlet: The word set, followed by a number between 1 and 512, changes the
[int] logical channel associated with an adstatus input or adstatus output object. The
current real audio driver input or output channel set for the new logical channel is
sent out the object's outlets.
update TEXT_HERE

Information for box attributes common to all objects

Output
cpu: Reports CPU utilization as a percentage (normally from 0 to 100).
cpulimit: Reports the current CPU utilization limit.
driver: Lists all current audio driver choices.
float: Out left outlet: For objects that don't use a menu-style output, the current value of the setting is sent out the left outlet.
Here are details for specific settings:
float: Out right outlet: Here are the objects that output something out the value outlet of the object:
info: Reports the number of function calls used in the top-level DSP chain.
info: Reports the number of signals used in the top-level DSP chain.
input: Lists audio input channels for the audio driver currently in use.
input: Reports the current input channel for the specified logical channel.
int: Out left outlet: For objects that don't use a menu-style output, the current value of the setting is sent out the left outlet. Here
are details for specific settings:
int: Out right outlet: Here are the objects that output something out the value outlet of the object:
iovs: Lists I/O vector sizes for the audio driver currently in use.
iovs: Reports the current I/O vector size.
latency: If supported by the audio driver, reports the input latency of the audio driver.
numinputs: Reports the number of inputs in the current audio driver.
numinputs: Reports the number of inputs in the current audio driver (same as left outlet).
numoutputs: Reports the number of outputs in the current audio driver.
numoutputs: Reports the number of outputs in the current audio driver (same as left outlet).
optimize: Creates an On/Off menu for use with this setting.
option: Creates a list of choices for the specified option.
option: Reports the menu item index of the option's current value.
optionname: Sets a menu that names the specified option. Intended for use with a pop-up menu object in label mode.
output: Lists audio output channels for the audio driver currently in use.
output: Reports the current output channel for the specified logical channel.
overdrive: Creates an On/Off menu for use with this setting.
overdrive: Reports the current on/off setting of overdrive mode.
overdrive: Reports the current on/off setting of overdrive mode.
set: Out left outlet: When a bang message is received or when the value of the setting that has a menu-style output is changed,
the word set, followed by a number with a menu item index (starting at 0) is sent out. Here are details of outputs from the left
outlet for specific settings with menu-style outputs:
sigvs: Lists signal vector sizes for the audio driver currently in use.
sigvs: Reports the current signal vector size.
sr: Lists sampling rates available for the audio driver currently in use.
sr: Reports the current sampling rate.
switch: Creates an On/Off menu for turning the DSP on and off.
switch: Reports the current on/off setting of the DSP.
takeover: Creates an On/Off menu for switching scheduler in audio interrupt mode.
takeover: Reports the current on/off setting of takeover mode.
timecode: If supported by the audio driver, reports the current timecode as a list in the following format:

1. time code sample count most significant word

2. time code sample count least significant word

3. time code subframes

4. time code flags

5. time code frame rate


various: Out left outlet: For many settings, a series of messages intended to set up a pop-up menu object are sent out the left
outlet when the reset or loadbang message is received by adstatus. See the reset message in the Input section for more details.

The following settings have a menu-style output: driver, input, iovs, optimize, output, sigvs, sr, switch, and takeover.

Examples

adstatus lets you monitor and change audio parameters from within your patch

See Also
Name Description
dspstate~ Report current DSP settings
adoutput~ Access audio driver output channel
MSP: Audio Input and Output MSP: Audio Input and Output
MSP Tutorial 26: Frequency MSP Tutorial 26: Frequency Domain Signal Processing with pfft~
Domain Signal Processing with
pfft~
allpass~
Apply an allpass filter effect

Description
Use the allpass~ object to filter an input with an allpass filter. The allpass filter has a flat magnitude response but a complex
phase response, typically delaying sharp transients.

Arguments
Name Units Type Opt Description
max-delay ms float opt The maximum delay time. Defaults to 10 ms if not specified.
initial-delay ms float opt Initial delay time
gain float opt Gain coefficient

Messages
float filter-parameter [float] Middle inlet: The delay time in milliseconds
Right inlet: The gain coefficient
clear Reset the filter state
signal Left inlet: The signal to be filtered
Middle inlet: The delay time in milliseconds
Right inlet: The gain coefficient

Information for box attributes common to all objects

Output
signal: The filtered signal.

Examples

Short delay with feedback to blur the input sound, or longer delay for discrete echoes

See Also
Name Description
biquad~ Two-pole, two-zero filter
comb~ Apply a comb filter effect
cross~ Third-order crossover filter
lores~ Resonant lowpass filter
phaseshift~ Distort the phase of a signal
reson~ Resonant bandpass filter
svf~ State-variable filter with simultaneous outputs
teeth~ Comb filter with feedforward and feedback delay control
Audio Filtering Audio Filtering
asin~
Signal arc-sine function

Description
Use the asin~ object to calculate and output a signal that is the arc-sine function of each sample of the input signal.

Arguments
None.

Messages
signal Input to arc-sine function

Information for box attributes common to all objects

Output
signal: The arc-sine of the input in radians.

Examples

asin~ lets you create linear ramps in radians

See Also
Name Description
asinh~ Signal hyperbolic arc-sine function
sinh~ Signal hyperbolic sine function
sinx~ Signal sine function
asinh~
Signal hyperbolic arc-sine function

Description
Use the asinh~ object to calculate and output a signal that is the hyperbolic arc-sine function of each sample of the input signal.

Arguments
None.

Messages
signal Input to hyperbolic arc-sine function

Information for box attributes common to all objects

Output
signal: The hyperbolic arc-sine of the input in radians.

Examples

See Also
Name Description
asin~ Signal arc-sine function
sinh~ Signal hyperbolic sine function
sinx~ Signal sine function
atan~
Signal arc-tangent function

Description
Use the atan~ object to calculate and output a signal that is the arc-tangent function of each sample of the input signal.

Arguments
None.

Messages
signal Input to arc-tangent function

Information for box attributes common to all objects

Output
signal: The arc-tangent of the input.

Examples

atan~ performs the arctangent function on a signal

See Also
Name Description
atanh~ Signal hyperbolic arc-tangent function
atan2~ Signal arc-tangent function (two variables)
tanh~ Signal hyperbolic tangent function
tanx~ Signal tangent function
atan2~
Signal arc-tangent function (two variables)

Description
Use the acosh~ object to take two given x and y values and output a signal which is their arc-tangent function, calculated as
follows:
Arc-tangent (y/x)

Arguments
None.

Messages
int y/x-values [int] Instead of a signal, atan2~ can also take integers in either inlet to specify the x
and y values in the same way a signal would but without sample-accurate timing.
float y/x-values [float] Instead of a signal, atan2~ can also take floats in either inlet to specify the y and x
values in the same way a signal would but without sample-accurate timing.
signal In left input: y value input to an arc-tangent function.

In right input: x value input to an arc-tangent function.

Information for box attributes common to all objects

Output
signal: The arc-tangent input values (i.e. Arc-tangent (y/x)).

Examples

Calculate the angle of two points around an origin (0, 0), in radians

See Also
Name Description
atan~ Signal arc-tangent function
atanh~ Signal hyperbolic arc-tangent function
tanx~ Signal tangent function
atanh~
Signal hyperbolic arc-tangent function

Description
Use the atanh~ object to calculate and output a signal that is the hyperbolic arc-tangent function of each sample of the input
signal.

Arguments
None.

Messages
signal Input to hyperbolic arc-tangent function

Information for box attributes common to all objects

Output
signal: The hyperbolic arc-tangent of the input.

Examples

See Also
Name Description
atan~ Signal arc-tangent function
atan2~ Signal arc-tangent function (two variables)
tanh~ Signal hyperbolic tangent function
tanx~ Signal tangent function
atodb~
Convert linear amplitude to a signal-rate deciBel value

Description
Use the atodb~ to convert a signal representing a linear amplitude value to a deciBel equivalent.

Arguments
None.

Messages
signal A signal representing a linear amplitude value. It is converted to a
gain/attenuation, expressed in deciBels, and output as a signal.

Information for box attributes common to all objects

Output
signal: The gain or attenuation from unity gain, expressed in deciBels, is output as a signal.

Examples

Old-fashioned, no-nonsense numerical conversion

See Also
Name Description
expr Evaluate a mathematical expression
atodb Convert linear amplitude to decibels
dbtoa Convert decibels to a linear amplitude
dbtoa~ Convert a deciBel value to linear amplitude at signal rate
average~
Multi-mode signal average

Description
Use the average~ to perform bipolar, absolute, or rms averaging on any input signal.

Arguments
Name Units Type Opt Description
max- samples int opt Sets the maximum averaging interval in samples. The default value is 100.
averaging-
interval
averaging- symbol opt Sets the averaging mode, as defined in the "Messages" section. The default is
mode bipolar.

Messages
int averaging-sample-interval Sets the interval in samples used for each of the three modes of signal averaging.
[int] The default value is 100.
bipolar Sets bipolar averaging mode (default). In bipolar mode, the sample values are
averaged.
absolute Sets absolute averaging mode. This mode averages the absolute value of the
incoming samples.
rms Sets root mean square (RMS) averaging mode. This mode computes the square
root of the average of the sample values squared.

The RMS mode of the average~ object is more CPU-intensive than the bipolar
and absolute modes.While RMS values are often used to measure signal levels, the
absolute mode often works as well as the RMS mode in many level-detection
tasks.
signal The signal to be averaged.

Information for box attributes common to all objects

Output
signal: The running average value of the input signal averaged over the specified number of samples.

Examples

Running average of a signal across n samples

See Also
Name Description
avg~ Signal average
meter~ Visual peak level indicator
MSP Compression Introduction: MSP Compression Introduction: What is Compression?
What is Compression?
avg~
Signal average

Description
Use the avg~ object to keep track of the average (absolute) amplitude of the input signal received over a specified time interval.

Arguments
None.

Messages
bang Triggers a report of the average (absolute) amplitude of the signal received since
the previous bang, and clears the avg~ object's memory in preparation for the
next report.
signal The signal to be averaged.

Information for box attributes common to all objects

Output
float: When bang is received in the inlet, avg~ reports the average amplitude of the signal received since the previous bang.

Examples

Report the average (absolute) amplitude of a signal

See Also
Name Description
average~ Multi-mode signal average
meter~ Visual peak level indicator
begin~
Define a switchable part of a signal network

Description
Use the begin~ to designate the beginning portion of a signal network that you wish to be turned off when it's not needed. You
connect the outlet of begin~ to the signal inlet of another object to define the beginning of a signal network that will eventually
pass through a gate~ or selector~.

Arguments
None.

Information for box attributes common to all objects

Output
signal: A constant signal of 0 used to designate the beginning portion of a signal network that will be turned off whenever used in
tandem with gate~ and selector~ objects.

Examples

See Also
Name Description
selector~ Assign one of several inputs to an outlet
gate~ Route a signal to one of several outlets
MSP Tutorial 5: Turning Signals MSP Tutorial 5: Turning Signals On and Off
On and Off
biquad~
Two-pole, two-zero filter

Description
biquad~ implements a two-pole, two-zero filter using the following equation:

y[n] = a0 * x[n] + a1 * x[n-1] + a2 * x[n-2] - b1 * y[n-1] - b2 * y[n-2]

You can specify the coefficients a0, a1, a2, b1, and b2 as signals or floats (if you make the filter explode by making the b
coefficients too high, you can recover (after lowering them) with the clear message, or by turning the audio on and off).

Arguments
Name Units Type Opt Description
a0 float Set the initial value for the a0 filter coefficient. If a signal is connected to the
second inlet, the coefficient supplied as an argument is ignored.
a1 float Set the initial value for the a1 filter coefficient. If a signal is connected to the third
inlet, the coefficient supplied as an argument is ignored.
a2 float Set the initial value for the a2 filter coefficient. If a signal is connected to the
fourth inlet, the coefficient supplied as an argument is ignored.
b1 float Set the initial value for the b1 filter coefficient. If a signal is connected to the fifth
inlet, the coefficient supplied as an argument is ignored.
b2 float Set the initial value for the b2 filter coefficient. If a signal is connected to the sixth
inlet, the coefficient supplied as an argument is ignored.

Messages
int filter-coefficient [int] Converted to float.

The coefficients in inlets 2 to 6 may be specified by a number instead of a signal. If


a signal is also connected to the inlet, the number value is ignored.
float filter-coefficient [float] The coefficients in inlets 2 to 6 may be specified by a float instead of a signal. If a
signal is also connected to the inlet, the float is ignored.
list a0 [float] The five filter coefficients can be provided as a list in the left inlet. The first
a1 [float] number in the list is coefficient a0, the next is a1, and so on. If a signal is
a2 [float] connected to a given inlet, the coefficient supplied in the list for that inlet is
b1 [float] ignored.
b2 [float]
dictionary dictionary-name [symbol] The word dictionary, followed by a symbol that references a named filterdesign
object dictionary (set via the name attribute), will cause the biquad~ object to use
the dictionary values for filter coefficients.
clear Clears the biquad~ object's memory of previous inputs and outputs, resetting xn-
1, xn-2, yn-1, and yn-2 to 0.
signal In left inlet: Signal to be filtered. The filter mixes the current input sample with
the two previous input samples and the two previous output samples according to
the formula:

yn = a0xn + a1xn-1 + a2xn-2 - b1yn-1 - b2yn-2.

In 2nd inlet: Amplitude coefficient a0, for scaling the amount of the current input
to be passed directly to the output.

In 3rd inlet: Amplitude coefficient a1, for scaling the amount of the previous input
sample to be added to the output.
In 4th inlet: Amplitude coefficient a2, for scaling the amount of input sample n-2
to be added to the output.

In 5th inlet: Amplitude coefficient b1, for scaling the amount of the previous
output sample to be added to the current output.

In right inlet: Amplitude coefficient b2, for scaling the amount of output sample n-
2 to be added to the current output. .
stoke a0 [float] The word stoke, followed by a list that specifies a set of filter coefficient values,
a1 [float] will preload the filter so that it starts in a given initial state, allowing the filter to be
a2 [float] used for purposes such as a ringing oscillator.
b1 [float]
b2 [float]

Attributes
Name Type g/s Description
smooth int Toggles the smoothing of filter coeffient changes.
def.:1

Information for box attributes common to all objects

Output
signal: The filtered signal.

Examples

Filter coefficients may be supplied as numerical values or as varying signals

See Also
Name Description
buffir~ buffer-based FIR filter
cascade~ Cascaded series of biquad filters
comb~ Apply a comb filter effect
cross~ Third-order crossover filter
filtergraph~ Edit a filter interactively
lores~ Resonant lowpass filter
onepole~ Single-pole lowpass filter
reson~ Resonant bandpass filter
svf~ State-variable filter with simultaneous outputs
teeth~ Comb filter with feedforward and feedback delay control
Audio Filtering Audio Filtering
bitand~
Bitwise and-operation of floating point signals

Description
Use the bitand~ object to perform a bitwise intersection (a bitwise "and") on two incoming floating-point signals as either raw
32-bit data or as integer values. The output is a floating-point signal composed of those bits which are 1 in both numbers.

Arguments
Name Units Type Opt Description
bitmask int opt Sets the bitmask to be used by the bitand~ object. The default is 0. An integer
value can be used as a bitmask regardless of the mode; the binary representation
of this integer is the bitmask.
operational-mode int opt Specifies whether the floating-point signal or floating-point values will be
processed as raw 32-bit floating-point values or converted to integer values for the
bitwise operation. The modes of operation are listed below:

0: Treat both floating-point signal inputs as raw 32-bit values (default).


1: Convert both floating-point signal inputs to integer values.
2: Treat the floating-point signal in the left inlet as a raw 32-bit value
3: Convert the floating-point signal in the left inlet to an integer and treat the right
input as a raw 32-bit value.

Messages
int bitmask [int] In right inlet: An integer value can be used as a bitmask when supplied to the right
inlet of the bitand~ object, provided that the proper mode is set.
float bitmask [float] In right inlet: A floating-point value can be used as a bitmask when supplied to
the right inlet of the bitand~ object, provided that the proper mode is set.
bits bitmask [list] In left inlet: The word bits, followed by a list containing 32 ones or zeros, specifies
a bitmask to be used by bitand~. Alternately, a bitmask value can be set by using
an int value in the right inlet.
mode behavioral-flag [int] In left inlet: The word mode, followed by a zero or one, specifies whether the
floating signal or floating-point values will be processed as a raw 32-bit floating-
point value or converted to an integer value for the bitwise operation. The modes
of operation are:

0: Treat both floating-point signal inputs as raw 32-bit values (default).


1: Convert both floating-point signal inputs to integer values.
2: Treat the floating-point signal in the left inlet as a raw 32-bit value and treat the
value in the right inlet as an integer.
3 - Convert the floating-point signal in the left inlet to an integer and treat the
right input as a raw 32-bit value.

Note: If you convert the floating-point signal input to an integer and then convert
it back, the resulting floating-point value will retain only 24 bits of integer
resolution.
signal In left inlet: The floating-point signal is compared, in binary form, with the
floating-point signal in the right inlet. The signal can be treated as either a
floating-point signal or as an integer.
In right inlet: The floating-point signal to be compared with the signal in the left
inlet. The signal can be treated as either a floating-point signal or as an integer.
The raw floating-point signal bit values are expressed in the following form:
<1 sign bit> <8 exponent bits> <23 mantissa bits>

Information for box attributes common to all objects


Output
signal: The two floating-point signals or ints received in the inlets are compared, one bit at a time. If a bit is 1 in both numbers,
it will be 1 in the output number, otherwise it will be 0 in the output floating-point signal.

Examples

See Also
Name Description
bitshift~ Bit shifting for floating point signals
bitor~ Bitwise or-operation of floating point signals
bitxor~ Bitwise exclusive-or-operation of floating point signals
bitnot~ Bitwise inversion of a floating point signal
bitnot~
Bitwise inversion of a floating point signal

Description
Use the bitnot~ object to perform a bitwise inversion on an incoming floating-point signal as either raw 32-bit data or as an
integer value. All bit values of 1 are set to 0, and vice versa.

Arguments
Name Units Type Opt Description
operational-mode int opt Specifies whether the floating-point signal or floating-point value will be
processed as a raw 32-bit floating-point value or converted to an integer value for
bit inversion. The modes of operation are listed below.

0: Treat floating-point signal input as a raw 32-bit value (default).


1: Convert the floating-point signal input to an integer value.

Messages
int operational-mode [int] Sets the operational mode of the bitnot~ object as described by the mode
message.
float operational-mode (0 or 1) Sets the operational mode of the bitnot~ object as described by the mode
[float] message.
mode operational-mode [int] In left inlet: The word mode, followed by a zero or one, specifies whether the
floating signal or floating-point value will be processed as a raw 32-bit floating-
point value or converted to an integer value for bit inversion. The modes of
operation are:

0: Treat floating-point signal input as a raw 32-bit value (default).


1: Convert the floating-point signal input to an integer value.

Note: If you convert the floating-point signal input to an int and then convert it
back, the resulting floating-point value will retain only 24 bits of integer
resolution.
signal The bitnot~ object can perform bit inversion on either a floating-point signal as
bits, or as an integer.
Floating-point signal bit values are expressed in the following form:
<1 sign bit> <8 exponent bits> <23 mantissa bits>

Information for box attributes common to all objects

Output
signal: The resulting bit inverted floating-point signal.

Examples
See Also
Name Description
bitshift~ Bit shifting for floating point signals
bitor~ Bitwise or-operation of floating point signals
bitxor~ Bitwise exclusive-or-operation of floating point signals
bitand~ Bitwise and-operation of floating point signals
bitor~
Bitwise or-operation of floating point signals

Description
Use the bitor~ object to perform a bitwise "or" on two incoming floating-point signals as either raw 32-bit data or as integer
values. The bits of both incoming signals are compared, and a 1 is output if either of the two bit values is 1. The output is a
floating-point signal composed of the resulting bit pattern.

Arguments
Name Units Type Opt Description
bitmask int opt Sets the bitmask to be used by the bitor~ object. The default is 0. An integer value
can be used as a bitmask regardless of the mode; the binary representation of this
integer is the bitmask.
operational-mode int opt Specifies whether the floating-point signal or floating-point values will be
processed as raw 32-bit floating-point values or converted to integer values for the
bitwise operation. The modes of operation are:

0: Treat both floating-point signal inputs as raw 32-bit values (default).


1: Convert both floating-point signal inputs to integer values.
2: Treat the floating-point signal in the left inlet as a raw 32-bit value and treat the
value in the right inlet as an integer.
3: Convert the floating-point signal in the left inlet to an integer and treat the right
input as a raw 32-bit value.

Note: If you convert the floating-point signal input to an integer and then convert
it back, the resulting floating-point value will retain only 24 bits of integer
resolution.

Messages
int bitmask [int] In right inlet: An integer value can be used as a bitmask when supplied to the right
inlet of the bitor~ object, provided that the proper mode is set.
float bitmask [float] In right inlet: A floating-point value can be used as a bitmask when supplied to
the right inlet of the bitor~ object, provided that the proper mode is set.
bits bitmask (32 ones or zeros) [list] In left inlet: The word bits, followed by a list containing 32 ones or zeros, specifies
a bitmask to be used by bitor~. Alternately, a bitmask value can be set by using an
int value in the right inlet.
mode operational-mode (0 through 3) In left inlet: The word mode, followed by a zero or one, specifies whether the
[int] floating signal or floating-point values will be processed as a raw 32-bit floating-
point value or converted to an integer value for the bitwise operation. The modes
of operation are:

Mode Descriptions:
0 - Treat both floating-point signal inputs as raw 32-bit values (default).
1 - Convert both floating-point signal inputs to integer values.
2 - Treat the floating-point signal in the left inlet as a raw 32-bit value and treat
the value in the right inlet as an integer.
3 - Convert the floating-point signal in the left inlet to an integer and treat the
right input as a raw 32-bit value.

Note: If you convert the floating-point signal input to an integer and then convert
it back, the resulting floating-point value will retain only 24 bits of integer
resolution.
signal In left inlet: The floating-point signal is compared, in binary form, with the
floating-point signal in the right inlet. The signal can be treated as either a
floating-point signal or as an integer.
In right inlet: The floating-point signal to be compared with the signal in the left
inlet. The signal can be treated as either a floating-point signal or as an integer.
The raw floating-point signal bit values are expressed in the following form:
<1 sign bit> <8 exponent bits> <23 mantissa bits>

Information for box attributes common to all objects

Output
signal: The two floating-point signals or ints received in the inlets are compared, one bit at a time. If a bit is 1 in either one of the
numbers, it will be 1 in the output number, otherwise it will be 0 in the output number. The output is a floating-point signal
composed of the resulting bit pattern.

Examples

See Also
Name Description
bitshift~ Bit shifting for floating point signals
bitand~ Bitwise and-operation of floating point signals
bitxor~ Bitwise exclusive-or-operation of floating point signals
bitnot~ Bitwise inversion of a floating point signal
bitsafe~
Replace NaN and infinite signal values with 0

Description
Use the bitsafe~ object to detect NaN (not a number) and +/- infinity values in an incoming signal and replace those occurences
with zero. This is useful in conjunction with the bitwise operators, or any other situation where these values are possible.

Arguments
None.

Messages
signal Input signals to bitsafe~ will have infinite and NaN values replaced with 0 in the
output signal.

Information for box attributes common to all objects

Output
signal: The resulting floating-point signal which has 0 values where infinite or NaN values existed in the input.

Examples

See Also
Name Description
bitshift~ Bit shifting for floating point signals
bitor~ Bitwise or-operation of floating point signals
bitxor~ Bitwise exclusive-or-operation of floating point signals
bitnot~ Bitwise inversion of a floating point signal
bitand~ Bitwise and-operation of floating point signals
bitshift~
Bit shifting for floating point signals

Description
Use the bitshift~ object to perform bitwise operations on a floating point signal as bits or as an integer.

Arguments
Name Units Type Opt Description
number-of- int opt Sets the number of bits to be shifted on the incoming floating-point signal.
bits/direction-of-shift Positive shift values correspond to left shifting that number of bits, negative shift
values correspond to right shifting that number of bits.
operational-mode int opt Specifies whether the floating-point signal or floating-point value will be
processed as a raw 32-bit floating-point value or converted to an integer value for
bit shifting. The modes of operation are listed below.

0: Treat floating-point signal input as a raw 32-bit value (default).


1: Convert the floating-point signal input to an integer value.

Messages
int operational-mode [int] Sets the operational mode of the bitshift~ object as described by the mode
message.
floatoperational-mode (0 or 1) Performs the same function as int.
[float]
mode operational-mode [int] In left inlet: The word mode, followed by a zero or one, specifies whether the
floating signal or floating-point value will be processed as a raw 32-bit floating-
point value or converted to an integer value for bit shifting. The modes of
operation are:

Mode Descriptions:
0 - Treat floating-point signal input as a raw 32-bit value (default).
1 - Convert the floating-point signal input to an integer value.
Note: If you convert the floating-point signal input to an int and then convert it
back, the resulting floating-point value will retain only 24 bits of integer
resolution.
shift number-of-bits/direction-of- In left inlet: The word shift, followed by a positive or negative number, specifies
shift [int] the number of bits to be shifted on the incoming floating-point signal. Positive
number values correspond to left shifting that number of bits (i.e., Left shifting a
number n places is the same as dividing it by 2n). Negative numbers correspond
to right shifting that number of bits (i.e., Right shifting a number n places is the
same as dividing it by 2n).
signal The bitshift~ object performs bit shifting on a floating-point signal as either raw
32-bit data or as an integer value.
Floating-point signal bit values are expressed in the following form: <1 sign bit>
<8 exponent bits> <23 mantissa bits>

Information for box attributes common to all objects

Output
signal: The resulting bit shifted floating-point signal.

Examples
See Also
Name Description
bitand~ Bitwise and-operation of floating point signals
bitor~ Bitwise or-operation of floating point signals
bitxor~ Bitwise exclusive-or-operation of floating point signals
bitnot~ Bitwise inversion of a floating point signal
bitxor~
Bitwise exclusive-or-operation of floating point signals

Description
Use the bitxor~ object to perform a bitwise "exclusive or" operation on two incoming floating-point signals as either raw 32-bit
data or as integer values. The bits of both incoming signals are compared, and the corresponding output bit will be set to 1 if the
two bit values are different, and 0 if the two values are the same. The output is a floating-point signal composed of the resulting
bit pattern.

Arguments
Name Units Type Opt Description
bitmask int opt Sets the bitmask to be used by the bitxor~ object. The default is 0. An integer
value can be used as a bitmask regardless of the mode; the binary representation
of this integer is the bitmask.
operational-mode int opt Specifies whether the floating-point signal or floating-point value will be
processed as a raw 32-bit floating-point value or converted to an integer value for
bit inversion. The modes of operation are listed below.

0: Treat floating-point signal input as a raw 32-bit value (default).


1: Convert the floating-point signal input to an integer value.

Messages
int bitmask [int] In right inlet: An integer value can be used as a bitmask when supplied to the right
inlet of the bitxor~ object, provided that the proper mode is set.
float bitmask [float] In right inlet: A floating-point value can be used as a bitmask when supplied to
the right inlet of the bitxor~ object, provided that the proper mode is set.
bits bitmask (32 ones or zeros) [list] In left inlet: The word bits, followed by a list containing 32 ones or zeros, specifies
a bitmask to be used by bitxor~. Alternately, a bitmask value can be set by using
an int value in the right inlet.
mode operational-mode (0 through 3) In left inlet: The word mode, followed by a zero or one, specifies whether the
[int] floating signal or floating-point values will be processed as a raw 32-bit floating-
point value or converted to an integer value for the bitwise operation. The modes
of operation are:

0: Treat both floating-point signal inputs as raw 32-bit values (default).


1: Convert both floating-point signal inputs to integer values.
2: Treat the floating-point signal in the left inlet as a raw 32-bit value and treat the
value in the right inlet as an integer.
3: Convert the floating-point signal in the left inlet to an integer and treat the right
input as a raw 32-bit value.

Note: If you convert the floating-point signal input to an integer and then convert
it back, the resulting floating-point value will retain only 24 bits of integer
resolution.
signal In left inlet: The floating-point signal is compared, in binary form, with the
floating-point signal in the right inlet. The signal can be treated as either a
floating-point signal or as an integer.
In right inlet: The floating-point signal to be compared with the signal in the left
inlet. The signal can be treated as either a floating-point signal or as an integer.
The raw floating-point signal bit values are expressed in the following form:
<1 sign bit> <8 exponent bits> <23 mantissa bits>

Information for box attributes common to all objects


Output
signal: The two floating-point signals or ints received in the inlets are compared, one bit at a time. A 1 is output if the two bit
values are different, 0 if they are the same. The output is a floating-point signal composed of the resulting bit pattern.

Examples

See Also
Name Description
bitshift~ Bit shifting for floating point signals
bitand~ Bitwise and-operation of floating point signals
bitor~ Bitwise or-operation of floating point signals
bitnot~ Bitwise inversion of a floating point signal
buffer~
Store audio samples

Description
Use the buffer~ object as a buffer of memory in which samples are stored to be saved, edited, or referenced.

Arguments
Name Units Type Opt Description
name symbol The first argument is a name used by other objects to refer to the buffer~ to access
its contents.

For information about using named objects in Max for Live, click here.
filename symbol opt After the buffer~ object's name, you may type the name of an audio file to load
when the buffer~ is created.
duration ms number opt After the optional filename argument, a duration may be provided, in
milliseconds, to set the size of the buffer~, which limits the amount of sound that
will be stored in it. (A new duration can be specified as part of a read message,
however.) If no duration is typed in, the buffer~ has no sample memory. It does
not, however, limit the size of an audio file that can be read in.
channels int opt After the duration, an additional argument may be typed in to specify the number
of audio channels to be stored in the buffer~. (This is to tell buffer~ how much
memory to allocate initially; however, if an audio file with more channels is read
in, buffer~ will allocate more memory for the additional channels.) The maximum
number of channels buffer~ can hold is four. By default, buffer~ has one channel.

Messages
bang Redraws the contents of the buffer~ object's waveform display window. You can
open the display window by double-clicking on the buffer~ object.
(remote) The contents of buffer~ can be altered by the peek~ and record~ objects or
referenced/played-back by the 2d.wave~, play~, wave~, groove~, buffir~,
cycle~, and lookup~ objects.
(drag) When an audio file is dragged from the Max 5 File Browser to a buffer~ object,
the file will be loaded.
apply function-and- The word apply, followed by list consisting of one to three symbols or numbers,
parameters [list] will apply a windowing function to the current contents of a buffer~.

The word apply, followed by a single symbol that designates a windowing


function, will apply that function to the current contents of the buffer~.
Supported functions include triangle, hamming, hanning, blackman, welch, and
kaiser. An additional second symbol argument of half (e.g. apply blackman half)
will calculate the function and apply only the second half to the whole buffer~.

Note: The kaiser function requires a second floating point argument that specifies
the beta parameter and precedes an optional half argument (e.g. apply kaiser 4.5
half).

The word apply, followed by the word gain and a floating-point number that
specifies a gain value, will scale every sample by the gain coefficient.

The word apply, followed by the word getdeltas, will replace every sample value
with the a new value representing the difference from the previous sample.
clear Erases the contents of buffer~.
clearlow Erases the contents of the buffer like the clear message, but performs the clear as
a low-priority task.
crop start and end times [list] The crop message, followed by two numbers that specify start and end time in
milliseconds, will trim the audio data in the buffer. It resizes the buffer~ to the
selection length.
(mouse) Double-clicking on buffer~ opens a display window where you can view the
contents of the buffer~. When the user clicks or drags with the mouse in the
buffer~ object's editing window, the cursor's time location in the buffer~, in
milliseconds, is sent out the outlet.
duplicate buffer-name [symbol] The word duplicate, followed by a symbol that specifies the name of a buffer~,
will import the contents of the named buffer.
filetype file-type-code [symbol] The word filetype, followed by symbol which specifies an audio file format, sets
the file type used by the buffer~ object. The default file type is AIFF.Supported
file types are identified as follows:

aiff- Apple Interchange File Format (default)


wave- WAVE
raw- raw
au- NeXT/Sun
fill constant/function [list] The word fill, followed by list consisting of one to three symbols or numbers,
specifies how the contents of a buffer~ object will be filled.

The word fill, followed by a single floating-point number, will set every sample in
the buffer~ to that value.

The word fill, followed by a symbol that designates a function, will fill the buffer~
with one cycle of that function. Supported functions include sin (sine), cos,
(cosine), and sinc. An optional second argument (e.g. fill sin 2) can be used to
define the number of cycles of the function used to fill the buffer~. An additional
optional third argument defines a rational number of cycles with which to fill the
buffer~ (e.g. fill cos 1 4 will fill a buffer~ with a quarter cycle of the cosine
function).

Note: the sinc function requires two int arguments that specify the number of zero
crossings and an additional flag that toggles starting the function at zero (e.g. fill
sinc 4 1).
format bit-depth/sample-type The word format followed by a number or a symbol will set the bit-depth or
[list] sample-type of the buffer.

Numerical values are:


8 - 8-bit integer
16 - 16-bit integer
24 - 24-bit integer
32 - 32-bit integer

Symbol values used to set bit-depth or sample type are:


int8 - 8-bit integer
int16 - 16-bit integer
int24 - 24-bit integer
int32 - 32-bit integer
float32 - 32-bit floating-point
float64 - 64-bit floating-point
mulaw - 8-bit mu-law encoding
alaw - 8-bit a-law encoding
enumerate Posts information in the Max window identifying all buffer~ objects which
reference the same data stored in the buffer~ object which received the
enumerate message.(The labelling information: "(this one)", will appear next to
the address of the buffer~ object which received the enumerate message).
import filename [list] The word import, followed by a filename, reads that file into buffer~ immediately
if it exists in Max's search path without opening the Open Document dialog box.
Without a filename, import brings up an Open Document dialog box allowing you
to choose a file. The imported file retains the sampling rate and word size of the
original file, but looping points and markers are not imported. The filename may
be followed by a float indicating a starting time in the file, in milliseconds, to begin
reading. (The beginning of the file is 0.)

The buffer~ object uses QuickTime to convert a media file (including MP3 files)
into the sample memory of a buffer~, and requires that QuickTime be installed on
your system. If you are using Max on Windows, we recommend that you install
QuickTime and choose a complete install of all optional components.

Since the import message uses QuickTime, which specifies units of time for all
files as 1/600 of a second rather than milliseconds, importing is not guaranteed to
start at the specified offset with millisecond accuracy.
The starting time may be followed by a second argument - a floating point value
that specifies the duration of sound, in milliseconds, to be read into buffer~. This
duration overrides the current size of the object's sample memory. If the duration
is specified by a negative value, buffer~ reads in the entire file and resizes its
sample memory and adjusts the number of channels in the file accordingly.
The duration may be followed by a third argument that specifies the number of
channels to be read in. If the number of channels is not specified (i.e., if the
message includes only offset and duration information), buffer~ reads in the
number of channels indicated in the header of the audio file.
If only two arguments are specified, buffer~ imports the number of channels
indicated in the header of the audio file. If three arguments are specified, buffer~
imports the number of channels specified by the third argument. If the third
argument is 0, buffer~ imports the number of channels indicated in the header of
the audio file.
name buffer-name [symbol] The word name, followed by a symbol, changes the name by which other objects
such as cycle~, groove~, lookup~, peek~, play~, record~, and wave~ can refer
to the buffer~. Objects that were referring to the buffer~ under its old name lose
their connection to it. Every buffer~ object should be given a unique name; if you
give a buffer~ object a name that already belongs to another buffer~, that name
will no longer be associated with the buffer~ that first had it.
open Opens the buffer~ sample display window or brings it to the front if it is already
open.
normalize normalization_factor The word normalize, followed by a floating point number, will scale the sample
[list] values in the buffer~ object so that the highest peak matches the value given by
the argument. This can cause either amplification or attenuation of the audio, but
in either case, every value is scaled.
printmodtime Posts information in the Max window about when the buffer~ was last modified
(i.e. written into, or modified in attributes).
read filename [list] Reads an AIFF, Next/Sun, or WAV file into the sample memory of the buffer~.
The word read, followed by a filename, reads that file into buffer~ immediately if
it exists in Max's search path without opening the Open Document dialog box.
Without a filename, import brings up an Open Document dialog box allowing you
to choose a file. The imported file retains the sampling rate and word size of the
original file, but looping points and markers are not imported. The filename may
be followed by a float indicating a starting time in the file, in milliseconds, to begin
reading. (The beginning of the file is 0.)
The starting time may be followed by a second argument - a floating point value
that specifies the duration of sound, in milliseconds, to be read into buffer~. This
duration overrides the current size of the object's sample memory. If the duration
is specified by a negative value, buffer~ reads in the entire file and resizes its
sample memory and adjusts the number of channels in the file accordingly.
The duration may be followed by a third integer argument that specifies the
number of channels to be read in.
If only two arguments are specified, buffer~ reads the number of channels
indicated in the header of the audio file. If three arguments are specified, buffer~
reads the number of channels specified by the third argument. If the third
argument is 0, buffer~ reads in the number of channels indicated in the header of
the audio file.
set buffer-name [symbol] The word set, followed by a symbol, changes the name by which other objects
such as cycle~, groove~, lookup~, peek~, play~, record~, and wave~ can refer
to the buffer~. Objects that were referring to the buffer~ under its old name lose
their connection to it. Every buffer~ object should be given a unique name; if you
give a buffer~ object a name that already belongs to another buffer~, that name
will no longer be associated with the buffer~ that first had it.
sizeinsamps buffer-duration [int] The word sizeinsamps, followed by a duration in samples, sets the size of the
number-of-channels buffer~ object's sample memory. This limits the amount of data that can be
[int] stored, unless this size limitation is overridden by a replace message or a duration
argument in a read message.
sr sampling-rate The word sr, followed by a sampling rate, sets the buffer~ object's sampling rate.
(samples-per-second) By default, the sampling rate is the current output sampling rate, or the sampling
[float] rate of the most recently loaded audio file.
readagain filename [list] Reads sound data from the most recently loaded file (specified in a previous read
or replace message).
replace filename [list] The replace message is equivalent to the read message with a negative duration
argument.
samptype sample-type [symbol] In left inlet: The word samptype, followed by a symbol, specifies the sample type
to use when interpreting an audio file's sample data (thus overriding the audio
file's actual sample type). This is sometimes called "header munging."

The following types of sample data are supported:

int8- 8-bit integer


int16- 16-bit integer
int24- 24-bit integer
int32- 32-bit integer
float32- 32-bit floating-point
float64- 64-bit floating-point
mulaw- 8-bit "mu"-law encoding
alaw- 8-bit a-law encoding
wclose Closes the buffer~ sample display window if it is open.
write filename [symbol] Saves the contents of buffer~ into an audio file. A standard file dialog is opened
for naming the file unless the word write is followed by a symbol, in which case
the file is saved in the current default folder, using the symbol as the filename.
Unless you change the format with the Format pop-up menu in the standard Save
As dialog box, the file will be saved in the format specified by the most recently
received filetype message, or the file type of the most recently opened audio file.
By default, buffer~ saves in AIFF format.
writeaiff filename [symbol] Saves the contents of the buffer~ as an AIFF file. A standard Save As dialog is
opened for naming the file unless the word writeaiff is followed by a symbol, in
which case the file is saved in the current default folder, using the symbol as the
filename.
writeau filename [symbol] Saves the contents of the buffer~ as a NeXT/Sun file. A standard Save As dialog is
opened for naming the file unless the word writeau is followed by a symbol, in
which case the file is saved in the current default folder, using the symbol as the
filename.
writeflac filename [symbol] Saves the contents of the buffer~ into a FLAC file. A standard Save As dialog is
opened for naming the file unless the word writeflac is followed by a symbol, in
which case the file is saved in the current default folder, using the symbol as the
filename.
writeraw filename [symbol] Saves the contents of the buffer~ as a raw file with no header. The default sample
format is 16-bit, but the output sample format can be set with the samptype
message. A standard Save As dialog is opened for naming the file unless the word
writeraw is followed by a symbol, in which case the file is saved in the current
default folder, using the symbol as the filename.
writewave filename [symbol] Saves the contents of the buffer~ into a WAV file. A standard Save As dialog is
opened for naming the file unless the word writewave is followed by a symbol, in
which case the file is saved in the current default folder, using the symbol as the
filename.

Attributes
Name Type g/s Description
size float The length of the buffer~ expressed in milliseconds.

Information for box attributes common to all objects

Output
float: When the user clicks or drags with the mouse in the buffer~ object's editing window, the cursor's time location in the
buffer~, in milliseconds, is sent out the outlet.

Examples

buffer~ can be used as a waveform table for an oscillator, or as a sample buffer

See Also
Name Description
2d.wave~ Two-dimensional wavetable
buffir~ buffer-based FIR filter
cycle~ Sinusoidal oscillator
groove~ Variable-rate looping sample playback
info~ Report information about a sample
lookup~ Transfer function lookup table
peek~ Read and write sample values
play~ Position-based sample playback
poke~ Write sample values to a buffer by index
record~ Record sound into a buffer
sfplay~ Play audio file from disk
sfrecord~ Record to audio file on disk
wave~ Variable size wavetable
MSP Tutorial 3: Wavetable MSP Tutorial 3: Wavetable Oscillator
Oscillator
MSP Tutorial 12: Waveshaping MSP Tutorial 12: Waveshaping
MSP Tutorial 13: Recording and MSP Tutorial 13: Recording and Playback
Playback
MSP Tutorial 14: Playback with MSP Tutorial 14: Playback with Loops
Loops
MSP Tutorial 15: Variable-length MSP Tutorial 15: Variable-length Wavetable
Wavetable
MSP Tutorial 20: MIDI Sampler MSP Tutorial 20: MIDI Sampler Control
Control
MSP Tutorial 25: Using the FFT MSP Tutorial 25: Using the FFT
buffir~
buffer-based FIR filter

Description
Use buffir~ object when you need a finite impulse response (FIR) filter that convolves an input signal with samples from an input
buffer.

Arguments
Name Units Type Opt Description
buffer-name symbol The name of a buffer~ object which buffir~ uses to filter the input signal.
read-offset samples int or opt The offset, in samples, into the buffer~ object before buffir~ begins reading
float samples to construct the filter. The default is 0.
read- samples int or opt The size, in samples, of the slice in the buffer~ which buffir~ will use for the
duration float filter. The default is 0.

Messages
int read-offset [int] In middle inlet: The offset into the filter buffer~ from which buffir~ begins to
read, in samples.

In right inlet: The size (in samples) of the slice from the buffer~ which is used to
filter the input signal (the maximum is 4096).
float read-offset [float] In middle inlet: The offset into the filter buffer~ from which buffir~ begins to
read, in samples.

In right inlet: The size (in samples) of the slice from the buffer~ which is used to
filter the input signal (the maximum is 4096).
clear The word clear erases (zeroes) the current input history for the filter.
set buffer-name [symbol] The word set, followed by the name of a buffer~ object, an int which specifies
read-offset [int] sample offset, and an optional int which specifies a number of samples, specifies
read-duration [int] the name of a buffer~ object which buffir~ uses to filter its input signal.
signal In left inlet: The signal to be convolved with samples from the buffer~.

In middle inlet: The offset (in samples) into the filter buffer~ from which the
buffir~ object begins to read.

In right inlet: The size of the slice from the filter buffer~ which is used to filter the
input signal, in samples. The maximum is 4096.

Information for box attributes common to all objects

Output
signal: The filtered signal, based on a convolution of the input signal with samples in the buffer~.

Examples
buffir~ lets you use slices of a buffer~ as an impulse response for an FIR filter

See Also
Name Description
biquad~ Two-pole, two-zero filter
buffer~ Store audio samples
cascade~ Cascaded series of biquad filters
Audio Filtering Audio Filtering
capture~
Store a signal to view as text

Description
Use the capture object to collect signal values for signal debugging or investigation. To record signal values, use the record~ or
sfrecord~ object.

Arguments
Name Units Type Opt Description
behavioral-flag (f) symbol opt If the first argument is the letter f, capture~ stores the first signal samples it
receives, and then ignores subsequent samples once its storage buffer is full. If the
letter f is not present, capture~ stores the most recent signal samples it has
received, discarding earlier samples if necessary.
maximum-samples int opt Limits the number of samples (and thus the length of the excerpt) that can be
held by capture~. If no number is typed in, capture~ stores 4096 samples. The
maximum possible number of samples is limited only by the amount of memory
available to the Max application. A second number argument may be typed in to
set the precision (the number of digits to the right of the decimal point) with
which samples will be shown in the editing window.
signal-vector- list opt A list of up to 10 indices within a signal vector. If no indices present, capture~
indices (up to 10 records the entire vector.
ints)

Messages
(mouse) Double-clicking on capture~ opens a window for viewing and editing its contents.
The numbers in the editing window can be copied and pasted into a graphic
buffer~ editing window.
clear Erases the contents of capture~.
open Causes an editing and viewing window for the capture~ object to become visible.
The window is also brought to the front.
signal An excerpt of the signal is stored as text for viewing, editing, or saving to a file.
(The length of the excerpt can be specified as a typed-in argument to the object.)
wclose Closes the window associated with the capture~ object.
write filename [symbol] Saves the contents of capture~ into a text file. A standard file dialog is opened for
naming the file. The word write, followed by a symbol, saves the file, using the
symbol as the filename, in the same folder as the patch containing the capture~.
If the patch has not yet been saved, the capture~ file is saved in the same folder
as the Max application.

Information for box attributes common to all objects

Output
(text): capture~ outputs nothing and has no outlet but the signal which it captures into text can be saved to a file or copied and
pasted elsewhere for editing.

Examples

Capture a portion of a signal as text, to view, save, copy and paste, etc.
See Also
Name Description
scope~ Visualize an audio signal
MSP Tutorial 23: Viewing Signal MSP Tutorial 23: Viewing Signal Data
Data
MSP Tutorial 25: Using the FFT MSP Tutorial 25: Using the FFT
cartopol~
Signal Cartesian to Polar coordinate conversion

Description
Use the cartopol~ object to convert signal values representing cartesian coordinates to a signal composed of polar coordinates.

Arguments
None.

Messages
signal In left inlet: The real part of a frequency domain signal (such as that created by the
fft~ or fftin~ objects) to be converted to a polar-coordinate signal pair consisting
of amplitude and phase values.

In right inlet: The imaginary part of a frequency domain signal (such as that
created by the fft~ or fftin~ objects) to be converted to a polar-coordinate signal
pair consisting of amplitude and phase values.

Information for box attributes common to all objects

Output
signal: Out left outlet: The magnitude (amplitude) of the frequency bin represented by the current input signals.

Out right outlet: The phase, expressed in radians, of the frequency bin represented by the current input signals. If only the left
outlet is connected the phase computation will be bypassed, reducing the intensity of the computation.

Examples

Use cartopol~ to get amplitude/phase data from the real/imaginary data pair that fftin~ outputs

See Also
Name Description
cartopol Convert cartesian to polar coordinates
fft~ Fast Fourier transform
fftin~ Input for a patcher loaded by pfft~
fftinfo~ Report information about a patcher loaded by pfft~
fftout~ Output for a patcher loaded by pfft~
frameaccum~ Compute "running phase" of successive phase deviation frames
framedelta~ Compute phase deviation between successive FFT frames
ifft~ Inverse fast Fourier transform
pfft~ Spectral processing manager for patchers
poltocar Convert polar to cartesian coordinates
poltocar~ Signal Polar to Cartesian coordinate conversion
vectral~ Vector-based envelope follower
MSP Tutorial 26: Frequency MSP Tutorial 26: Frequency Domain Signal Processing with pfft~
Domain Signal Processing with
pfft~
cascade~
Cascaded series of biquad filters

Description
Use the cascade~ to filter an input signal using a series of biquad filters.

Arguments
None.

Messages
list filter-coefficients [list] In right inlet: The filter coefficients can be provided as a list in the left inlet. The
coefficients should be in sets of five, each set corresponding to a second-order
section or biquad. The first five coefficients in the list are used for the first second-
order section in the series, the next five for the second, and so on.
dictionary dictionary-name [symbol] The word dictionary, followed by a symbol that references a named filterdesign
object dictionary (set via the name attribute), will cause the cascade~ object to
use the dictionary values for filter coefficients.
clear Resets all coefficients and sample-memory to 0.
bypass operational-flag [int] The word bypass followed by a nonzero number will turn bypass mode on and
cause the dry unfiltered signal to pass through to the object's outlet; followed by a
0 will output the filtered signal.
signal In left inlet: Signal to be filtered. The signal is filtered by a series of two-pole two-
zero (i.e. biquad) filters, often referred to as "second order sections".
zero operational-flag [int] The word zero followed by a nonzero number will cause the filtered signal to be
muted; followed by a 0 will output the filtered signal (this will not prevent the
unfiltered signal from appearing at the outlet when bypass mode is turned on).

Information for box attributes common to all objects

Output
signal: The filtered signal.

Examples

Use cascade~ with filtergraph~ in multi-filter mode to efficiently process a complex parametric filter

See Also
Name Description
biquad~ Two-pole, two-zero filter
buffir~ buffer-based FIR filter
comb~ Apply a comb filter effect
filtergraph~ Edit a filter interactively
lores~ Resonant lowpass filter
onepole~ Single-pole lowpass filter
reson~ Resonant bandpass filter
teeth~ Comb filter with feedforward and feedback delay control
Audio Filtering Audio Filtering
change~
Report signal direction

Description
Use the change object to monitor increase, decrease, or no change in a signal value.

Arguments
None.

Messages
float input [float] You can set the value stored with a float.
signal Any signal to be watched for changed and unchanged values.

Information for box attributes common to all objects

Output
signal: When the current sample is greater in value than the previous sample, change~ outputs a sample of 1. When the current
sample is the same as the previous sample, change~ outputs a sample of 0. When the current sample is less than the previous
sample, change~ outputs a sample of -1.

Examples

Detect whether a signal is increasing, decreasing, or remaining constant

See Also
Name Description
edge~ Detect logical signal transitions
thresh~ Detect signal above a set level
zerox~ Detect zero crossings
click~
Create an impulse

Description
Use the click~ to create and output an impulse which can be used as an impulse-trigger.

Arguments
Name Units Type Opt Description
wavetable-values list opt A list of floating-point values in the range 0.0-1.0, can be used to specify an
impulse (i.e., a small wavetable) whose length is determined by the number of list
elements. The maximum size for the list is 256 items.

Messages
bang Sends an impulse out the click~ object's outlet. The default impulse consists of a
single value (1.0), followed by a zero value.
set wavetable-values [list] The word set, followed by a list of floating-point values in the range 0.0-1.0,
specifies a impulse (i.e., a small wavetable) whose length is determined by the
number of list elements. The maximum size for the list is 256 items.

Information for box attributes common to all objects

Output
signal: An impulse.

Examples

Trigger an impulse signal

See Also
Name Description
buffer~ Store audio samples
buffir~ buffer-based FIR filter
line~ Linear ramp generator
clip~
Limit signal amplitude

Description
Use the clip~ to constrains input signals between two specified values.

Arguments
Name Units Type Opt Description
minimum float opt Initial minimum limit for the range of the output signal. If no argument is
supplied, the minimum limit is initially set to 0. If a signal is connected to the
middle inlet, the corresponding argument is ignored.
maximum float opt Initial maximum limit for the range of the output signal. If no argument is
supplied, the maximum limit is initially set to 0. If a signal is connected to the
middle inlet, the corresponding argument is ignored.

Messages
int minimum/maximum [int] The middle and right inlets can receive a float or int instead of a signal to set the
minimum and/or maximum.
float minimum/maximum [float] The middle and right inlets can receive a float or int instead of a signal to set the
minimum and/or maximum.
signal In left inlet: Any signal, which will be restricted within the minimum and
maximum limits received in the middle and right inlets.

In middle inlet: Minimum limit for the range of the output signal.

In right inlet: Maximum limit for the range of the output signal.

Information for box attributes common to all objects

Output
signal: The input signal is sent out, limited within the specified range. Any value in the input signal that exceeds the minimum or
maximum limit is set equal to that limit.

Examples

Output is a clipped version of the input

See Also
Name Description
<~ Is less than, comparison of two signals
>~ Is greater than, comparison of two signals
trunc~ Truncate fractional signal values
comb~
Apply a comb filter effect

Description
Use the comb~ object to apply the classic comb filtering effect to an audio input. The comb~ object mixes the current input
sample with earlier input and/or output samples, according to the formula:

yn = axn + bxn-(DR/1000) + cyn-(DR/1000)

where R is the sampling rate and D is a delay time in milliseconds.

Arguments
Name Units Type Opt Description
max-delay ms float opt The maximum delay time. Defaults to 10 ms if not specified.
initial-delay ms float opt Initial delay time
gain-coefficient float opt Gain coefficient
feedforward- float opt The feedforward coefficient
coefficient
feedback-coefficient float opt The feedback coefficient

Messages
float filter-parameters [float] 2nd inlet: delay time in milliseconds
3rd inlet: gain coefficient
4th inlet: feedforward coefficient
Right inlet: feedback coefficient
clear Reset filter state to zero internal feedback
signal Left inlet: signal to be filtered
2nd inlet: delay time in milliseconds
3rd inlet: gain coefficient
4th inlet: feedforward coefficient
Right inlet: feedback coefficient

Information for box attributes common to all objects

Output
signal: The filtered signal.

Examples

Filter parameters may be supplied as float values or as signals

See Also
Name Description
allpass~ Apply an allpass filter effect
delay~ Delay a signal
reson~ Resonant bandpass filter
teeth~ Comb filter with feedforward and feedback delay control
MSP Tutorial 31: Comb Filter MSP Tutorial 31: Comb Filter
Audio Filtering Audio Filtering
cos~
Signal cosine function (0-1 range)

Description
Use the cos~ object to calculate and output a signal that is the cosine function of each sample of the input signal.

Arguments
None.

Messages
signal Input to a cosine function. The input is stated as a fraction of a cycle (typically in
the range from 0 to 1), and is multiplied by 2 before being used in the cosine
function.

Information for box attributes common to all objects

Output
signal: The cosine of 2 times the input. The method used in this object to calculate the cosine directly is typically less efficient
than using the stored cosine in a cycle~ object.

Examples

Cosine of the input (a fraction of a cycle) is calculated and sent out

See Also
Name Description
acos~ Signal arc-cosine function
acosh~ Signal hyperbolic arc-cosine function
asin~ Signal arc-sine function
asinh~ Signal hyperbolic arc-sine function
atan~ Signal arc-tangent function
atanh~ Signal hyperbolic arc-tangent function
atan2~ Signal arc-tangent function (two variables)
cosh~ Signal hyperbolic cosine function
cosx~ Signal cosine function
cycle~ Sinusoidal oscillator
phasor~ Generate sawtooth signals
sinh~ Signal hyperbolic sine function
sinx~ Signal sine function
tanh~ Signal hyperbolic tangent function
tanx~ Signal tangent function
trapezoid~ Trapezoidal wavetable
triangle~ Triangle/ramp wavetable
wave~ Variable size wavetable
2d.wave~ Two-dimensional wavetable
cosh~
Signal hyperbolic cosine function

Description
Use the cosh~ object to calculate and output a signal that is the hyperbolic cosine function of each sample of the input signal.

Arguments
None.

Messages
signal Input to hyperbolic cosine function

Information for box attributes common to all objects

Output
signal: The hyperbolic cosine of the input.

Examples

Exciting nautical motif audio control signals call for the cosh~ object

See Also
Name Description
acos~ Signal arc-cosine function
acosh~ Signal hyperbolic arc-cosine function
asin~ Signal arc-sine function
asinh~ Signal hyperbolic arc-sine function
atan~ Signal arc-tangent function
atanh~ Signal hyperbolic arc-tangent function
atan2~ Signal arc-tangent function (two variables)
cos~ Signal cosine function (0-1 range)
cosx~ Signal cosine function
sinh~ Signal hyperbolic sine function
sinx~ Signal sine function
tanh~ Signal hyperbolic tangent function
tanx~ Signal tangent function
cosx~
Signal cosine function

Description
Use the cosx~ object to calculate and output a signal that is the cosine function of each sample of the input signal. The cosx~
object is a true based function - it varies from the cos~ object, whose output is based around a value range of 0. - 1.0 and is
intended for use as a lookup table with the phasor~ object.

Arguments
None.

Messages
signal Output from a cosine function.

Information for box attributes common to all objects

Output
signal: The cosine of the input.

Examples

cosx~ can make your audio control signals less jumpy and more bumpy

See Also
Name Description
acos~ Signal arc-cosine function
acosh~ Signal hyperbolic arc-cosine function
asin~ Signal arc-sine function
asinh~ Signal hyperbolic arc-sine function
atan~ Signal arc-tangent function
atanh~ Signal hyperbolic arc-tangent function
atan2~ Signal arc-tangent function (two variables)
cos~ Signal cosine function (0-1 range)
cosh~ Signal hyperbolic cosine function
sinh~ Signal hyperbolic sine function
sinx~ Signal sine function
tanh~ Signal hyperbolic tangent function
tanx~ Signal tangent function
count~
Count samples elapsed

Description
Use the count~ object count samples elapsed and thus drive processes tightly synchronized to the sample rate. It outputs a signal
increasing by 1 for each sample elapsed. It can be set to loop, and can be used to drive objects such as index~ with sample
accuracy.

Arguments
Name Units Type Opt Description
minimum-count samples int opt Counter minimum value
maximum-count samples int opt Set the maximum value for a looping counter, or 0 for no maximum value. Note
that the maximum value is never reached.
enable int opt Specify whether the count~ object is off (0) or on (1) initially.
autoreset-state int opt When enabled, the internal counter is reset to the minimum value whenever audio
is turned on (see the autoreset message).

Messages
bang Reset to minimum and begin counting
int minimum-count [int] Set minimum value, reset, and begin counting
(inlet1) maximum-count [int] Set maximum value. A value of 0 eliminates the maximum.
float minimum/maximum-count Left inlet: Set minimum value without reset
[float]
Right inlet: Set maximum value without reset
list minimum-count [int] Set minimum, maximum, enable and autoreset state
maximum-count [int]
enable [int]
autoreset-state [int]
min minimum-count [int] Set minimum value without reset
set minimum-count [int] Set minimum value without reset
signal Enable counting with non-zero signal
stop Reset to minimum value

Attributes
Name Type g/s Description
autoreset int Reset the counter to the minimum value when audio turns on

Information for box attributes common to all objects

Output
signal: When the audio is first turned on, count~ always sends out its current minimum value. When a bang or int is received,
the count begins increasing from the current minimum value.

Examples
Send out a running count of the passing samples, beginning at a given point

See Also
Name Description
index~ Read from a buffer~ with no interpolation
mstosamps~ Convert milliseconds to samples
sampstoms~ Convert time from samples to milliseconds
+=~ Signal accumulator
counter Keep count based on bang messages
MSP Tutorial 13: Recording and MSP Tutorial 13: Recording and Playback
Playback
cross~
Third-order crossover filter

Description
Use the cross~ object as a pair of symmetrical low+high pass 3rd order filters with lowpass and highpass outlets you can use
separately or in combination to form a crossover filter.

Arguments
Name Units Type Opt Description
cutoff-frequency hz float Obligatory. The argument sets the initial cutoff frequency for the lowpass and the
highpass parts of the output signal.

Messages
int cutoff-frequency [int] In right inlet: Converted to float. Sets the filter cutoff frequency for both the
lowpass and the highpass parts of the output signal.
float cutoff-frequency [float] In right inlet: Sets the filter cutoff frequency for both the lowpass and the highpass
parts of the output signal.
clear Sets the filters' output memories to 0(this is helpful in case you blow it up).
signal In left inlet: Any signal to be filtered.

In right inlet: Sets the filter cutoff frequency for both the lowpass and the highpass
parts of the output signal.

Information for box attributes common to all objects

Output
signal: Out left inlet: The lowpass-filtered input signal.

In right inlet: The highpass-filtered input signal.

Together the lowpass and highpass filtered signals coombine to produce a flat frequency response equivalent to the input signal.
The phase response for the filtered output is, however, slightly altered.

Examples

Split a signal into high and low frequency components

See Also
Name Description
allpass~ Apply an allpass filter effect
biquad~ Two-pole, two-zero filter
filtergraph~ Edit a filter interactively
lores~ Resonant lowpass filter
onepole~ Single-pole lowpass filter
reson~ Resonant bandpass filter
svf~ State-variable filter with simultaneous outputs
Audio Filtering Audio Filtering
curve~
Exponential ramp generator

Description
Use the curve~ object to produce a signal that goes from an initial to target value over a specified time. It is similar to the line~
object, it produces non-linear ramps using a piecewise approximation of an exponential function.

Arguments
Name Units Type Opt Description
initial-value number opt The first argument sets an initial value for the signal output. The default value for
the parameter is 0.
curve-parameter number opt The second argument sets the initial curve parameter. The default value for the
curve parameter is 0.

Messages
int target-value [int] In left inlet: The number is the target value, to be arrived at in the time specified
by the number in the middle inlet. If no time has been specified since the last
target value, the time is considered to be 0 and the output signal jumps
immediately to the target value (ints are converted to floats).
float target-value [float] In left inlet: The number is the target value, to be arrived at in the time specified
by the number in the middle inlet. If no time has been specified since the last
target value, the time is considered to be 0 and the output signal jumps
immediately to the target value.
list target-value [number] In left inlet: The first number specifies a target value; the second number specifies
ramp-time [float] an amount of time, in milliseconds, to arrive at that value; and the optional third
curve-parameter [float] number specifies a curve parameter, for which values from 0 to 1 produce an
exponential curve and values from -1 to 0 produce a logarithmic curve. The closer
to 0 the curve parameter is, the more the curve resembles a straight line, and the
farther away the parameter is from 0, the more the curve resembles a step. In the
specified amount of time, curve~ generates an exponential ramp signal from the
currently stored value to the target value.

In middle inlet: A list may be used to specify time in one of the Max time
formats.
anything target-value [number] In left inlet: The first number specifies a target value; the second number specifies
ramp-time [float] an amount of time, in milliseconds, to arrive at that value; and the optional third
curve-parameter [float] number specifies a curve parameter, for which values from 0 to 1 produce an
exponential curve and values from -1 to 0 produce a logarithmic curve. The closer
to 0 the curve parameter is, the more the curve resembles a straight line, and the
farther away the parameter is from 0, the more the curve resembles a step. In the
specified amount of time, curve~ generates an exponential ramp signal from the
currently stored value to the target value.

In middle inlet: A list may be used to specify time in one of the Max time
formats.
factor nonlinear-factor [float] The word factor followed by a float will adjust the non-linear shaping parameters
of curve~.
pause In left inlet: Pauses the internal exponential ramp but does not change the target
value nor clear pending target-time-parameter triples. curve~ will continue
outputting whatever value was its current value when the pause message was
received, until either it receives a resume message or until a new ramp is input.
stop In left inlet: Stops the internal exponential ramp and clears pending target-time
parameter triples. curve~ will continue outputting whatever value was its current
value when the stop message was received, resetting its target value to that value.
resume In left inlet: Resumes the internal exponential ramp and subsequent pending
target-time pairs if the curve~ object was paused as a result of the pause
message.

Information for box attributes common to all objects

Output
bang: Out right outlet: When curve~ has finished generating all of its ramps, bang is sent out.
signal: Out left outlet: The current target value, or an exponential curve moving toward the target value according to the most
recently received target value, transition time, and curve parameter.

Examples

Curved ramps used as control signals for frequency and amplitude

See Also
Name Description
line~ Linear ramp generator
transport Control a master clock
cycle~
Sinusoidal oscillator

Description
Use the cycle~ object to generate a periodic waveform. The default waveform is one cycle of a cosine wave. You can also use the
wave~ object, which offers additional flexibility though slightly less optimization.

Arguments
Name Units Type Opt Description
frequency hz number opt Oscillator frequency (initial) The initial frequency of the oscillator
buffer-name symbol opt The name of a buffer~ object used to define the oscillator's wavetable. If a
frequency argument is present, the buffer~ name follows the frequency. If no
buffer~ name is given, cycle~ uses an internal 64-bit 16K cosine wavetable.
sample-offset int opt If a buffer~ name has been given, this defines the sample offset into the named
buffer~ object's sample memory. cycle~ only uses the first channel of a multi-
channel buffer~.

Messages
float frequency-or-phase [float] Left inlet: frequency of the oscillator
Right inlet: phase of the oscillator in the range 0.0 to 1.0
(mouse) Double-click to display buffer~ contents
set buffer-name [symbol] Set a buffer~ object to use as the wavetable, using the first 512 samples. If no
sample-offset [int] name is given, the internal cosine wavetable with 16K samples will be used. Use
the setall message to use an entire buffer~ as a wavetable.
setall value [symbol] Set a buffer~ object to use as the wavetable, using the entire buffer~ length. This
is in contrast to the set message which only uses the first 512 samples of the
buffer~.
signal Left inlet: frequency of the oscillator
Right inlet: phase of the oscillator in the range 0.0 to 1.0

Attributes
Name Type g/s Description
buffer symbol Buffer containing an external waveform. Setting the buffer~ with the attribute is
analogous to sending the setall message.
buffer_offset int Offset into buffer~
buffer_sizeinsamps int Override the size of the buffer used for the wavetable. If using the set message the
size will be 512, or if using the setall message the size will be the whole buffer~
length. Use this attribute to define a different size (the size should be a power of
two). Setting this size to 0 will result in an effective size of 512 and setting it to -1
will result an effective size of the whole buffer~ length.
'-1' = TEXT_HERE
'0' = TEXT_HERE
'16' = TEXT_HERE
'32' = TEXT_HERE
'64' = TEXT_HERE
'128' = TEXT_HERE
'256' = TEXT_HERE
'512' = TEXT_HERE
'1024' = TEXT_HERE
'2048' = TEXT_HERE
'4096' = TEXT_HERE
'8192' = TEXT_HERE
'16384' = TEXT_HERE
'32768' = TEXT_HERE
'65536' = TEXT_HERE
frequency float Oscillator frequency
phase float Phase offset

Information for box attributes common to all objects

Output
signal: A waveform (cosine by default) repeating at the specified frequency, with the specified phase.

Examples

Repeated cosine or any other waveform

See Also
Name Description
buffer~ Store audio samples
buffir~ buffer-based FIR filter
cos~ Signal cosine function (0-1 range)
line~ Linear ramp generator
phasor~ Generate sawtooth signals
rect~ Antialiased rectangular (pulse) oscillator
saw~ Antialiased sawtooth oscillator
techno~ Signal-driven step sequencer
trapezoid~ Trapezoidal wavetable
tri~ Antialiased triangular oscillator
triangle~ Triangle/ramp wavetable
wave~ Variable size wavetable
2d.wave~ Two-dimensional wavetable
MSP Tutorial 2: Adjustable MSP Tutorial 2: Adjustable Oscillator
Oscillator
MSP Tutorial 3: Wavetable MSP Tutorial 3: Wavetable Oscillator
Oscillator
MSP Tutorial 12: Waveshaping MSP Tutorial 12: Waveshaping
MSP Tutorial 13: Recording and MSP Tutorial 13: Recording and Playback
Playback
dac~
Audio output and on/off

Description
The dac~ object is the Digital-To-Analog-Converter through which you will route all signals from MSP out to your computer
speakers or audio hardware to be audible to the human ear. It also gives you access to the Audio Status window which controls
your audio settings and hardware.

Arguments
Name Units Type Opt Description
outputs int/symbol opt You can create a dac~ object that uses one or more audio output channel numbers
between 1 and 512. These numbers refer to logical channels and can be
dynamically reassigned to physical device channels of a particular driver using
either the Audio Status window, its I/O Mappings subwindow, or an adstatus
object with an output keyword argument.Arguments, If the computer's built-in
audio hardware is being used, there will be two input channels available. Other
audio drivers and/or devices may have more than two channels. If no argument is
typed in, dac~ will have two inlets, for input channels 1 and 2.

If a symbol is provided as the first argument to a dac~ object, then it will get an
independent control section in the Max mixer. If two dac~ instances in a patcher
hierarchy have the same name they will be on the same "bus" and share controls.

Messages
int on/off-flag [int] A non-zero number turns on audio processing in all loaded patches. 0 turns off
audio processing in all loaded patches.
list output-channel- list comprised of integers, sets the logical output channels for each signal inlet in
designations [list] order from left to right.
(mouse) Double-clicking on dac~ opens the Audio Status window.
open Opens the Audio Status window.
set output-channel- In any inlet: The word set, followed by a number, sets the logical output channel
designation [int] for the signal inlet in which the set message was received. For instance, sending
set 3 to the left inlet of dac~ makes the signal coming in the left inlet output to
logical output channel 3.

Note that if the audio is on and you use the set message to change a dac~ to use
logical channels that are not currently in use, no sound will be heard from these
channels until the audio is turned off and on again. For example, if you have a
dac~ object with arguments 1 2 3 4 and signals are only connected to the two
leftmost inlets (for channels 1 and 2), the message set 1 3 will not immediately
route the leftmost audio signal to logical channel 3, because it is not currently in
use. A method to get around this is to connect a sig~0 to each channel of a dac~
you plan on using for a set message. At this point, you might as well use a matrix~
or selector~ object to do something similar before the audio signal reaches the
dac~.
signal A signal coming into an inlet of dac~ is sent to the audio output channel
corresponding to the inlet. The signal must be between -1 and 1 to avoid clipping
by the DAC.
start Turns on audio processing in all loaded patches.
startwindow Turns on audio processing only in the patch in which this dac~ is located, and in
subpatches of that patch. Turns off audio processing in all other patches.
stop Turns off audio processing in all loaded patches.
wclose Closes the Audio Status window if it is open.
Information for box attributes common to all objects

Output
Audio: dac~ produces no output internal to the application. The signal received in the inlet is sent to its assigned logical audio
output channel, which is mapped to a physical device output channel in the Ausio Status window which is also made accessible
via the dac~.

Examples

Switch audio on and off, send signal to the audio outputs

See Also
Name Description
adc~ Audio input and on/off
adstatus Report and control audio driver settings
ezadc~ Audio input and on/off button
ezdac~ Audio output and on/off button
MSP: Audio Input and Output MSP: Audio Input and Output
MSP Tutorial 1: Test Tone MSP Tutorial 1: Test Tone
dbtoa~
Convert a deciBel value to linear amplitude at signal rate

Description
atodb~ takes any given signal representing a deciBel amplitude value and outputs a signal which is a linear amplitude conversion
of the input.

Arguments
None.

Messages
signal A signal representing a gain/attenuation, expressed in deciBels. It is converted to a
linear amplitude value and output as a signal.

Information for box attributes common to all objects

Output
signal: The linear amplitrude value output as a signal.

Examples

Old-fashioned, no-nonsense numerical conversion

See Also
Name Description
expr Evaluate a mathematical expression
atodb Convert linear amplitude to decibels
atodb~ Convert linear amplitude to a signal-rate deciBel value
dbtoa Convert decibels to a linear amplitude
degrade~
Signal quality reducer

Description
degrade~ takes any given signal and reduces the sampling rate and bit-depth as specified/desired.

Arguments
Name Units Type Opt Description
resampling- float opt The first argument sets the resampling frequency ratio, as described above. If this
frequency-ratio argument is not supplied, the default value is 1.0.
number-of- int opt The second argument sets the number of bits used to quantize the input signal. If
quantization-bits this argument is not supplied, the default value is 24.

Messages
signal In left inlet: The signal to be degraded.

Information for box attributes common to all objects

Output
signal: The output signal is the input signal after being resampled and quantized. Note that this object deliberately does not use
any interpolation when resampling, nor any dithering when quantizing. It is intended for creating "low-fi" effects.

Note: Use caution when listening to the output of this object. Quantizing to a small number of bits can create very loud, noisy
signals.

Examples

Change a signal's effective sampling rate and bit depth

See Also
Name Description
downsamp~ Downsample a signal
round~ Round an input signal value
delay~
Delay a signal

Description
Use the delay~ object to delay a signal by a certain amount of time. The delay time can be specified in samples (determined by the
sampling rate), or using the Max time format syntax for tempo-relative values.

Arguments
Name Units Type Opt Description
maximum-delay- samples int Set maximum delay time in samples. This determines the amount of memory
memory allocated for the delay line.
initial-delay-time time- list opt Set the initial delay time. The delay time can be either a number which specifies
value time in samples (e.g. delay~ 44100 200) or a notevalue (e.g. delay~ 2000 2n).

Messages
int delay-time [int] In right inlet: set delay time. The delay time cannot be less than 0 (no delay) nor
can it be greater than the maximum delay time.
float delay-time [float] Set delay time (converted to int)
list time/transport-settings [list] Set delay time in a Max time format.
anything time/transport-settings [list] Set delay time in a Max time format.
clear Zero the delay memory
maxsize maximum-delay-memory Set maximum delay time
[int]
ramp ramp-time [float] Set the time to ramp to a new delay time
signal In left inlet: Signal to be delayed.
In right inlet: Set delay time. Signal-based delay uses interpolation, which
introduces a one-sample delay.

Attributes
Name Type g/s Description
delay atom Delay Time

Information for box attributes common to all objects

Output
signal: The output consists of the input delayed by the specified number of samples.

Examples

Delay signal for a specific number of samples, for echo or filtering effects

See Also
Name Description
comb~ Apply a comb filter effect
tapin~ Input to a delay line
tapout~ Output from a delay line
mstosamps~ Convert milliseconds to samples
sampstoms~ Convert time from samples to milliseconds
pipe Delay numbers, lists or symbols
transport Control a master clock
delta~
Signal of sample differences

Description
delta~ outputs a signal which represents the differences between each incoming sample value in the input signal.

Arguments
None.

Messages
signal Input signal to be evaluated.

Information for box attributes common to all objects

Output
signal: The output consists of samples that are the difference between the current input sample and the previous input sample.
For example, if the input signal contained 1,.5,2,.5, the output would be 1,-.5,1.5,-1.5.

Examples

Report the difference between one sample and the previous sample

See Also
Name Description
average~ Multi-mode signal average
avg~ Signal average
deltaclip~
Limit changes in signal amplitude

Description
deltaclip~ limits the change between samples in an incoming signal. It is similar to the clip~ object, but it limits amplitude
changes with respect to slope rather than amplitude.

Arguments
Name Units Type Opt Description
minimum-slope- float opt Initial minimum slope value for the rate of change of the output signal. If no
value argument is supplied, the minimum limit is initially set to 0. If a signal is
connected to the middle inlet, the corresponding argument is ignored.
minimum and float opt Initial maximum slope value for the rate of change of the output signal. If no
maximum-slope- argument is supplied, the maximum limit is initially set to 0. If a signal is
values connected to the right inlet, the corresponding argument is ignored.

Messages
int minimum and maximum- In middle inlet: Minimum slope for the rate of change of the output signal. The
slope-value [int] minimum slope is typically negative.

In right inlet: Maximum slope for the rate of change of the output signal. The
maximum slope is typically positive.
float minimum and maximum- In middle inlet: Minimum slope for the rate of change of the output signal. The
slope-value [float] minimum slope is typically negative.

In right inlet: Maximum slope for the rate of change of the output signal. The
maximum slope is typically positive.
(inlet1) minimum-slope-value [float] In middle inlet: Minimum slope for the rate of change of the output signal. The
minimum slope is typically negative.
(inlet2) maximum-slope-value [float] In right inlet: Maximum slope for the rate of change of the output signal. The
maximum slope is typically positive.
reset Resets the minimum and maximum slope values to the default value of 0.
signal In left inlet: Any signal.

Information for box attributes common to all objects

Output
signal: The input signal is sent out, with its change limited by the minimum and maximum slope values.

Examples

Limit a signal's rate of change

See Also
Name Description
clip~ Limit signal amplitude
/~
Divide one signal by another

Description
Use the /~ object is to multiply a signal coming into the left inlet by the reciprocal of either the initial argument or an int or float
received in the right inlet.

Arguments
Name Units Type Opt Description
initial-divisor number opt Sets an initial value by which to divide the signal coming into the left inlet. If a
signal is connected to the right inlet, the argument is ignored. If no argument is
present, and no signal is connected to the right inlet, the initial value is 1 by
default.

Messages
int dividend/divisor [int] In left inlet: The number is divided by the signal coming into the right inlet. If a
signal is also connected to the left inlet, a float or int is ignored.

In right inlet: A number by which to divide the signal coming into the left inlet. If a
signal is also connected to the right inlet, a float or int is ignored.
float dividend/divisor [float] In left inlet: The number is divided by the signal coming into the right inlet. If a
signal is also connected to the left inlet, a float or int is ignored.

In right inlet: A number by which to divide the signal coming into the left inlet. If a
signal is also connected to the right inlet, a float or int is ignored.
signal In left inlet: The signal is divided by a signal coming into the right inlet, or a
constant value received in the right inlet.

In right inlet: The signal is used as the divisor, to be divided into the signal coming
into the left inlet, or the constant value received in the left inlet.

Information for box attributes common to all objects

Output
signal: The ratio of the two inputs, i.e., the left input divided by the right input.

Examples

It is more computationally efficient to use an equivalent multiplication when possible

See Also
Name Description
!/~ Divide input from a number
*~ Multiply two signals
%~ Divide two signals, output the remainder
downsamp~
Downsample a signal

Description
downsamp~ samples and holds a signal received in the left inlet at a rate set by an argument to the object of the value received in
the right inlet, expressed in samples. No interpolation of the output is performed.

Arguments
Name Units Type Opt Description
downsampled-rate number opt Sets the sample rate.

Messages
int downsampled-rate [int] In right inlet: Sets the sample rate used to downsample the input signal. You can
specify the number of samples with floating-point values, but the downsamp~
object will sample the input at most as frequently as the current sampling rate.
float downsampled-rate [float] In right inlet: Sets the sample rate used to downsample the input signal. You can
specify the number of samples with floating-point values, but the downsamp~
object will sample the input at most as frequently as the current sampling rate.
signal In left inlet: A signal to be downsampled.

In right inlet: The rate, in samples, at which the incoming signal is to be


downsampled.

Information for box attributes common to all objects

Output
signal: The input signal, resampled at the rate set by argument or by the value received in the right inlet.

Examples

Sample and hold every n samples

See Also
Name Description
degrade~ Signal quality reducer
sah~ Sample and hold a signal according to a trigger
dspstate~
Report current DSP settings

Description
dspstate~ can be used for calculations that require the sampling rate of current DSP processing block size. You can also use the
leftmost outlet to trigger some event when the audio is turned on or off.

Arguments
None.

Messages
bang Triggers a report out the dspstate~ object's outlets, telling whether the audio is on
or off, the current sampling rate, and the signal vector size.
signal If a signal is connected to the dspstate~ object's inlet, dspstate~ reports that
signal's sampling rate and vector size, rather than the global sampling rate and
signal vector size.

Information for box attributes common to all objects

Output
float: Out second outlet: Sampling rate of the connected signal or the global sampling rate.
int: Out left outlet: If the audio is on or being turned on, 1 is sent out. If the audio is off or being turned off, 0 is sent out.
int: Out third outlet: Current DSP signal vector size.
int: Out fourth outlet: Current I/O signal vector size.

Examples

Trigger an action when audio is turned on or off use sample rate to calculate timings

See Also
Name Description
adstatus Report and control audio driver settings
sampstoms~ Convert time from samples to milliseconds
mstosamps~ Convert milliseconds to samples
MSP Tutorial 20: MIDI Sampler MSP Tutorial 20: MIDI Sampler Control
Control
MSP Tutorial 25: Using the FFT MSP Tutorial 25: Using the FFT
MSP Tutorial 26: Frequency MSP Tutorial 26: Frequency Domain Signal Processing with pfft~
Domain Signal Processing with
pfft~
dsptime~
Report milliseconds of audio processed

Description
dsptime~ reports the time in milliseconds since the audio was last turned on when triggered by a bang.

Arguments
None.

Messages
bang When dsptime~ receives a bang, it reports the number of milliseconds
corresponding to the number of audio samples that have currently been processed.
signal If a signal is connected to the dsptime~ object's inlet, dsptime~ reports the
number of milliseconds corresponding to the number of audio samples that have
currently been processed within the connected signal.

Information for box attributes common to all objects

Output
float: The number of milliseconds corresponding to the number of audio samples that have currently been processed. The value
is based on the processed audio sample count, not the real time of the millisecond timer. This means you can use the dsptime~
object as a sort of clock in conjunction with the ad_nonreal audio driver.

Examples

Shut audio processing off automatically after 40 seconds have been processed

See Also
Name Description
adstatus Report and control audio driver settings
edge~
Detect logical signal transitions

Description
Use the edge~ to detect zero to non-zero (and vice versa) signal transitions and report a bang out of one of its two outlets
according to which direction the transition has occurred.

Arguments
None.

Messages
signal A signal that will change between zero and non-zero values

Information for box attributes common to all objects

Output
bang: Out left outlet: Sent when the input signal changes from zero to non-zero. The minimum time between bang messages will
not be shorter than the minimum scheduler interval, which is generally equal to the signal vector size, but may be larger if
Scheduler in Audio Interrupt mode is not enabled.

Out right outlet: Sent when the input signal changes from non-zero to zero. The output will not happen more often than the time
represented by the number of samples in the current input/output vector size.

Examples

Send a triggering Max message when a significant moment occurs in a signal

See Also
Name Description
change~ Report signal direction
thresh~ Detect signal above a set level
zerox~ Detect zero crossings
==~
Is equal to, comparison of two signals

Description
==~ outputs a 1 signal when the left input is equal to the right input and a 0 when it is not equal to the right input. The right
input can be a signal or a float.

Arguments
Name Units Type Opt Description
initial- number opt Sets an initial comparison value for the signal coming into the left inlet. 1 is sent
comparison-value out if the signal is equal to the argument; otherwise, 0 is sent out. If a signal is
connected to the right inlet, the argument is ignored. If no argument is present,
and no signal is connected to the right inlet, the initial value is 0 by default.

Messages
int input-comparison-value [int] In right inlet: A number to be used for comparison with the signal coming into the
left inlet. If a signal is also connected to the right inlet, a float or int is ignored.
float input-comparison-value [float] In right inlet: A number to be used for comparison with the signal coming into the
left inlet. If a signal is also connected to the right inlet, a float or int is ignored.
signal In left inlet: The signal is compared to a signal coming into the right inlet, or a
constant value received in the right inlet. If it is equal to the value in the right
inlet, 1 is sent out; otherwise, 0 is sent out.

In right inlet: The signal is used for comparison with the signal coming into the left
inlet.

Information for box attributes common to all objects

Output
signal: If the signal in the left inlet is equal to the value in the right inlet, 1 is sent out; otherwise, 0 is sent out.

Examples

Detect when a signal equals a certain value, or when two signals equal each other

See Also
Name Description
<~ Is less than, comparison of two signals
<=~ Is less than or equal to, comparison of two signals
>~ Is greater than, comparison of two signals
>=~ Is greater than or equal to, comparison of two signals
!=~
Not equal to, comparison of two signals
change~ Report signal direction
edge~ Detect logical signal transitions
ezadc~
Audio input and on/off button

Description
ezadc~ works as a user interface version of the adc~ object. It appears as a button which can be clicked with the mouse to turn
audio on or off.

Arguments
None.

Messages
int stop/start-flag [int] A non-zero number turns on audio processing in all loaded patches. A value of 0
turns all audio processing off.
list input-channel- list comprised of integers sets the logical input channels for each signal inlet.
designations [list]
(mouse) Clicking on ezadc~ toggles audio processing on or off. Audio on is represented by
the object being highlighted.
local behavioral [int] The word local, followed by 1, makes a click to turn on an ezadc~ object
equivalent to sending it the startwindow message. The message local 0 returns
the ezadc~ object to its default mode where a click to turn it on is equivalent to
the start message.
open Opens the Audio Status window. The window is also brought to the front.
set logical-output-channel The word set, followed by two numbers, sets the logical input channel for one of
[int] the object's signal outlets. The first number specifies the outlet number, where 1 is
logical-input-channel the leftmost outlet. The second number specifies the logical input channel (from 1
[int] to 512). If the second number is 0, the outlet sends out the zero signal.
start Turns on audio processing in all loaded patches.
startwindow Turns on audio processing only in the patch in which this ezadc~ is located, and
in subpatches of that patch. Turns off audio processing in all other patches.
stop Turns off audio processing in all loaded patches.
wclose Closes the Audio Status window.

Attributes
Name Type g/s Description
bgcolor float Background Color
border float Border Size
def.:0.
bordercolor float Border Color
local int Switch is Local
def.:0
offgradcolor1 float Foreground Color Off 1
offgradcolor2 float Foreground Color Off 2
ongradcolor1 float Foreground Color On 1
ongradcolor2 float Foreground Color On 2

Information for box attributes common to all objects

Output
signal: Out left outlet: Audio input from channel 1.

Out right outlet: Audio input from channel 2.


Examples

Audio input for processing and recording

See Also
Name Description
adstatus Report and control audio driver settings
Audio input and on/off button
adc~ Audio input and on/off
MSP: Audio Input and Output MSP: Audio Input and Output
MSP Tutorial 13: Recording and MSP Tutorial 13: Recording and Playback
Playback
ezdac~
Audio output and on/off button

Description
ezdac~ works as a user interface version of the dac~ object. It appears as a button which can be clicked with the mouse to turn
audio on or off.

Arguments
None.

Messages
int on/off-flag [int] A non-zero number turns on audio processing in all loaded patches. 0 turns off
audio processing in all loaded patches.
list output-channel- list comprised of integers, sets the logical output channels for each signal inlet in
designations [list] order from left to right.
(mouse) Clicking on ezdac~ toggles audio processing on or off. Audio on is represented by
the object being highlighted.
local behavioral [int] The word local, followed by 1, makes a click to turn on an ezdac~ object
equivalent to sending it the startwindow message. The message local 0 returns
the ezdac~ object to its default mode where a click to turn it on is equivalent to
the start message.
open Opens the Audio Status window. The window is also brought to the front.
set output-channel- In any inlet: The word set, followed by a number, sets the logical output channel
designation [int] for the signal inlet in which the set message was received. For instance, sending
set 3 to the left inlet of ezdac~ makes the signal coming in the left inlet output to
logical output channel 3.

Note that if the audio is on and you use the set message to change a ezdac~ to use
logical channels that are not currently in use, no sound will be heard from these
channels until the audio is turned off and on again.
signal In left inlet: The signal is sent to audio output channel 1. The signal in each inlet
must be between -1 and 1 to avoid clipping by the DAC.

In right inlet: The signal is sent to audio output channel 2.


start Turns on audio processing in all loaded patches.
startwindow Turns on audio processing only in the patch in which this ezdac~ is located, and
in subpatches of that patch. Turns off audio processing in all other patches.
stop Turns off audio processing in all loaded patches.
wclose Closes the Audio Status window.

Attributes
Name Type g/s Description
bgcolor float Sets the color of the ezdac~ button background in RGBA format.
border float Border size in pixels
def.:0.
bordercolor float Sets the border color in RGBA format.
local int Toggles enabling/disabling audio input for the local window only in the patch in
def.:0 which this ezdac~ is located, and in subpatches of that patch. Turns off audio
processing in all other patches.
offgradcolor1 float Sets the first gradient color used in the ezdac~ button in the off position in RGBA
format.
offgradcolor2 float
Sets the second gradient color used in the ezdac~ button in the off position in
RGBA format.
ongradcolor1 float Sets the first gradient color used in the ezdac~ button in the on position in RGBA
format
ongradcolor2 float Sets the second gradient color used in the ezdac~ button in the on position in
RGBA format.

Information for box attributes common to all objects

Output
Audio: None. The signal received in the inlet is sent to the corresponding audio output channel.

Examples

Switch audio on and off, send signal to the audio outputs

See Also
Name Description
adstatus Report and control audio driver settings
ezadc~ Audio input and on/off button
adc~ Audio input and on/off
MSP: Audio Input and Output MSP: Audio Input and Output
MSP Tutorial 3: Wavetable MSP Tutorial 3: Wavetable Oscillator
Oscillator
fbinshift~
Frequency domain frequency shifter for pfft~

Description
The fbinshift~ object implements a frequency-domain frequency shifter that can be used inside a patch loaded by a pfft~ object.

Arguments
Name Units Type Opt Description
frequency-shift hz float opt A numerical argument will be used as the frequency shift in Hertz. The default is
zero.
frequency-shift hz int Integer inputs are converted to floating-point values and used as the frequency
shift in Hertz. The default is zero.

Messages
signal In left inlet: The signal present at the left inlet is the real part of a frequency-
domain signal coming from a fftin~ object inside a pfft~.

In middle inlet: The signal input to the middle inlet is the imaginary part of a
frequency-domain signal coming from a fftin~ object inside a pfft~. Both real and
imaginary inputs must be connected for the fbinshift~ to work.

Information for box attributes common to all objects

Output
signal: The output is the frequency shifted complex signal. The left outlet is the real component, and the right outlet is the
imaginary component. These may be connected to the real and imaginary inputs of a fftout~ object inside a pfft~.

Examples

Using fbinshift~ inside a pfft~ subpatch

See Also
Name Description
freqshift~ Time-domain frequency shifter
gizmo~ Frequency-domain pitch shifter for pfft~
hilbert~ Phase quadrature filter
fffb~
Fast fixed filter bank

Description
The fffb~ object implements a bank of bandpass filter objects, each of which is similar to the reson~ filter object. An input signal
is applied to all filters, and the outputs of each filter are available separately.

Arguments
Name Units Type Opt Description
number-of-filters int The first argument specifies the number of filters.
1st-filter- float opt Three additional float arguments may be used to specify the frequency of the first
frequency filter, the ratio of frequencies between successive filters, and the Q factor for all of
the filters.
filter-frequency- float opt Following the initial first filter frequency, a list is used to specify the ratio of
ratios (float) frequencies between successive filters.
Q list opt Following the initial first filter frequency and frequency ratio arguments, a third
argument specifies the Q applied to all filters.
harmonic-series- symbol opt If you use the letter H as the second argument rather than a float, the filters will be
flag (H) tuned to a harmonic series rather using frequency ratios.

Messages
list filter-index and settings A filter index followed by just a frequency or a frequency and a Q setting will set
[list] the particular filter addressed by the index number to the settings which follow it.
anything filter-index and settings A filter index followed by just a frequency or a frequency and a Q setting will set
[list] the particular filter addressed by the index number to the settings which follow it.
Q bandwidths [list] In left inlet: The symbol Q, followed by a list consisting of an int and one or more
floats, sets the Q factors of the filters, starting with the filter whose index is given
by the first number. This filter's Q factor is set to the second number in the list.
Any following numbers in the list set the Q factors of filters following the first
designated one. Indices are zero-based.
QAll general-bandwidth [float] In left inlet: The word QAll, followed by a float, sets the Q of all of the filters to the
given floating-point value.
clear Clears the fffb~ object's memory of previous inputs and outputs.
freq filter-frequencies [list] In left inlet: The word freq, followed by a list consisting of an int and one or more
floats, sets the center frequencies of the filters starting with the filter whose index
is given by the first number. This filter's frequency is set to the second number in
the list. Any following numbers in the list set the frequencies of filters following
the first designated one. Indices are zero-based.

For example, the message freq 3 1974.0 333.0 1234.0 sets the frequency of the
fourth filter to 1974Hz, the fifth filter to 333Hz, and the sixth filter to 1234Hz.
gain amplitudes [list] In left inlet: The word gain, followed by a list consisting of an int and one or more
floats, sets the gains of the filters starting with the filter whose index is given by
the first number. This filter's gain is set to the second number in the list. Any
following numbers in the list set the gains of filters following the first designated
one. Indices are zero-based.
freqAll general-center-frequency in left inlet: The word freqAll, followed by a float, sets the center frequencies of all
[float] of the filters to the given floating-point value.
freqRatio frequency-ratios [list] In left inlet: The word freqRatio, followed by a list of two or more numbers sets
the center frequency of the first filter to the first value in the list, and sets the
frequencies of the remaining filters by repeatedly multiplying the first value by the
second, so that the ratio of frequencies of successive filters is the second value. For
example, the message freqRatio 440. 2. sets the frequency of the first filter to
440Hz, the frequency of the second to 880Hz, the frequency of the third to
1760Hz, and so on.

If the second item in the list is the letter H rather than a number, the filters will be
tuned in a harmonic series. For example, the message freqRatio 100 H sets the
frequencies of the filters to 100Hz, 200Hz, 300Hz, 400Hz, and so on.
gainAll general-amplitude [float] In left inlet: The word gainAll, followed by a float, sets the gain of all of the filters
to the given floating-point value.
signal The signal present at the left inlet is sent to all of the filters.

Information for box attributes common to all objects

Output
signal: The output of each filter is provided at a separate outlet. The leftmost outlet is the output of the first filter.

Examples

Stereo expansion by altering the base frequency and frequency ratio

See Also
Name Description
reson~ Resonant bandpass filter
Audio Filtering Audio Filtering
fft~
Fast Fourier transform

Description
fft~ performs a Fast Fourier transform on any incoming signal and outputs the real and imaginary parts of that transform as well
as a synchronization signal.

Arguments
Name Units Type Opt Description
number-of-FFT- int opt The first argument specifies the number of points (samples) in the FFT. It must be
samples a power of two. The default number of points is 512.
spectral-frame-size int opt The second argument specifies the number of samples between successive FFTs.
This must be at least the number of points, and must also be a power of two. The
default interval is 512.
number-of-FFT- int opt The third argument specifies the offset into the interval where the FFT will start.
samples This must either be 0 or a multiple of the signal vector size. fft~ will correct bad
arguments, but if you change the signal vector size after creating an fft~ and the
offset is no longer a multiple of the vector size, the fft~ will not operate when
signal processing is turned on.

Messages
phase offset [int] Offset from the beginning of a period when the FFT is performed.
signal In left inlet: The real part of a complex signal that will be transformed.

In right inlet: The imaginary part of a complex signal that will be transformed.

If signals are connected only to the left inlet and left outlet, a real FFT (fast Fourier
transform) will be performed. Otherwise, a complex FFT will be performed.

Information for box attributes common to all objects

Output
signal: Out left outlet: The real part of the Fourier transform of the input. The output begins after all the points of the input have
been received.

Out middle outlet: The imaginary part of the Fourier transform of the input. The output begins after all the points of the input
have been received.

Out right outlet: A sync signal that ramps from 0 to the number of points minus 1 over the period in which the FFT output
occurs. You can use this signal as an input to the index~ object to perform calculations in the frequency domain. When the FFT
is not being sent out (in the case where the interval is larger than the number of points), the sync signal is 0.

Examples
Fast Fourier transform of an audio signal

See Also
Name Description
cartopol Convert cartesian to polar coordinates
cartopol~ Signal Cartesian to Polar coordinate conversion
fftin~ Input for a patcher loaded by pfft~
fftinfo~ Report information about a patcher loaded by pfft~
fftout~ Output for a patcher loaded by pfft~
frameaccum~ Compute "running phase" of successive phase deviation frames
framedelta~ Compute phase deviation between successive FFT frames
ifft~ Inverse fast Fourier transform
index~ Read from a buffer~ with no interpolation
pfft~ Spectral processing manager for patchers
poltocar Convert polar to cartesian coordinates
poltocar~ Signal Polar to Cartesian coordinate conversion
vectral~ Vector-based envelope follower
MSP Tutorial 25: Using the FFT MSP Tutorial 25: Using the FFT
fftin~
Input for a patcher loaded by pfft~

Description
The fftin~ object provides an signal input to a patcher loaded by a pfft~ object.

Arguments
Name Units Type Opt Description
inlet-assignment int Determines the inlet number of the pfft~ which will be routed into the fftin~
object. Inlet assignment starts at one, for the leftmost inlet in the pfft~. Multiple
fftin~ objects will typically have different inlet numbers.
window-envelope- symbol Specifies the window envelope function the fftin~ object will apply to overlapping
function FFTs on the input signal. The options are square (i.e. no window envelope),
hanning (the default), triangle, hamming and blackman (Note: The Blackman
window should be used with an overlap of 4 or more). If the symbol nofft is used,
then the fftin~ object will not use a windowing envelope and will not perform a
Fast Fourier Transform -- it will echo the first half of its input sample window to
its real output and the second half of its input sample window to its imaginary
output. This can allow you to input raw control signals from outside the parent
patcher through inlets in the pfft~ object, provided its overlap is set to 2. Other
overlap values may not yield useful results.

Messages
signal Dummy inlet for the connection of a begin~ object. The signal input for an fftin~
object is an inlet in the pfft~ subpatcher which contains the object.

Information for box attributes common to all objects

Output
signal: Out left outlet: This output contains the real-values resulting from the Fast Fourier transform performed on the
corresponding inlet of the pfft~. This output frame is only half the size of the parent pfft~ object's FFT size because the spectrum
of a real input signal is symmetrical and therefore half of it is redundant. The real and imaginary pairs for one spectrum are called
a spectral frame.

Out middle outlet: This output contains the imaginary-values resulting from the Fast Fourier transform performed on the
corresponding inlet of the pfft~. This output frame is only half the size of the parent pfft~ object's FFT size because the spectrum
of a real input signal is symmetrical and therefore half of it is redundant. The real and imaginary pairs for one spectrum are called
a spectral frame.

Out right outlet: A stream of samples corresponding to the index of the current bin whose data is being sent out the first two
outlets. This is a number from 0 - (frame size - 1). The spectral frame size inside a pfft~ object's subpatch is equal to half the FFT
window size.

Examples

fftin~ outputs a frequency/domain signal pair and a sync signal that indicates the bin number
See Also
Name Description
cartopol Convert cartesian to polar coordinates
cartopol~ Signal Cartesian to Polar coordinate conversion
fft~ Fast Fourier transform
fftinfo~ Report information about a patcher loaded by pfft~
fftout~ Output for a patcher loaded by pfft~
frameaccum~ Compute "running phase" of successive phase deviation frames
framedelta~ Compute phase deviation between successive FFT frames
ifft~ Inverse fast Fourier transform
in Message input for a patcher loaded by poly~ or pfft~
out Message output for a patcher loaded by poly~ or pfft~
pfft~ Spectral processing manager for patchers
poltocar Convert polar to cartesian coordinates
poltocar~ Signal Polar to Cartesian coordinate conversion
vectral~ Vector-based envelope follower
MSP Tutorial 26: Frequency MSP Tutorial 26: Frequency Domain Signal Processing with pfft~
Domain Signal Processing with
pfft~
fftinfo~
Report information about a patcher loaded by pfft~

Description
fftinfo~ gets info about the fft frames in a patcher loaded by a pfft~. It reports the information when sent a bang or whenever
DSP is turned on via a dac~ (fftinfo~ only functions within a pfft~).

Arguments
None.

Messages
bang Causes the FFT window size, the FFT frame size (i.e., the signal vector size inside
the patcher loaded by pfft~), and the FFT hop size to be sent out the object's
outputs.
signal Reports the FFT window size, the FFT frame size, and the FFT hop size of the
signal network to which it is connected.

Information for box attributes common to all objects

Output
int: Out left outlet: The current FFT window size specified by argument to the pfft~ object.

Out middle-left outlet: The current spectral frame size (half the FFT window size).

Out middle-right outlet: The current FFT hop size (i.e., the window size divided by the overlap).

Out right outlet: The full spectrum flag. It indicates whether or not the spectral subpatch of the parent pfft~ object is processing
the default half-spectrum FFT frames, or full (mirrored) FFT spectrum frames.

Examples

fftinfo~ reports information about the FFT subpatcher in which it is located

See Also
Name Description
cartopol Convert cartesian to polar coordinates
cartopol~ Signal Cartesian to Polar coordinate conversion
fft~ Fast Fourier transform
fftin~ Input for a patcher loaded by pfft~
fftout~ Output for a patcher loaded by pfft~
frameaccum~ Compute "running phase" of successive phase deviation frames
framedelta~ Compute phase deviation between successive FFT frames
ifft~ Inverse fast Fourier transform
pfft~ Spectral processing manager for patchers
poltocar Convert polar to cartesian coordinates
poltocar~ Signal Polar to Cartesian coordinate conversion
vectral~ Vector-based envelope follower
MSP Tutorial 25: Using the FFT MSP Tutorial 25: Using the FFT
MSP Tutorial 26: Frequency MSP Tutorial 26: Frequency Domain Signal Processing with pfft~
Domain Signal Processing with
pfft~
fftout~
Output for a patcher loaded by pfft~

Description
The fftout~ object provides an signal output to a pfft~ object.

Arguments
Name Units Type Opt Description
outlet-assignment int Determines the outlet number in the pfft~ which will receive the output of the
fftout~ object. Outlet assignments start at 1 for the leftmost outlet of pfft~.
Multiple fftout~ objects will typically have different outlet numbers.
window-envelope- symbol opt Tells fftout~ which window envelope function to use when overlapping fft's on the
function input signal. The options are square (i.e. no window envelope), hanning (the
default), and hamming. If the argument nofft is used, then the fftout~ will echo
its input signal to its output without performing a Fast Fourier transform. This
allows you to output raw control signals from the pfft~ to the parent patcher. Note
that when the nofft option is used, overlap-adding is still being performed to
create the output signal.

Messages
signal In left inlet: The real part of a signal that will be inverse-transformed back into the
time domain.

In right inlet: The imaginary part of a signal that will be inverse-transformed back
into the time domain.
Note that the real and imaginary inlets of fftout~ expect only the first half of the
spectrum, as output by fftin~. This half-spectrum is called a spectral frame in
pfft~ terminology.

Information for box attributes common to all objects

Output
signal: The fftout~ object transforms frequency domain signals back into the time domain, at which point they are overlap-
added and output by the corresponding outlet in the pfft~ object in which the subpatcher is loaded. The fftout~ object itself has
no outlets.

Examples

fftout~ converts frequency domain signal pairs into time domain signals and sends them to pfft~

See Also
Name Description
cartopol Convert cartesian to polar coordinates
cartopol~ Signal Cartesian to Polar coordinate conversion
fft~ Fast Fourier transform
fftin~ Input for a patcher loaded by pfft~
fftinfo~ Report information about a patcher loaded by pfft~
frameaccum~ Compute "running phase" of successive phase deviation frames
framedelta~ Compute phase deviation between successive FFT frames
ifft~ Inverse fast Fourier transform
out Message output for a patcher loaded by poly~ or pfft~
pfft~ Spectral processing manager for patchers
poltocar Convert polar to cartesian coordinates
poltocar~ Signal Polar to Cartesian coordinate conversion
vectral~ Vector-based envelope follower
MSP Tutorial 25: Using the FFT MSP Tutorial 25: Using the FFT
MSP Tutorial 26: Frequency MSP Tutorial 26: Frequency Domain Signal Processing with pfft~
Domain Signal Processing with
pfft~
filtercoeff~
Signal-rate filter coefficient generator

Description
The filtercoeff~ object is a signal-rate filter coefficient calculator for the biquad~ object. It calculates the filter coefficients from
three higher-level parameters: frequency, amplitude and resonance (Q) or slope (S). Its internal calculations are based on those of
the filtergraph~ object.

Arguments
Name Units Type Opt Description
default-filter-type symbol opt A symbol argument may be used to set the default filter type (highpass, lowpass,
etc...).
resampling-factor int opt An optional second argument can be used to specify a resampling factor.

Messages
int filter-parameters [int] Integer values are converted to float.

In 1st inlet: Sets the center or cutoff frequency parameter for the filter and causes
output.

In 2nd inlet: Sets the gain parameter for the filter and causes output.

In 3rd inlet: Sets the Q (resonance) or S (slope) parameter for the filter and causes
output. (note that the term slope is only used for the third parameter of shelving
filters, and is roughly equivalent to resonance).
float filter-parameters [float] In 1st inlet: Sets the center or cutoff frequency parameter for the filter and causes
output.

In 2nd inlet: Sets the gain parameter for the filter and causes output.

In 3rd inlet: Sets the Q (resonance) or S (slope) parameter for the filter and causes
output. (note that the term slope is only used for the third parameter of shelving
filters, and is roughly equivalent to resonance)
list center-frequency [float] A list of up to 3 floats will specify the center-frequency, the gain, and the Q-factor
initial-gain [float] respectively. A signal connected to any inlet where these parameters would
Q [float] normally be received will override any input from a list and the effects of these
parameters are completely dependent on what type of filter is chosen.
bandpass center-frequency [float] In left inlet: The word bandpass sets the filter type to bandpass mode. The
Q [float] frequency response of the filter is based on two parameters: center frequency and
Q (resonance). The gain parameter is set to unity gain (1.0).
bandstop center-frequency [float] In left inlet: The word bandstop sets the filter type to bandstop mode. The
Q [float] frequency response of the filter is based on two parameters: center frequency and
Q (resonance). The gain parameter is set to unity gain (1.0).
allpass center-frequency [float] In left inlet: The word allpass sets the filter type to allpass mode. The frequency
Q [float] response of the filter is based on two parameters: center/cutoff frequency and Q
(resonance). The gain parameter is set to unity gain (1.0). An allpass filter is
designed to modify the phase response, leaving a flat amplitude response
highpass center-frequency [float] In left inlet: The word highpass sets the filter type to highpass mode. The
Q [float] frequency response of the filter is based on two parameters: cf (cutoff frequency)
and Q (resonance). The gain parameter is set to unity gain (1.0).
highshelf center-frequency [float] In left inlet: The word highshelf sets the filter type to highshelf mode. The
initial-gain [float] frequency response of the filter is based on three parameters: cutoff frequency,
Q [float] gain, and S (slope).
gainbpass center-frequency [float] In left inlet: The word gainbpass sets the filter type to bandpass mode with user-
initial-gain [float] controllable gain. The frequency response of the filter is based on three
Q [float] parameters: center frequency, gain, and Q (resonance).
gainbstop center-frequency [float] In left inlet: The word gainbstop sets the filter type to bandstop mode with user-
initial-gain [float] controllable gain. The frequency response of the filter is based on three
Q [float] parameters: center frequency, gain, and Q (resonance).
gainapass center-frequency [float] In left inlet: The word gainapass sets the filter type to allpass mode with user-
initial-gain [float] controllable gain. The frequency response of the filter is based on three
Q [float] parameters: center/cutoff frequency, gain, and Q (resonance), although only the
gain parameter has an effect on the amplitude response. An allpass filter is
designed to modify the phase response, leaving a flat amplitude response
gainhpass center-frequency [float] In left inlet: The word gainhpass sets the filter type to highpass mode with user-
initial-gain [float] controllable gain. The frequency response of the filter is based on three
Q [float] parameters: cf (cutoff frequency) gain, and Q (resonance).
gainlpass center-frequency [float] In left inlet: The word gainlpass sets the filter type to lowpass mode with user-
initial-gain [float] controllable gain. The frequency response of the filter is based on three
Q [float] parameters: cf (cutoff frequency) gain, and Q (resonance).
gainresonant center-frequency [float] In left inlet: The word gainrtesonant sets the filter type to resonant mode
initial-gain [float] (resonant bandpass filter) with user-controllable gain. The frequency response of
Q [float] the filter is based on three parameters: center frequency, gain, and Q (resonance).
lowpass center-frequency [float] In left inlet: The word lowpass sets the filter type to lowpass mode. The frequency
Q [float] response of the filter is based on two parameters: cf (cutoff frequency) and Q
(resonance). The gain parameter is set to unity gain (1.0).
lowshelf center-frequency [float] In left inlet: The word lowshelf sets the filter type to lowshelf mode. The
initial-gain [float] frequency response of the filter is based on three parameters: cutoff frequency,
Q [float] gain, and S (slope).
peaknotch center-frequency [float] In left inlet: The word peaknotch sets the filter type to peaknotch mode. The
initial-gain [float] frequency response of the filter is based on three parameters: center/cutoff
Q [float] frequency, gain, and Q (resonance).
off filter-type [list] In left inlet: The word off sets the filter type to off mode whereby the dry,
unfiltered signal is passed to the outputs.
resamp resampling-factor [int] Set the resampling factor
resonant center-frequency [float] In left inlet: The word resonant sets the filter type to resonant mode (resonant
Q [float] bandpass filter). The frequency response of the filter is based on two parameters:
center frequency and Q (resonance). The gain parameter is set to unity gain (1.0).
signal In 1st inlet: Sets the center or cutoff frequency parameter for the filter and causes
output.

In 2nd inlet: Sets the gain parameter for the filter and causes output.

In 3rd inlet: Sets the Q (resonance) or S (slope) parameter for the filter and causes
output. (note that the term slope is only used for the third parameter of shelving
filters, and is roughly equivalent to resonance)

Information for box attributes common to all objects

Output
signal: The five signal outlets output signal-rate filter coefficients for the biquad~ object.

Examples
The filtercoeff~ object lets you send sample-accurate coefficients to biquad~

See Also
Name Description
allpass~ Apply an allpass filter effect
biquad~ Two-pole, two-zero filter
cascade~ Cascaded series of biquad filters
delay~ Delay a signal
filtergraph~ Edit a filter interactively
lores~ Resonant lowpass filter
reson~ Resonant bandpass filter
teeth~ Comb filter with feedforward and feedback delay control
Audio Filtering Audio Filtering
filterdesign
Create a filter specification

Description
Use the filterdesign object to create a dictionary containing a specification for a filter that can be realized by several other
objects including the cascade~ object.

Arguments
None.

Messages
bang Sending a bang will generate the filterdesign dictionary using current attributes
and send it out the first outlet.
(mouse) TEXT_HERE

Attributes
Name Type g/s Description
frequency float Filter cutoff frequencies specified in units defined by the units attribute. For
lowpass and highpass filters a single frequency will be used to define the cutoff.
For bandpass and bandstop filters two frequencies are required.
name symbol Dictionary Name
order int The order of the filter, which is to say the number of poles and zeroes. For
reference, the biquad~ object is a second-order filter (2 poles and 2 zeroes).
passband_ripple float Magnitude ripple in the passband for Chebyshev Type 1 filters in decibels. Higher
amounts of ripple will provide a narrower transition band given a constant order
for the filter.
response symbol Response
'lowpass' = Low frequencies pass through, high frequencies are attenuated
'highpass' = High frequencies pass through, low frequencies are attenuated
'bandpass' = A band of frequencies pass through, low and high frequencies are
attenuated
'bandstop' = A band of frequencies are attenuated, low and high frequencies pass
through
samplerate int Samplerate used when unit attribute is set to hertz. If the samplerate is set to zero
then MSP's samplerate will be used.
sos_output int Inclusion of coefficients for second-order-sections in the output dictionary. This is
the native format used by cascade~, zplane~, and filtergraph~.
stopband_attenuation float Minimum attenuation in Chebyshev Type 2 filter stopband in decibels. For given
order of filter, greater attenuation results in a wider transition band and less
attenuation in the stopband results in a narrower transition band.
tf_output int Include single-section transfer function coefficients in the output dictionary. This
representation works well for low-ordered filters but quickly becomes subject to
floating-point precision roundoff as the order of the filter increases.
topology symbol The organization of the zeroes and poles used to realize the filter.
'butterworth' = Gentle transition, flat passband, monotonically decreasing
stopband
'chebyshev-1' = Steepest transition, definable ripple in passband, monotonically
decreasing stopband
'chebyshev-2' = Moderate transition, flat passband, definable ripple in the
stopband
units symbol Frequency Units
'hertz' = Cycles per second, based on the samplerate attribute
'normalized' = Range from 0.0 to 1.0; 1.0 is the nyquist frequency
'radians' = Range from 0.0 to pi; pi is the nyquist frequency
zpk_output int Include zeroes-poles-gain representation in the output dictionary. Zeroes-poles-
gain (ZPK) provides a more accurate representation of the filter's response than
the single-section transfer function (see tf_output attribute) for higher-order
filters. If calculating coefficients for second-order-sections (see sos_output
attribute) the ZPK representation is calculated as an intermediary stage.

Information for box attributes common to all objects

Output
dictionary: A filterdesign dictionary containing the specified filter characteristics.

Examples

See Also
Name Description
filterdetail Detail the characteristics of a filter
plot~ Visualize sets of data on a two-dimensional graph
cascade~ Cascaded series of biquad filters
Audio Filtering Audio Filtering
filterdetail
Detail the characteristics of a filter

Description
Use the filterdetail object to produce details from a filter specification provided as input. The filter specification may be generated
by the filterdesign object, or by other means. The output includes the impulse response, step response, magnitude and phase
responses, as well as phase and group delay.

Arguments
None.

Messages
list a0 [float] Specify a biquad filter using a list of five filter coefficients
a1 [float]
a2 [float]
b1 [float]
b2 [float]
dictionary dictionary-name [symbol] A filterdesign dictionary specifying a filter in terms of its zeroes, poles, and gain or
as a transfer function. The transfer function is expressed as a fraction with the FIR
coefficients composing the numerator and the IIR coefficients composing the
denominator. The zero-pole-gain representation is preferred because it yields a
more numerically accurate result.

Attributes
Name Type g/s Description
numpoints int The resolution of the returned filter characteristics. You may reduce this to reduce
the computational intensity of performing the detailing calculations, or increase it
to gain greater resolution. By default, a resolution of 512 points is used.

Information for box attributes common to all objects

Output
list:
leftmost outlet -- magnitude response
second outlet -- phase response
third outlet -- phase delay
fourth outlet -- group delay
fifth outlet -- impulse response
rightmost outlet -- step response

Examples

See Also
Name Description
filterdesign Create a filter specification
plot~ Visualize sets of data on a two-dimensional graph
cascade~ Cascaded series of biquad filters
biquad~ Two-pole, two-zero filter
Audio Filtering Audio Filtering
filtergraph~
Edit a filter interactively

Description
Use the filtergraph~ object to generate filter coefficients for the biquad~ or cascade~ objects with a graphical interface.

Arguments
None.

Messages
bang In left inlet: In display mode, bang causes the filtergraph~ object to send its
internally-stored biquad coefficients out the leftmost outlet. In the interactive filter
modes, bang additionally causes the current filter parameters to be sent out their
respective outlets (see Output).
int filter-parameter [int] All int values are converted to float.

In 1st-5th inlets: When in display mode, a float in one of the first five inlets
changes the current value of the corresponding biquad~ filter coefficient (a0, a1,
a2, b1, and b2, respectively), recalculates the filter's frequency response based on
these coefficients and causes a list of the current filter coefficients to be output
from the leftmost outlet.

In 6th inlet: Sets the center or cutoff frequency parameter for the filter and causes
output.

In 7th inlet: Sets the gain parameter for the filter and causes output.

In 8th inlet: Sets the Q (resonance) or S (slope) parameter for the filter and causes
output.

Note: Input to any one of the inlets will recalculate the current filter's graph and
trigger the output.
float filter-parameter [float] In 1st-5th inlets: When in display mode, a float in one of the first five inlets
changes the current value of the corresponding biquad~ filter coefficient (a0, a1,
a2, b1, and b2, respectively), recalculates the filter's frequency response based on
these coefficients and causes a list of the current filter coefficients to be output
from the leftmost outlet.

In 6th inlet: Sets the center or cutoff frequency parameter for the filter and causes
output.

In 7th inlet: Sets the gain parameter for the filter and causes output.

In 8th inlet: Sets the Q (resonance) or S (slope) parameter for the filter and causes
output.

Note: Input to any one of the inlets will recalculate the current filter's graph and
trigger the output.
list a0 [float] In left inlet: A list of five float values which correspond to biquad~ filter
a1 [float] coefficients sets the filtergraph~ object's internal values for these coefficients and
a2 [float] causes the object to output the list out its left outlet. If filtergraph~ is in display
b1 [float] mode, it will display the frequency response of the filter obtained from these
b2 [float] coefficients. If more than five values are sent, they are interpreted as sets of
cascaded biquad coefficients (see the cascade message).

in 6th inlet: A list of three values which correspond to center/cutoff frequency,


gain and Q/S (resonance/slope), sets these values, recalculates the new filter
coefficients and causes output. This is equivalent to the params message.
anything messages [list] Allows for backwards compatibility with these obsolete messages: gainlpass,
gainhpass, gainbpass, gainbstop, rgbcolor, freq, gain, Q, fconstrain,
aconstrain, qconstrain, lin, log, log2, scale, amp, phase, and spectrum.
bandpass center-frequency [float] In left inlet: The word bandpass sets the filter type of the filtergraph~ object to
bandpass mode. It is equivalent to the mode 3 message. The frequency response
gain [float] of the filter is based on three parameters: cf (center frequency) gain, and Q
Q [float] (resonance).
bandstop cutoff-frequency [float] In left inlet: The word bandstop sets the filter type of the filtergraph~ object to
gain [float] bandstop mode. It is equivalent to the mode 4 message. The frequency response
Q [float] of the filter is based on three parameters: cf (center frequency) gain, and Q
(resonance).
allpass center-frequency [float] In left inlet: The word allpass sets the filter type of the filtergraph~ object to
allpass mode.It is equivalent to the mode 9 message. The frequency response of
gain [float] the filter is based on three parameters: cf (center frequency, or cutoff frequency)
Q [float] gain, and Q (resonance), although only the gain parameter has an effect on the
amplitude response. An allpass filter is designed to modify the phase response
(use the phasespect 1 message to view the phase response).
analog analog-filter-prototype In left inlet: The word analog, followed by a 0 or 1, toggles the analog filter
[list] prototype parameter for the bandpass, and peaknotch filters. Unlike the standard
digital versions, these "imitation analog" filters do not have a notch at the nyquist
frequency, and thus imitate the response of a analog filter. The imitation analog
filters are slightly more computationally expensive, so this option is set to 0
(disabled) by default.
dictionary dictionary-name The word dictionary, followed by a symbol that references a named filterdesign
[symbol] object dictionary, will cause the filtergraph~ object to use the dictionary values for
filter coefficients.
display filter-type [list] In left inlet: The word display sets the filter type of the filtergraph~ object to
display only. It is equivalent to the mode 0 message. In display mode,
filtergraph~ simply displays the frequency response for a set of five biquad~ filter
coefficients.
displaydot mousable-bandwidth- In left inlet: The displaydot message, followed by a 0 or 1, toggles the display of
display [list] the mousable bandwidth region when filtergraph~ is in display mode. This allows
you to use filtergraph~ as an interface to design and display your own filter
algorithms. The default is disabled (by default, display mode functions uniquely as
a display).
cascade filter-coefficient-list In left inlet: The cascade message works in display mode only. The word cascade,
[list] followed by up to 24 groups of five float values corresponding to filter coefficients,
will display a composite filter response which shows the multiplication of a group
of biquad filters in cascade.
constraints filter-index [int] In left inlet: The word constraints, followed by seven numbers, allows you to
minimum-frequency constrain the frequency, amplitude and Q values within the specified ranges. This
[float] is useful to constrain values obtained by clicking and dragging. The first number
maximum-frequency should be an integer, and it specified the filter number whose constraints will be
[float] set. The remaining six numbers are floating-point values which set the minimum
minimum-gain [float] and maximum frequency values, the minimum and maximum amplitude values,
maximum-gain [float] and the minimum and maximum Q values, respectively. Specifying constraint
minimum-Q [float] values of zero will remove the constraints for that value. The constrints message
maximum-Q [float] causes the filter coefficients to be output.
flat filter-indices [list] The word flat, followed by a list that specifies the indices of filters in a multifilter
array, will set the designated filters to flat response (i.e. no resonance for filtering)
The changes made to the filters vary depending on filter type:

Lowpass and highpass filters: Q values set to 0.707, and gain coefficients are set to
1. (0dB)
Band pass and band stop filters are ignored.

All other filter types: The gain coefficients are set to 1. (0dB)
highpass cutoff-frequency [float] In left inlet: The word highpass sets the filter type of the filtergraph~ object to
gain [float] highpass mode.It is equivalent to the mode 2 message. The frequency response of
Q [float] the filter is based on three parameters: cf (cutoff frequency) gain, and Q
(resonance) or S (slope - used for the shelving filters).
highorder a/b-grouped-filter- The highorder message works in display mode only. The word highorder,
coefficients [list] followed by a list of n groups of biquad filter "a" coefficients and n-1 groups of
biquad filter "b" coefficients, will display the response of an nth order filter.
highshelf cutoff-frequency [float] In left inlet: The word highshelf sets the filter type of the filtergraph~ object to
gain [float] highshelf mode.It is equivalent to the mode 7 message. The frequency response of
slope [float] the filter is based on three parameters: cf (cutoff frequency) gain, and S (slope).
gainmode gain-parameter [list] In left inlet: The word gainmode, followed by a 0 or 1, toggles the gain parameter
for the lowpass, highpass, bandpass, and bandstop filters. The traditional
definitions of these filters have a fixed gain of 1.0, but by gain-enabling them, their
amplitude response can be scaled without the additional use of a signal multiply at
the filters output.The default is 0 (disabled).
markers frequency-value- In left inlet: The word markers, followed by a list of up to 64 frequency values will
markers [list] place visual markers (vertical lines) at these frequencies behind the graph. The
markers message will set the markers used for both linear and logarithmic
frequency displays.
mode filter-type [int] In left inlet: The word mode, followed by a number from 0-9, sets the current
filter type. The numbers and associated filter types are.

Number - Filter type

0 - display only
1 - lowpass
2 - highpass
3 - bandpass
4 - bandstop
5 - peaknotch
6 - lowshelf
7 - highshelf
8 - resonant
9 - allpass

In display mode, filtergraph~ displays the frequency response for a set of five
biquad~ filter coefficients. In the other modes, it graphs the frequency response of
a filter based on three parameters: cf (center frequency, or cutoff frequency) gain,
and Q (resonance) or S (slope - used for the shelving filters).
(mouse) You can change the filter parameters by clicking and dragging on the filtergraph~
object's display. By default, horizontal mouse dragging is mapped to cutoff
frequency, and vertical mouse movement is mapped to gain (if gainmode is
enabled). If the cursor is located directly over the edge of a filter band, however,
the band rectangle is highlighted, indicating that clicking and dragging will map x-
axis movement to adjust filter bandwidth instead of cutoff frequency. .
If multiple bandwidth regions are overlapping, you can cycle through them by
double-clicking on the topmost one. This is useful for accessing smaller bandwidth
regions that might be otherwise "covered" by a larger region.
mousemode x-response-flag [int] In left inlet: The word mousemode followed by two int arguments, specifies the
y-response-flag [int] interpretation of horizontal and vertical mouse movement. With one argument,
only the horizontal mouse mode is affected. The mouse mode values are the same
for both axes: (0 = off, 1 = normal, 2 = alternate).
For horizontal movement (specified by the first argument), normal behavior
means that clicking on the filter band and dragging horizontally changes the
filter's cutoff frequency. When set to the alternate mouse mode (2), horizontal
movement affects Q, or resonance. When turned off (0), mouse activity along the
x-axis has no effect.

For vertical movement (specified by the second argument), normal behavior


means that the y-axis is mapped to gain during clicking and dragging activity.
When the alternate mouse mode (2) is selected, vertical movement changes the Q
(resonance) setting instead. When turned off (0), vertical mouse movement has no
effect.
lowpass cutoff-frequency [float] In left inlet: The word lowpass sets the filter type of the filtergraph~ object to
gain [float] lowpass mode.It is equivalent to the mode 1 message. The frequency response of
Q [float] the filter is based on three parameters: cf (center frequency, or cutoff frequency)
gain, and Q (resonance).
lowshelf center-frequency [float] In left inlet: The word lowshelf sets the filter type of the filtergraph~ object to
lowshelf mode.It is equivalent to the mode 6 message. The frequency response of
gain [float] the filter is based on three parameters: cf (center frequency, or cutoff frequency)
slope [float] gain, and S (slope).
peaknotch center-frequency [float] In left inlet: The word peaknotch sets the filter type of the filtergraph~ object to
peaknotch mode.It is equivalent to the mode 5 message. The frequency response
gain [float] of the filter is based on three parameters: cf (center frequency, or cutoff frequency)
Q [float] gain, and Q (resonance).
options filter-number [int] In left inlet: The word options, followed by five integers, allows you to set the
filter-mode [int] filter-specific options for a given filter. The first number specifies the filter whose
gain-enable-flag [int] options will be set. The remaining four integers set the filter mode (mode
analog-filter- message) gain-enabling flag (gainmode message), analog filter prototype flag
prototype-flag [int] (analog message) and interactive filter mode flag (displaydot message),
interactive-filter- respectively. The options message causes the filter coefficients to be re-evaluated
mode-flag [int] and output.
params filter-index [int] In left inlet: The word params, when followed by three numbers specifying
frequency [float] frequency, gain and Q, sets the filter parameters for the currently selected filter
gain [float] and triggers output. When followed by four numbers specifying filter number,
Q [float] frequency, gain and Q, this messages sets the filter parameters for the filter
indicated and causes output.
query frequency [float] In left inlet: The word query, followed by a float value, will cause the amplitude
and phase response of the graph at that frequency to be sent out the sixth outlet of
the filtergraph~ object as a list.
selectfilt filter-index [int] Selects a specific filter as the one actively being edited and highlighted in the
display.
set a0/center frequency In left inlet: The word set, followed by a list of five int values which correspond to
[float] biquad~ filter coefficients, sets the filtergraph~ object's internal values for these
a1/gain [float] coefficients but does not cause output. If filtergraph~ is in display mode, it will
a2/Q [float] display the frequency response of the filter obtained from these coefficients.
b1 [float]
b2 [float] in 6th inlet: A list of three values which correspond respectively to center/cutoff
frequency, gain and Q/S (resonance/slope), sets these values, recalculates the new
filter coefficients but does not cause output. In display mode this message has no
effect.
resonant center-frequency [float] In left inlet: The word resonant sets the filter type of the filtergraph~ object to
resonant mode (resonant bandpass filter). It is equivalent to the mode 8 message.
gain [float] The frequency response of the filter is based on three parameters: cf (center
Q [float] frequency) gain, and Q (resonance).
setconstraints filter-index [int] In left inlet: The word setconstraints, followed by seven numbers, allows you to
minimum-frequency set the frequency, amplitude and Q constraint values within the specified ranges
[float] without causing output. This is useful to constrain values obtained by clicking and
maximum-frequency dragging. The first number should be an integer, and it specified the filter number
[float] whose constraints will be set. The remaining six numbers are floating-point values
minimum-gain [float] which set the minimum frequency, maximum frequency, minimum amplitude,
maximum-gain [float] maximum amplitude, minimum Q and maximum Q, respectively. Specifying
minimum-Q [float] constraint values of zero will remove the constraints for that value.
maximum-Q [float]
setfilter filter number [list] In left inlet: The word setfilter, followed by a number, specifies the filter, by
number, which is the currently selected filter in a multiple filter array. Filters are
numbered from 0.
setoptions filter-number [int] In left inlet: The word setoptions, followed by five integers, allows you to set the
filter-mode [int] filter-specific options for a given filter without triggering output. The first number
gain-enable-flag [int] specifies the filter whose options will be set (filters are numbered from 0). The
analog-filter- remaining four integers set the filter mode (mode message) gain-enabling flag
prototype-flag [int] (gainmode message), analog filter prototype flag (analog message) and
interactive-filter- interactive filter mode flag (displaydot message), respectively.
mode-flag [int]
setparams filter-index [int] In left inlet: The word setparams, when followed by three numbers specifying
frequency [float] frequency, gain and Q, sets the filter parameters for the currently selected filter
gain [float] without triggering output. When followed by four numbers specifying filter
Q [float] number, frequency, gain and Q, this messages sets the filter parameters for the
filter indicated, without triggering output.
whichfilt filter-index [int] Selects a specific filter as the one actively being edited (without highlighting it in
the display).

Attributes
Name Type g/s Description
autoout int Output Coefficients on Load
def.:0
bgcolor float Background Color
bordercolor float Border Color
bwidthcolor float Band Color
curvecolor float Curve Color
dbdisplay int DeciBel Display
def.:1
display_flat int Display Flat Sign
def.:1
domain float Frequency Display Range
def.:20. 20000.
edit_Q float Q or S
edit_amp float Amplitude
edit_analog int Toggles the analog filter prototype parameter for the currently selected filter when
filtergraph~ is in bandpass or peaknotch mode. For more information on analog
filter mode, see the analog message listing above.

For single filters, the filter type displayed by the filtergraph~ object is the
currently selected filter; when dealing with multiple filters, the currently selected
filter is set using the edit_filter message (with the filters being numbered from 0).
edit_displaydot int Toggles the display of the mousable bandwidth region for the currently selected
filter when filtergraph~ is in display mode. For more information, see the
displaydot message listing above.

For single filters, the filter type displayed by the filtergraph~ object is the
currently selected filter; when dealing with multiple filters, the currently selected
filter is set using the edit_filter message (with the filters being numbered from 0).
edit_filter int Selects which filter to edit if nfilters is greater than 1. Filters are numbered from
def.:0 0.
'0' = TEXT_HERE
edit_freq float Frequency
edit_gainmode int Gain-Enabled
edit_maxQ atom Constrains Maximum Q
edit_maxamp atom Constrains Maximum Amplitude
edit_maxfreq atom Constrains Maximum Frequency
edit_minQ atom Constrains Minimum Q
edit_minamp atom Constrains Minimum Amplitude
edit_minfreq atom Constrains Minimum Frequency
edit_mode int Filter Type
'display' = None/arbitrary
'lowpass' = Low frequencies pass, high frequencies attenuated
'highpass' = High frequencies pass, low frequencies attenuated
'bandpass' = A band of frequencies pass, everything else is attenuated
'bandstop' = A band of frequencies are attenuated, everything else passes
'peaknotch' = A band of frequencies is attenuated or boosted depending on the
gain
'lowshelf' = Low frequencies are attenuated or boosted depending on the gain
'highshelf' = High frequencies are attenuated or boosted depending on the gain
'resonant' = Another bandpass filter
'allpass' = All frequencies pass through but the phase is affected
fgcolor float Foreground Color
fullspect int Display the full frequency spectrum from -Nyquist to +Nyquist.
def.:0
hbwidthcolor float Selection Color
hcurvecolor float Highlight Color
hfgcolor float Highlight Foreground Color
linmarkers float Marker positions for the linear frequency display. By default, the markers are set
def.:5512.5 11025. at SampleRate/4, SampleRate/2, and (3 * SampleRate)/4.
16537.5
logamp int Amplitude Display
def.:1 'Linear' = Linear amplitude display
'Logarithmic' = Log amplitude display
logfreq int Frequency Display
def.:1 'Linear' = Linear frequency display
'Logarithmic' = Log frequency display
logmarkers float Marker positions for the log frequency display. By default, the markers are set at
def.:10. 100. 1000. 50Hz, 500Hz and 5kHz at 44.1kHz. These values correspond to 0.007124,
10000. 0.071238, and 0.712379 radians for any sample rate.
markercolor float Grid Lines Color
nfilters int Number of cascaded biquad filters displayed. The range is between 1 and 24. When
def.:1 using more than one filter, the output of the filtergraph~ should be sent to a
cascade~ object instead of a biquad~.
numdisplay int Numerical Display
def.:1
parameter_enable int Parameter Mode Enable
phasespect int Display Phase Spectrum
def.:0
range float DeciBel Range
def.:0.0625 16.
textcolor float Text Color

Information about attributes available for Parameter-aware objects


Information for box attributes common to all objects

Menu Items
Name Description
Color Choosing the Color... menu item from the Object menu when the object is
selected opens a color picker, permitting adjustment to the appearance of the
filtergraph~ object.

Output
float: Out second through fifth outlets: Frequency, Gain (linear), Resonance (Q) and Bandwidth output in response to clicks on
the filtergraph~ object.
int: Out rightmost (seventh) outlet: Filter number. Indicates which of the cascaded biquad filters is being highlighted and/or
edited.
list: Out leftmost outlet: a list of 5 floating-point filter coefficients for the biquad~ object. Coefficients output in response to
mouse clicks and changes in the coefficient or filter parameter inlets. They are also output when the audio is turned on, and
optionally when the patch is loaded if the automatic output option is turned on (see autoout message, above).

Out sixth outlet: a list of 2 floating-point values (amplitude, phase) output in response to the query message (see above).

Examples

The filtergraph~ object greatly simplifies working with the biquad~ object

See Also
Name Description
allpass~ Apply an allpass filter effect
biquad~ Two-pole, two-zero filter
cascade~ Cascaded series of biquad filters
delay~ Delay a signal
filtercoeff~ Signal-rate filter coefficient generator
lores~ Resonant lowpass filter
reson~ Resonant bandpass filter
teeth~ Comb filter with feedforward and feedback delay control
zplane~ Graph filter poles and zeros on the Z-plane
Audio Filtering Audio Filtering
frameaccum~
Compute "running phase" of successive phase deviation frames

Description
frameaccum~ computes a running phase by keeping a sum of the values in each position of its incoming signal vectors. When
used inside a pfft~ object, it can keep a running phase of the FFT because the FFT size is equal to the signal vector size.

Arguments
Name Units Type Opt Description
phasewrap-flag (0 or int opt A non-zero integer argument will cause the accumulated values to be wrapped
nonzero) between - and . This optional feature is to reduce roundoff error when using
frameaccum~ to accumulate phase values. When the argument is set to one.
frameaccum~ object performs a phase warping (like the phasewrap~ object). It
is more efficient to use the non-zero argument than to use a combination of
frameaccum~ and phasewrap~ objects.

Messages
signal The input to be accumulated.

Information for box attributes common to all objects

Output
signal: For each signal vector, the first sample of its output will be the sum of all of the first samples in each signal vector it has
received, the second sample of its output will be the sum of all the second samples in each signal vector, and so on.

Examples

frameaccum~ computes the running phase between frames of spectral data

See Also
Name Description
framedelta~ Compute phase deviation between successive FFT frames
MSP Tutorial 26: Frequency MSP Tutorial 26: Frequency Domain Signal Processing with pfft~
Domain Signal Processing with
pfft~
frameaverage~
Perform a piece-wise running averaging of consecutive frames of audio.

Description
The frameaverage~ object performs a piece-wise running averaging of consecutive frames of audio. Where the framesmooth~
object can be seen as smoothing in the frequency domain (when using FFT as input), the frameaverage~ object can be seen as
performing temporal smoothing, more analogous to the vectral~ object.

Arguments
None.

Messages
signal Frames of audio samples on which to perform running average calculations.

Attributes
Name Type g/s Description
framecount int The number of frames across which to average samples of the same index. Limited
to between 1 and the 'maxframecount' argument given at object instantiation.
framesize int The number of samples per frame. If working with FFT output, this should be set
to the size of the FFT.

Information for box attributes common to all objects

Output
signal: frame-wise averaged audio signal.

Examples

See Also
Name Description
average~ Multi-mode signal average
fft~ Fast Fourier transform
framesmooth~ Perform averaging of consecutive samples, grouped into frames, without blurring across
the frames.
plot~ Visualize sets of data on a two-dimensional graph
vectral~ Vector-based envelope follower
framedelta~
Compute phase deviation between successive FFT frames

Description
framedelta~ computes a running phase deviation by subtracting values in each position of its previously received signal vector
from the current signal vector. When used inside a pfft~ object, it keeps a running phase deviation of the FFT because the FFT
size is equal to the signal vector size.

Arguments
None.

Messages
signal The input on which the deviation will be computed.

Information for box attributes common to all objects

Output
signal: For each signal vector, the first sample of its output will be the first sample in the current signal vector minus the first
sample in the previous signal vector, the second sample of its output will be the second sample in the current signal vector minus
the second sample in the previous signal vector, and so on.

Examples

framedelta~ computes the difference between successive frames of FFT data

See Also
Name Description
frameaccum~ Compute "running phase" of successive phase deviation frames
MSP Tutorial 26: Frequency MSP Tutorial 26: Frequency Domain Signal Processing with pfft~
Domain Signal Processing with
pfft~
framesmooth~
Perform averaging of consecutive samples, grouped into frames, without blurring across the frames.

Description
The framesmooth~ object performs averaging of consecutive samples, grouped into frames, without blurring across the frames.

Arguments
None.

Messages
signal Sets the number of audio samples to be smoothed.

Attributes
Name Type g/s Description
framesize int The number of samples per frame. If working with FFT output, this should be set
to the size of the FFT.
smoothness int The number of samples to be averaged to produce the smoothed output.

Information for box attributes common to all objects

Output
signal: Output samples with smoothing applied

Examples

See Also
Name Description
fft~ Fast Fourier transform
frameaverage~ Perform a piece-wise running averaging of consecutive frames of audio.
plot~ Visualize sets of data on a two-dimensional graph
vectral~ Vector-based envelope follower
freqshift~
Time-domain frequency shifter

Description
freqshift~ is a time-domain frequency shifter (also known as a single-sideband ring modulator).

Arguments
Name Units Type Opt Description
frequency-shift hz float opt A numerical argument will be used as the frequency shift in Hertz. The default is
zero.
frequency-shift hz int A numerical argument will be used as the frequency shift in Hertz. The default is
zero. .

Messages
int frequency-shift [int] In right inlet: Converted to float. A number value in the right inlet will be used as
a frequency amount in Hertz by which the left input signal will be shifted.
float frequency-shift [float] In right inlet: a float in the right inlet will be used as a frequency amount in Hertz
by which the left input signal will be shifted.
clear Clears sample memory (in case the filter is blown up).
signal In left inlet: The signal present at the left inlet is frequency-shifted by the
argument or value given in the right inlet.

In right inlet: a signal in the right inlet will be used as a frequency amount in Hertz
by which the left input signal will be shifted.

Information for box attributes common to all objects

Output
signal: The output is the frequency shifted signal.

Examples
freqshift~ shifts the frequencies of an incoming sound more efficiently than if you build it yourself from scratch

See Also
Name Description
fbinshift~ Frequency domain frequency shifter for pfft~
gizmo~ Frequency-domain pitch shifter for pfft~
hilbert~ Phase quadrature filter
ftom~
Convert frequency to MIDI note numbers at signal-rate

Description
ftom~ performs signal-rate frequency (Hz) to MIDI(note-value) conversion.

Arguments
None.

Messages
signal A signal representing a frequency value. It is converted to a MIDI pitch value (from
0 to 127) and output as a signal.

Attributes
Name Type g/s Description
base float Sets the "base frequency" used when converting frequency values (e.g., A = 440.).
The default is 440.

Information for box attributes common to all objects

Output
signal: The MIDI note value that corresponds to the input frequency is output as a signal. When an input frequency falls between
two equal tempered pitches, the fractional part of the MIDI value is included.

Examples

What

See Also
Name Description
expr Evaluate a mathematical expression
ftom Convert frequency to a MIDI note number
mtof Convert a MIDI note number to frequency
mtof~ Convert a MIDI note number to frequency at signal rate
fzero~
Fundamental frequency estimator

Description
The fzero~ object estimates the fundamental frequency of an an incoming, monophonic audio signal. It performs multiple layers
of wavelet transforms on an incoming vector, comparing the spacing between the peaks in each.

Arguments
None.

Messages
signal audio signal to be analyzed.

Attributes
Name Type g/s Description
freqmax int The maximum frequency, in Hertz, that the object will report.
freqmin int The minimum frequency, in Hertz, that the object will report.
onsetamp float fzero~ gives a bang or list out the right outlet when a new event crosses this
amplitude threshold.
onsetlist int Onset detector output: bang or list(pitch, amplitude)
onsetperiod int This attribute sets the minimum number of samples between reporting any offsets.

'16' = TEXT_HERE
'32' = TEXT_HERE
'64' = TEXT_HERE
'128' = TEXT_HERE
'256' = TEXT_HERE
'512' = TEXT_HERE
'1024' = TEXT_HERE
'2048' = TEXT_HERE
'4096' = TEXT_HERE
onsetpitch float fzero~ gives a bang or list out the right outlet when the frequency changes by this
amount, in in MIDI notes.
period int Sets the time period between analyses in samples.
'16' = TEXT_HERE
'32' = TEXT_HERE
'64' = TEXT_HERE
'128' = TEXT_HERE
'256' = TEXT_HERE
'512' = TEXT_HERE
'1024' = TEXT_HERE
'2048' = TEXT_HERE
'4096' = TEXT_HERE
size int Sets the buffer size to specify how many samples are analyzed each time.
'128' = TEXT_HERE
'256' = TEXT_HERE
'512' = TEXT_HERE
'1024' = TEXT_HERE
'2048' = TEXT_HERE
'4096' = TEXT_HERE
threshold float If the peak amplitude of the buffer is below this threshold, then fzero~ will report
nothing.
Information for box attributes common to all objects

Output
bang: Out right outlet: New note onset detected.
float: Out left outlet: Estimated fundamental frequency in Hertz.

Out middle outlet: Peak amplitude of the analysis buffer at the time of the last analysis.

Examples

detecting a d

See Also
Name Description
ftom Convert frequency to a MIDI note number
mtof Convert a MIDI note number to frequency
peakamp~ Report the maximum amplitude of a signal
thresh~ Detect signal above a set level
gain~
Exponential scaling volume slider

Description
gain~ is a slider that scales signals. It can also make a smooth transition as you move from one value of the slider to the next.

Arguments
None.

Messages
bang Sends current slider value out right outlet.
int slider-value [int] In left inlet: Sets the value of the slider, ramps the output signal to the level
corresponding to the new value over the specified ramp time, and outputs the
slider's value out the right outlet.
float slider-value [float] In left inlet: Converted to int. Sets the value of the slider, ramps the output signal
to the level corresponding to the new value over the specified ramp time, and
outputs the slider's value out the right outlet.
(inlet1) ramp-time [float] In right inlet: Sets the ramp time in milliseconds. The default is 10 milliseconds.
list slider-value [list] The object takes list messages in conjunction with pattr objects.
(mouse) Clicking and dragging with the mouse sets the value of the slider, ramps the
output signal to the level corresponding to the new value over the specified ramp
time, and outputs the sliders value out the right outlet.
set set-slider-value [int] In left inlet: The word set, followed by a number, sets the value of the slider,
ramps the output signal to the level corresponding to the new value over the
specified ramp time, but does not output the slider's value out the right outlet.
signal In left inlet: The input signal to be scaled by the slider.

Attributes
Name Type g/s Description
bgcolor float Sets the first interior color (background) of the slider in RGBA format.
bordercolor float Sets the border color of the slider in RGBA format.
inc float Sets the increment value used to calculate the output scale factor based on the
def.:1.071519 input value. The default value is 1.071519.
interp float Sets the interpolation ramp time in milliseconds for the gain~ object. The default
def.:10. is 10.
knobcolor float Sets the knob color of the gain~ object in RGBA format.
orientation int Sets the gain~ object to a horizontal or vertical data display.
def.:0 Automatic: (the default) sets the display dependent on the size of the slider -
longest side of the rectangle that describes the slider sets the orientation.
Horizontal
Vertical
'Automatic' = TEXT_HERE
'Horizontal' = TEXT_HERE
'Vertical' = TEXT_HERE
parameter_enable int Parameter mode enable or disable
relative int Sets way that the gain~ object responds to mouse clicks.
def.:0 'Absolute' = Absolute mode
'Relative' = Relative mode
scale float Sets the base output value used to calculate the output scale factor based on the
def.:7.94321 input value. The default value is 7.94231. See the "Inspector" section for an
explanation of the calculation. The word size, followed by a number, sets the
range of gain~ to the number. The values of the slider will then be 0 to the range
value minus 1. The default value is 158.
size int Sets the number of steps (range) of the gain~ object. The default value is 158.
def.:158
stripecolor float Sets the second interior color (stripe) of the slider in RGBA format.

Information about attributes available for Parameter-aware objects

Information for box attributes common to all objects

Menu Items
Name Description
Color Choosing the Color... menu item from the Object menu when the object is
selected opens a color picker, permitting adjustment to the appearance of the
gain~ object.

Output
int: Out right outlet: The current slider value, when dragging on the slider with the mouse or when gain~ receives an int or float
in its left inlet.
signal: Out left outlet: The input signal, scaled by the current slider value as x in the equation shown above.

Examples

Specialized fader to scale a signal exponentially or logarithmically

See Also
Name Description
linedrive Scale numbers exponentially
MSP Tutorial 31: Comb Filter MSP Tutorial 31: Comb Filter
gate~
Route a signal to one of several outlets

Description
Use gate~ to route an input signal at the second inlet to one of several outlets, or to no outlet at all. When there is only one outlet
(the default case), it acts as a simple switch. Unlike the Max gate object, any outlet which is not selected outputs a signal
composed of zero values.

Arguments
Name Units Type Opt Description
number-of-outlets int opt Number of outlets
number-of-outlets int opt Set the outlet that is initially selected. If 0, all signals are shut off and zero signals
are sent out all outlets.

Messages
int outlet-selected [int] Select outlet to route input to. If the number is 0 or negative a zero signal is sent
out. If the number is greater than the number of outlets, the signal is sent to the
rightmost outlet. If a signal is connected to the left inlet, gate~ ignores int or
float messages.
signal In left inlet: Select outlet to route input to. If the number is 0 or negative a zero
signal is sent out. If the number is greater than the number of outlets, the signal is
sent to the rightmost outlet. If a signal is connected to the left inlet, gate~ ignores
int or float messages.

In right inlet: The input signal to be passed through to one of the gate~ object's
outlets, according to the most recently received int or float in the left inlet, or the
value of the signal coming in the left inlet. If the signal network connected to the
right inlet of gate~ contains a begin~ object -- and a signal is not connected to the
left inlet of the gate~-- all processing between the begin~ outlet and the gate~
inlet will be turned off when gate~ is shut off.

Information for box attributes common to all objects

Output
signal: Depending on the value of the left inlet (either signal or number), one of the object's outlets will send out the input signal
and rest will send out zero signals, or (if the inlet is closed) all outlets will send out zero signals.

Examples

gate~ routes the input signal to one of its outlets, or shuts it off entirely
See Also
Name Description
selector~ Assign one of several inputs to an outlet
matrix~ Signal routing and mixing matrix
gate Pass input to an outlet
MSP Tutorial 4: Routing Signals MSP Tutorial 4: Routing Signals
MSP Tutorial 22: MIDI Panning MSP Tutorial 22: MIDI Panning
gen~
Generate native audio signal processing routines

Description
The gen~ object turns an embedded Gen patcher into signal processing routines of optimized native machine code. The Gen
patcher can be built from a wide set of low-level Gen operator objects as well as embedded code expressions.

Arguments
Name Units Type Opt Description
patcher-name symbol opt The first argument, if given, specifies the name of a .gendsp patcher to be loaded
which already exists and is in the Max search path. The patcher can also be
specified using the gen attribute. If no Gen patcher is specified by argument or gen
attribute, an embedded Gen patcher is created instead.

Messages
(drag) TEXT_HERE
(mouse) Double-click to open the Gen patcher.
compile Recompile the Gen patcher.
build_autocompile ARG_NAME_0 [list] TEXT_HERE
gen~ ARG_NAME_0 [list] TEXT_HERE
open View the Gen patcher.
signal Send signals to the Gen patcher.
reload Reload the Gen patcher.
wclose Close the view of the Gen patcher.

Attributes
Name Type g/s Description
cpu float (get) Reports cpu usage as a fraction of available compute time, if cpumeasure is
enabled.
cpumeasure int CPU monitoring must be enabled for cpu to work.
def.:0
debug int Enable/disable debug mode
def.:0
dumpoutlet int Attribute Dump Outlet
def.:0
fixdenorm int Enable/disable denormal replacement
def.:0
gen symbol Gen File
def.:
t symbol TEXT_HERE
title symbol TEXT_HERE

Information for box attributes common to all objects

Buffer
buffer: References an external named buffer~ object. The first argument specifies a name by which to refer to this data in other
objects in the gen patcher (such as peek and poke); the second optional argument specifies the name of the external buffer~
object to reference (if ommitted, the first argument name is used). The first outlet sends the length of the buffer in samples; the
second outlet sends the number of channels. This operator is not available in GenExpr.
channels: The length (in samples) of a data/buffer object. The first argument should be a name of a data or buffer object in the
gen patcher. This operator is not available in GenExpr.
cycle: An interpolating oscillator that reads repeatedly through one cycle of a waveform. If the buffer/data waveform is not
specified, an internal sine table is used. By default it is driven by a frequency input, but if the @index attribute is set to 'phase', it
can be driven by a phase input instead. In GenExpr, only the built-in sinusoid wavetable can be used.
data: Stores an array of sample data (64-bit floats) usable for sampling, wavetable synthesis and other purposes. The first
argument specifies a name by which to refer to this data in other objects in the gen patcher (such as peek and poke); the second
optional argument specifies the length of the array (default 512 samples); and the third optional argument specifies the number
of channels (default 1, maximum 16). The first outlet sends the length of the buffer in samples; the second outlet sends the
number of channels. This operator is not available in GenExpr.
dim: The length (in samples) of a data/buffer object. The first argument should be a name of a data or buffer object in the gen
patcher. This operator is not available in GenExpr.
lookup: Index a data/buffer object using a signal, for waveshaping. The first argument should be a name of a data or buffer object
in the gen patcher. The second argument (or second inlet if omitted) specifies which channel to use. Input signals in the range -1
to 1 are mapped to the full size of the data/buffer, with linear interpolation. The last inlet specifies a channel offset (default 0).
This operator is not available in GenExpr.
nearest: Multi-channel lookup a data/buffer object (no interpolation). The first argument should be a name of a data or buffer
object in the gen patcher. The second argument specifies the number of output channels. The input phase ranges from 0 to 1, and
wraps outside this range. The last inlet specifies a channel offset (default 0). This operator is not available in GenExpr.
peek: Read values from a data/buffer object. The first argument should be a name of a data or buffer object in the gen patcher.
The second argument (or second inlet if omitted) specifies which channel to use. The first inlet specifes a sample index to read (no
interpolation); indices out of range return zero. The last inlet specifies a channel offset (default 0). This operator is not available
in GenExpr.
poke: Write values into a data/buffer object. The first argument should be a name of a data or buffer object in the gen patcher.
The second argument (or third inlet if omitted) specifies which channel to use (default 1). The first inlet specifies a value to write,
while the second inlet specifies the sample index within the data/buffer. If the index is out of range, no value is written. This
operator is not available in GenExpr.
sample: Linear interpolated multi-channel lookup of a data/buffer object. The first argument should be a name of a data or buffer
object in the gen patcher. The second argument specifies the number of output channels. The last inlet specifies a channel offset
(default 0). This operator is not available in GenExpr.
splat: Mix values into a data/buffer object, with linear interpolated overdubbing. The first argument should be a name of a data
or buffer object in the gen patcher. The second argument (or third inlet if omitted) specifies which channel to use (default 1). The
first inlet specifies a value to write, while the fractional component of the second inlet specifies a phase (0..1) within the
data/buffer (indices out of range will wrap). Splat writes with linear interpolation between samples, and mixes new values with
the existing data (overdubbing). This operator is not available in GenExpr.
wave: Wavetable synthesis using a data/buffer object. The first argument should be a name of a data or buffer object in the gen
patcher. The second argument specifies the number of output channels. The first inlet specifies phase (0..1), while the second and
third inlets specify start/end sample positions within the data/buffer. The last inlet specifies a channel offset (default 0). This
operator is not available in GenExpr.

Comparison
!=, neq: Returns 1 if in1 does not equal in2, else returns zero.
!=p, neqp: Returns in1 if it does not equal in2, else returns zero.
<, lt: Returns 1 if in1 is lesser (in the positive direction) than in2, else returns zero.
<=, lte: Returns 1 if in1 is equal to or lesser (in the positive direction) than in2, else returns zero.
<=p, ltep: Returns in1 if in1 is equal to or lesser (in the positive direction) than in2, else returns zero.
<p, ltp: Returns in1 if in1 is lesser (in the positive direction) than in2, else returns zero.
==, eq: Returns 1 if in1 equals in2, else returns zero.
==p, eqp: Returns in1 if it equals in2, else returns zero.
>, gt: Returns 1 if in1 is greater (in the positive direction) than in2, else returns zero.
>=, gte: Returns 1 if in1 is equal to or greater (in the positive direction) than in2, else returns zero.
>=p, gtep: Returns in1 if in1 is equal to or greater (in the positive direction) than in2, else returns zero.
>p, gtp: Returns in1 if in1 is greater (in the positive direction) than in2, else returns zero.
max, maximum: The maximum of the inputs
min, minimum: The minimum of the inputs
step: Akin to the GLSL step operator: 0 is returned if in1 < in2, and 1 is returned otherwise.

Constant
constant: A constant value
degtorad, DEGTORAD: the constant pi/180
e, E: the constant e
f, float: A constant float value, or a conversion of the incoming value to float.
halfpi, HALFPI: the constant pi/2
i, int: A constant integer value, or a conversion of the incoming value to integer.
invpi, INVPI: the constant 1/pi
ln10, LN10: the constant ln10
ln2, LN2: the constant ln2
log10e, LOG10E: the constant log10e
log2e, LOG2E: the constant log2e
pi, PI: the constant pi
radtodeg, RADTODEG: the constant 180/pi
sqrt1_2, SQRT1_2: the constant 1/sqrt(2)
sqrt2, SQRT2: the constant sqrt(2)
twopi, TWOPI: the constant 2*pi

Convert
atodb: Convert linear amplitude to deciBel value
dbtoa: Convert deciBel value to linear amplitude
ftom: Frequency given in Hertz is converted to MIDI note number (0-127). Fractional note numbers are supported. An additional
optional argument sets the tuning base (default 440).
mstosamps: Convert period in milliseconds to samples
mtof: MIDI note number (0-127) is converted to frequency in Hertz. Fractional note numbers are supported. An additional
optional argument sets the tuning base (default 440).
sampstoms: Convert period in samples to milliseconds

Declare
param, Param: Named parameters can be modified from the host object of the gen patcher. The first argument specifies the
name of the parameter, the second argument specifies the initial value.

Dsp
fixdenorm: This operator detects denormal numbers and replaces them with zero. A denormal or subnormal number is a floating
point value very close to zero (filling the underflow gap). Calculations with denormal values can be up to 100 times more
expensive, so it is often beneficial to replace them with zeroes. Denormals often occur in feedback loops with multipliers, such as
filters, delays and exponential decays. Denormal detection is based on a bitmask. Note that feedback operators in gen~ (delay,
history) apply fixdenorm to their input signals by default.
fixnan: This operator replaces NaNs with zero. A NaN (Not a Number) is a floating point data value which represents an
undefined or unrepresentable value, such as the result of dividing by zero. Computations on NaNs produce more NaNs, and so it
is often preferable to replace the NaN with a zero value. Note that division and modulo operators in gen~ protect against
generating NaNs by default.
isdenorm: This operator detects denormal numbers and returns 1 if the input is denormal, and zero otherwise. A denormal or
subnormal number is a floating point value very close to zero (filling the underflow gap). Calculations with denormal values can
be up to 100 times more expensive, so it is often beneficial to replace them with zeroes. Denormals often occur in feedback loops
with multipliers, such as filters, delays and exponential decays. Denormal detection is based on a bitmask. Note that feedback
operators in gen~ (delay, history) apply fixdenorm to their input signals by default.
isnan: This operator detects the presence of NaN values, returning 1 if the input is NaN, and zero otherwise. A NaN (Not a
Number) is a floating point data value which represents an undefined or unrepresentable value, such as the result of dividing by
zero. Computations on NaNs produce more NaNs, and so it is often preferable to replace the NaN with a zero value. Note that
division and modulo operators in gen~ protect against generating NaNs by default.
samplerate: The current samplerate

Expression
expr: Evaluates GenExpr code. Standard mathematical operators (+, -, *, / etc.) and gen patcher operators can be used. See the
GenExpr documentation for more detail.

Feedback
delay: Delays a signal by a certain amount of time (specified in samples). The first argument specifies the maximum delay time
(in samples, default 512), while the second argument specifies the number of tap inlet/outlet pairs (default 1). The first inlet is the
signal to be delayed. Additional inlets specify the delay time per tap (in samples). With @feedback 1, like the history operator
(and unlike delay~), the signal input of delay allows feedback connections. Denormal protection is automatically applied to the
signal input. The minimum delay time however is increased by 1 sample. With @interp none or @interp step, no interpolation is
done on output. With @interp linear (the default), @interp cosine, @interp cubic or @interp spline, interpolation is applied to
the output. In the case of @interp cubic and @interp spline, the minimum delay time is increased by 1 sample. Note that delay is
not currently supported in GenExpr.
history: The history operator allows feedback in the gen patcher through the insertion of a single-sample delay. The first
argument is an optional name for the history operator, which allows it to also be set externally as a parameter. The second
argument specifies an initial value of stored history (defaults to zero). Denormal protection is automatically applied to the history
input.

Filter
*=, mulequals: The object multiplies by, and then outputs, an internal value. This occurs at sample-rate, so the stored value can
grow very large or very small, very fast. The value to be multiplied by is specified by either the first inlet or argument. The
internal sum can be reset to the minimum by sending a nonzero value to the right-most inlet. The minimum value is 0 by default,
but can be changed with the @min attribute. An optional maximum value can be specified with the @max attribute; values will
wrap at the maximum.
+=, accum, plusequals: The object adds to, and then outputs, an internal sum. This occurs at sample-rate, so the sum can grow
very large, very fast. The value to be added is specified by either the first inlet or argument. The internal sum can be reset to the
minimum by sending a nonzero value to the right-most inlet. The minimum value is 0 by default, but can be changed with the
@min attribute. An optional maximum value can be specified with the @max attribute; values will wrap at the maximum.
change: Returns the sign of the difference between the current and previous input: 1 if the input is increasing, -1 if decreasing,
and 0 if unchanging.
dcblock: A one-pole high-pass filter to remove DC components. Equivalent to the GenExpr: History x1, y1; y = in1 - x1 +
y1*0.9997; x1 = in1; y1 = y; out1 = y;
delta: Returns the difference between the current and previous input.
interp: Smoothly mix between inputs, according to an interpolation factor in the range of 0 to 1 (first inlet). The @mode attribute
can choose between linear or cosine interpolation to mix between two additional inlets, or cubic or spline to mix between four
additional inlets. The default mode is linear.
phasewrap: Wrap input to the range -pi to +pi
sah: The first inlet is the 'input' and the second inlet is the 'control'. When the control makes a transition from being at or below
the trigger value to being above the trigger threshold, the input is sampled. The sampled value is output until another control
transition occurs, at which point the input is sampled again. The default threshold value is 0, but can be specified as the last
inlet/argument. The @init attribute sets the initial previous value to compare to (default 0).
spline_interp: The first inlet is the 'input' and the second inlet is the 'control'. When the control makes a transition from being at
or below the trigger value to being above the trigger threshold, the input is sampled. The sampled value is output until another
control transition occurs, at which point the input is sampled again. The default threshold value is 0, but can be specified as the
last inlet/argument. The @init attribute sets the initial previous value to compare to (default 0).

Input-output
in: Receive input into a gen patcher
out: Send output from a gen patcher

Logic
!, not: Zero input returns 1, any other value returns zero.
&&, and: Returns 1 if both in1 and in2 are nonzero.
^^, xor: Returns 1 if one of in1 and in2 are nonzero, but not both.
bool: Any nonzero value becomes 1, zero passes through.
or, ||: Returns 1 if either in1 and in2 are nonzero.

Math
!%, rmod: Reverse modulo (remainder of second input / first input)
!-, rsub: Reverse subtraction (subtract second input from first)
!/, rdiv: Reverse division (divide second input by first)
%, mod: Modulo inputs (remainder of first input / second input)
*, mul: Multiply inputs
+, add: Add inputs
-, sub: Subtract inputs
/, div: Divide inputs
absdiff: Compute the absolute difference between two inputs
cartopol: Convert Cartesian values to polar format. Angles are in radians.
neg: Negate input
poltocar: Convert polar values to Cartesian format. Angles are in radians.

Numeric
abs: Negative values will be converted to positive counterparts.
ceil: Round the value up to the next higher integer
floor, trunc: Round the value down to the next lower integer
fract: Return only the fractional component
sign: Positive input returns 1, negative input returns -1, zero returns itself.

Powers
exp: Raise the mathemtatical value e to a power
exp2: Raise 2 to a power
ln, log: The natural logarithm
log10: The logarithm base 10 of the input
log2: The logarithm base 2 of the input
pow: Raise in1 to the power of in2
sqrt: The square root of the input

Range
clamp, clip: Clamps the input value between specified min and max. Ranges are inclusive (both min and max values may be
output). If two arguments are given, they correspond to the min and max values respectively. If one argument is given, it is
assumed to correspond to the maximum value, while the minimum is set by the second inlet. If no arguments are given, min and
max are specified by the second and third inlets (defaulting to 0 and 1 respectively).
fold: Low and high values can be specified by arguments or by inlets. The default range is 0..1.
scale: Similar to the Max scale and MSP scale~ objects. Inputs are: 1) value to scale, 2) input lower bound, 3), input upper bound,
4) output lower bound, 5) output upper bound, 6) exponential curve. Default lower and upper bounds are zero and one; default
exponential curve is 1 (linear). No bound clamping is performed. The high and low values can be reversed for inverted mapping.
wrap: Low and high values can be specified by arguments or by inlets. The default range is 0..1.

Route
?, switch: Selects between the second and third inputs according to the Boolean value of the first: returns in2 if in1 is nonzero,
else returns in3. If one argument is given, it specifies the 'true' value (and the right inlet is the 'false' value). If two arguments are
given, they are the true and false values.
mix: Mixes (interpolates) between inputs a and b according to the value of the third input t, using linear interpolation. The factor
(t) should vary between 0 (for a) and 1 (for b). If one argument is given, it specifies the mix (interpolation) factor.
smoothstep: Smoothstep is a scalar interpolation function commonly used in computer graphics. The function interpolates
smoothly between two input values based on a third one that should be between the first two. The returned value is clamped
between 0 and 1. The slope (i.e. derivative) of the smoothstep function starts at 0 and ends at 0.

Routing
gate: Similar to the MSP gate~ object. It takes an argument for number of outputs (one is the default) and lets you choose which
the incoming signal (at the right inlet) is sent to according to the (integer) value in the left inlet. A value of zero or less to the left
inlet will choose no output; a value greater than the number of outlets will select the last outlet. Like gate~, un-selected outlets
will send zero. This operator is not available in GenExpr.
selector: Similar to the MSP selector~ object. In a Gen patcher it takes an argument for number of choices (one is the default). In
GenExpr, the number of choices is determined by the number of arguments. The first input lets you choose which of the
remaining inputs is sent to the output. A value of zero or less to the first input will result in a zero signal at the output; a value
greater than the number of choices will select the last input.

Trigonometry
acos: The arc cosine of the input (returns radians)
acosh: The inverse hyperbolic cosine of the input
asin: The arc sine of the input (returns radians)
asinh: The inverse hyperbolic sine of the input
atan: The arc tangent of the input (returns radians)
atan2: Returns the angle to the coordinate (in2, in1) in radians.
atanh: The inverse hyperbolic tangent of the input
cos: The cosine of the input (in radians)
cosh: The hyperbolic cosine of the input
degrees: convert radians to degrees
hypot: Returns the length of the vector to (in1, in2).
radians: convert degrees to radians
sin: The sine of the input (in radians)
sinh: The hyperbolic sine of the input
tan: The tangent of the input (in radians)
tanh: The hyperbolic tangent of the input

Waveform
noise: A random number generator
noise: A random number generator
phasor: A non-bandlimited sawtooth-waveform signal generator which can be used as LFO audio signal or a sample-accurate
timing/control signal.
train: train~ generates a pulse signal whose period is specifiable in terms of samples. The first input sets the pulse period (in
samples). The second input sets the pulse width (default 0.5). The third inlet sets the phase of the 'on' portion (default 0.)
triangle: A triangle/ramp wavetable with input to change phase offset of the peak value. The phase ranges from 0 to 1 (and wraps
outside these values). With a duty cycle of 0, it produces a descending sawtooth; with a duty cycle of 1 it produces ascending
sawtooth; with a duty cycle of 0.5 it produces a triangle waveform. Output values always bounded in 0 to 1.

Waveform
noise: A random number generator
noise: A random number generator
phasor: A non-bandlimited sawtooth-waveform signal generator which can be used as LFO audio signal or a sample-accurate
timing/control signal.
train: train~ generates a pulse signal whose period is specifiable in terms of samples. The first input sets the pulse period (in
samples). The second input sets the pulse width (default 0.5). The third inlet sets the phase of the 'on' portion (default 0.)
triangle: A triangle/ramp wavetable with input to change phase offset of the peak value. The phase ranges from 0 to 1 (and wraps
outside these values). With a duty cycle of 0, it produces a descending sawtooth; with a duty cycle of 1 it produces ascending
sawtooth; with a duty cycle of 0.5 it produces a triangle waveform. Output values always bounded in 0 to 1.
Examples

Using gen~ to host a Gen patcher

See Also
Name Description
jit.gen Generate new Jitter MOP objects
jit.pix Generates Jitter mop pixel processing objects from a patcher.
Gen Overview Gen Overview
Gen Common Operators Gen Common Operators
gen~ Operators gen~ Operators
gizmo~
Frequency-domain pitch shifter for pfft~

Description
The gizmo~ object implements a frequency-domain pitch shifter. It works by analyzing the frequency bins of an FFT'd signal,
finding the peaks in the spectrum, and shifting them along the frequency axis to transpose the sound.

Arguments
Name Units Type Opt Description
default-pitch- float or opt A numerical argument will be used as the default pitch shift scalar. The default is
scalar int 1.0 (no pitch scaling).

Messages
clip frequency-clipping-flag (0 or In left inlet: The word clip, followed by a zero or one, disables or enables the
nonzero) [int] clipping of clips any out-of-range peaks caused by transposition rather than of
folding them over. The default is off (equivalent to the message clip 0, so the
gizmo~ object behaves like a time-domain transposer. Clipping may be turned off
to avoid unwanted aliasing, and its use will probably depend on the sound being
transposed and the range of transposition.
freqshift frequency-shift [float] In left inlet: The word freqshift followed by a numerical value representing a
positive or negative frequency in Hertz will be used as a frequency offet for the
scaled amplitude peaks in the frequency spectrum. This corresponds to a
frequency-shift of the transposed signal (see the freqshift~ or fbinshift~ objects
for additional information).
signal In left inlet: The signal present at the left inlet is the real part of a
frequencydomain signal coming from a fftin~ object inside a pfft~.

In middle inlet: The signal input to the middle inlet is the imaginary part of a
frequency-domain signal coming from a fftin~ object inside a pfft~. Both real and
imaginary inputs must be connected for gizmo~ to work.

Information for box attributes common to all objects

Output
signal: The output is the pitch-shifted complex signal. The left outlet is the real component, and the right outlet is the imaginary
component. These may be connected to the real and imaginary inputs of a fftout~ object inside a pfft~.

Examples

gizmo~ shifts the pitch of an incoming sound so you can use it for harmonization effects
See Also
Name Description
fbinshift~ Frequency domain frequency shifter for pfft~
freqshift~ Time-domain frequency shifter
hilbert~ Phase quadrature filter
>~
Is greater than, comparison of two signals

Description
>~ outputs a 1 signal when the left input is greater-than the right input and a 0 when it is less-than or equal-to the right input.
The right input can be a signal or a float.

Arguments
Name Units Type Opt Description
initial- number opt Sets an initial comparison value for the signal coming into the left inlet. 1 is sent
comparison-value out if the signal is greater than the argument; otherwise, 0 is sent out. If a signal is
connected to the right inlet, the argument is ignored. If no argument is present,
and no signal is connected to the right inlet, the initial value is 0 by default.

Messages
int comparison-value [int] In right inlet: A number to be used for comparison with the signal coming into the
left inlet. If a signal is also connected to the right inlet, a float or int is ignored.
float comparison-value [float] In right inlet: A number to be used for comparison with the signal coming into the
left inlet. If a signal is also connected to the right inlet, a float or int is ignored.
signal In left inlet: The signal is compared to a signal coming into the right inlet, or a
constant value received in the right inlet. If it is greater than the value in the right
inlet, 1 is sent out; otherwise, 0 is sent out.

In right inlet: The signal is used for comparison with the signal coming into the left
inlet.

Information for box attributes common to all objects

Output
signal: If the signal in the left inlet is greater than the value in the right inlet, 1 is sent out; otherwise, 0 is sent out.

Examples

Convert any signal to only 1 and 0 values

See Also
Name Description
<~ Is less than, comparison of two signals
<=~ Is less than or equal to, comparison of two signals
>=~ Is greater than or equal to, comparison of two signals
==~ Is equal to, comparison of two signals
!=~ Not equal to, comparison of two signals
sah~ Sample and hold a signal according to a trigger
>=~
Is greater than or equal to, comparison of two signals

Description
>=~ outputs a 1 signal when the left input is greater-than or equal-to the right input and a 0 when it is less-than the right input.
The right input can be a signal or a float.

Arguments
Name Units Type Opt Description
initial- number opt Sets an initial comparison value for the signal coming into the left inlet. 1 is sent
comparison-value out if the signal is greater than or equal to the argument; otherwise, 0 is sent out.
If a signal is connected to the right inlet, the argument is ignored. If no argument
is present, and no signal is connected to the right inlet, the initial value is 0 by
default.

Messages
int comparison-value [int] In right inlet: A number to be used for comparison with the signal coming into the
left inlet. If a signal is also connected to the right inlet, a float or int is ignored.
float comparison-value [float] In right inlet: A number to be used for comparison with the signal coming into the
left inlet. If a signal is also connected to the right inlet, a float or int is ignored.
signal In left inlet: The signal is compared to a signal coming into the right inlet, or a
constant value received in the right inlet. If it is greater-than or equal-to the value
in the right inlet, 1 is sent out; otherwise, 0 is sent out.

In right inlet: The signal is used for comparison with the signal coming into the left
inlet.

Information for box attributes common to all objects

Output
signal: If the signal in the left inlet is greater than or equal to the value in the right inlet, 1 is sent out; otherwise, 0 is sent out.

Examples

See Also
Name Description
<~ Is less than, comparison of two signals
<=~ Is less than or equal to, comparison of two signals
>~ Is greater than, comparison of two signals
==~ Is equal to, comparison of two signals
!=~ Not equal to, comparison of two signals
sah~ Sample and hold a signal according to a trigger
groove~
Variable-rate looping sample playback

Description
The groove~ object is a variable-rate, looping, sample-playback object which references the audio information stored in a
buffer~ object having the same name.

Arguments
Name Units Type Opt Description
buffer-name symbol Names the buffer~ object containing the sample to be used by groove~ for
playback.
number-of- int opt A second argument may specify the number of output channels: 1, 2, or 4. The
outputs default number of channels is 1. If the buffer~ being played has fewer channels
than the number of groove~ output channels, the extra channels output a zero
signal. If the buffer~ has more channels, channels are mixed.

Messages
int playback-position [int] In all inlets: Converted to float.

In left inlet: Sets the sample playback position in milliseconds. 0 sets the playback
position to the beginning.
In middle inlet: Sets the sample playback start position in milliseconds.
In right lnlet: Sets the sample playback start position in milliseconds.
float playback-position [float] In left inlet: Sets the sample playback position in milliseconds. 0 sets the playback
position to the beginning.
In middle inlet: Sets the sample playback start position in milliseconds.
In right lnlet: Sets the sample playback start position in milliseconds.
list bars [int] In middle inlet: A list composed of three integers specifying bars, beats, and units
beats [int] may be used to specify the loop start point when the groove~ object is set to
units [int] follow a named transport (set using the transport attribute).

In right inlet: A list composed of three integers specifying bars, beats, and units
may be used to specify the loop end point when the groove~ object is set to follow
a named transport (set using the transport attribute).
anything bars [int] In middle inlet: A list composed of three integers specifying bars, beats, and units
beats [int] may be used to specify the loop start point when the groove~ object is set to
units [int] follow a named transport (set using the transport attribute).

In right inlet: A list composed of three integers specifying bars, beats, and units
may be used to specify the loop end point when the groove~ object is set to follow
a named transport (set using the transport attribute).
(mouse) Double-clicking on a groove~ object opens the sample display window of the
buffer~ object associated with the groove~ object.
loopinterp behavioral-flag (0 or 1) The word loopinterp, followed by 1, enables interpolation about start and end
[int] points for a loop. loop 0 turns off loop interpolation. By default, loop
interpolation is off. Turning loop interpolation on disables resampling.
set buffer-name [symbol] The word set, followed by a symbol, switches the buffer~ object containing the
sample to be used by groove~ for playback.
reset Clear the start and end loop points
setloop start-point [list] The word setloop, followed by two numbers, sets the start and end loop points in
end-point [list] milliseconds.
signal In left inlet: Defines the sample increment for playback of a sound from a buffer~.
A sample increment of 0 stops playback. A sample increment of 1 plays the sample
at normal speed. A sample increment of -1 plays the sample backwards at normal
speed. A sample increment of 2 plays the sample at twice the normal speed. A
sample increment of .5 plays the sample at half the normal speed. The sample
increment can change over time for vibrato or other types of speed effects. The
groove~ object uses the buffer~ sampling rate to determine playback speed.

If a loop start and end have been defined for groove~ and looping is turned on,
when the sample playback reaches the loop end the sample position is set to the
loop start and playback continues at the current sample increment.

In middle inlet: Sets the starting point of the loop in milliseconds.

In right inlet: Sets the end point of the loop in milliseconds.


startloop Causes groove~ to begin sample playback at the starting point of the loop. If no
loop has been defined, groove~ begins playing at the beginning.
stop The word stop will cause groove~ to stop playback until the next int, float, or
startloop message is received.

Attributes
Name Type g/s Description
loop int Turn on looping
loopend atom Sets the loop end point. The end point time can be specified in any of the Max
time formats.
loopstart atom Sets the loop start point. The start point time can be specified in any of the Max
time formats.
resample int Resample the audio from buffer~ to produce higher-quality output. This process
dramatically reduces aliasing and other undesirable audio artifacts, though the
resampling can be computationally expensive in some cases.
transport symbol Sets the name of a transport object with which to associate. By default, the global
transport is used. When the groove~ object is associated with a transport, loop
points are specified using 3-item lists which correspond to time in bars, beats, and
units.

Information for box attributes common to all objects

Output
signal: Out left outlet: Sample output. If groove~ has two or four output channels, the left outlet plays the left channel of the
sample.

Out middle outlets: Sample output. If groove~ has two or four output channels, the middle outlets play the channels other than
the left channel.

Out right outlet: Sync output. During the loop portion of the sample, this outlet outputs a signal that goes from 0. when the loop
starts to 1. when the loop ends.
Note: In order for buffer playback to begin (and consequently for sync output), one of the groove~ object's output channels must
be connected to another signal object.

Examples
See Also
Name Description
2d.wave~ Two-dimensional wavetable
buffer~ Store audio samples
play~ Position-based sample playback
wave~ Variable size wavetable
index~ Read from a buffer~ with no interpolation
record~ Record sound into a buffer
transport Control a master clock
MSP Tutorial 14: Playback with MSP Tutorial 14: Playback with Loops
Loops
MSP Tutorial 20: MIDI Sampler MSP Tutorial 20: MIDI Sampler Control
Control
hilbert~
Phase quadrature filter

Description
hilbert~ is a 6th order hilbert transformer with a minimum of error.

Arguments
None.

Messages
clear Clears the object's sample-memory in case of a blow-up.
signal In left inlet: The signal that will be hilbert-transformed. The Hilbert transform, or
phase quadrature, produces signals that are 90 degrees out of phase with each
other.

Information for box attributes common to all objects

Output
signal: Out left outlet: The "real" part of the hilbert-transformed signal. It will be 90 degrees out of phase from the "imaginary"
part.

Out right outlet: The "imaginary" part of the hilbert-transformed signal. It will be 90 degrees out of phase from the "real" part.

Examples

It seems Pythagoras was right

See Also
Name Description
fbinshift~ Frequency domain frequency shifter for pfft~
freqshift~ Time-domain frequency shifter
gizmo~ Frequency-domain pitch shifter for pfft~
hostcontrol~
Control a ReWire host's transport

Description
When you choose the ad_rewire driver in the Audio Status window, the hostcontrol~ object lets you send commands to the
ReWire host to start and stop the transport, set the transport position, change the tempo, change the time signature, and set loop
points.

Arguments
None.

Messages
int playback-flag (1 or 0) [int] 1 starts playing from the beginning. 0 stops playing and resets the position to the
beginning.
bpm host-tempo [float] The word bpm, followed by a number (in beats per minute), changes the host's
tempo.
loop state (0 or nonzero), start (1- The word loop, followed by one or three numbers, controls the host's loop state. If
PPQ-ticks), and end (1-PPQ- the first number is non-zero, looping will be enabled; otherwise, it will be turned
ticks) [list] off. An optional second and third number may be used to specify the loop start and
end points, expressed in 1 PPQ ticks. If the second and third numbers are not
present, the loop points are not changed.
pause The word pause stops playback without changing the current position.
resume The word resume starts playback from the current position.
seek transport-position (1-PPQ- The word seek, followed by a number specifying ticks (in 1 PPQ), sets the current
ticks) [float] transport position. For example, to seek to the start of the fifth measure if the time
signature is 4/4 the send the message "seek 16".
tempo host-tempo [float] The word tempo, followed by a number (in samples per beat), changes the host's
tempo.
timesig host-time-signature The word timesig, followed by two numbers that specify numerator and
(numerator) [int] denominator values, changes the host's time signature. For example, to set the
host-time-signature time signature to 3/4 send the message timesig 3 4.
(denominator) [int]

Information for box attributes common to all objects

Output
Rewire: Controls a Rewire host.

Examples

See Also
Name Description
hostphasor~ ReWire host synchronization source
hostsync~ Get transport control info from a ReWire host
hostphasor~
ReWire host synchronization source

Description
hostphasor~ outputs an audio-rate sawtooth wave that is sample-synchronized to the beat of the ReWire host sequencer. The
waveform can be fed to other audio objects to lock audio processes to the audio of the ReWire host.

Arguments
None.

Information for box attributes common to all objects

Output
signal: The output of hostphasor~ is analogous to phasor~: it ramps from 0 to 1.0 over the period of a beat. If the current host
environment does not support synchronization or the ReWire host's transport is stopped, the output of hostphasor~ is a zero
signal.

Examples

See Also
Name Description
hostcontrol~ Control a ReWire host's transport
hostsync~ Get transport control info from a ReWire host
hostsync~
Get transport control info from a ReWire host

Description
The hostsync~ object provides information about the current state of the ReWire host.

Arguments
None.

Messages
bang bang will cause the hostsync~ object to report its transport state.

Information for box attributes common to all objects

Output
float: Out 4nd outlet: The current beat fraction, from 0 to 1.0. If the ReWire host does not support synchronization, there is no
output from this outlet.
float: Out 6th outlet: The current tempo in samples per beat. This number can be converted to beats per minute using the
following formula: (sampling-rate / samples-per-beat) * 60. If the ReWire host does not support synchronization, there is no
output from this outlet.
float: Out 7th outlet: The current number of beats, expressed in 1 PPQ. This number will contain a fractional part between beats.
If the ReWire host does not support synchronization, there is no output from this outlet.
int: Out left outlet: 1 if the ReWire host's transport is currently running; 0 if it is stopped or paused.
int: Out 2nd outlet: The current bar count in the ReWire host sequence, starting at 1 for the first bar. If the ReWire host does not
support synchronization, there is no output from this outlet.
int: Out 3rd outlet: The current beat count in the ReWire host sequence, starting at 1 for the first beat. If the ReWire host does
not support synchronization, there is no output from this outlet.
int: Out 8th outlet: The current sample count, as defined by the ReWire host.
int: Out 10th outlet: A number representing the validity of the other information coming from hostsync~. Mask with the
following values to determine if the information from hostsync~ will be valid.

Sample Count Valid 1 (always true)

Beats Valid 2 (2nd, 3rd, 4th, and 7th outlets valid)

Time Signature Valid 4 (5th outlet valid)

Tempo Valid 8 (6th outlet valid)

Transport Valid 16 (left outlet valid)

Loop Info Valid 64 (9th outlet valid)


list: Out 5th outlet: The current time signature as a list containing numerator followed by denominator. For instance, 3/4 time
would be output as the list 3 4. If the ReWire host does not support time signature information, there is no output from this
outlet.
list: Out 9th outlet: The loop info output as a list of three numbers containing loop on/off state (0,1), the loop start point (in
1PPQ ticks), and the loop stop point (in 1PPQ ticks). For example, if the time signature was 4/4 and looping was on from the
start of the fifth measure for four bars the list would be 1 16 32.

Examples

See Also
Name Description
hostcontrol~ Control a ReWire host's transport
hostphasor~ ReWire host synchronization source
ifft~
Inverse fast Fourier transform

Description
ifft~ performs an Inverse FFT (inverse fast Fourier transform) on an input signal.

Arguments
Name Units Type Opt Description
IFFT-points samples int opt The first argument specifies the number of points (samples) in the IFFT. It must
be a power of two. The default number of points is 512. The second argument
specifies the number of samples between successive IFFTs. This must be at least
the number of points, and must be also be a power of two. The default interval is
512. The third argument specifies the offset into the interval where the IFFT will
start. This must either be 0 or a multiple of the signal vector size. ifft~ will correct
bad arguments, but if you change the signal vector size after creating an ifft~ and
the offset is no longer a multiple of the vector size, the ifft~ will not operate when
signal processing is turned on.

Messages
phase offset [int] Offset from the beginning of a period when the IFFT is performed
signal In left inlet: The real part of a complex signal that will be inverse transformed.

In right inlet: The imaginary part of a complex signal that will be inverse
transformed.

If signals are connected only to the left inlet and left outlet, a real IFFT (inverse
Fast Fourier transform) will be performed. Otherwise, a complex IFFT will be
performed.

Information for box attributes common to all objects

Output
signal: Out left outlet: The real part of the inverse Fourier transform of the input. The output begins after all the points of the
input have been received.

Out middle outlet: The imaginary part of the inverse Fourier transform of the input. The output begins after all the points of the
input have been received.

Out right outlet: A sync signal that ramps from 0 to the number of points minus 1 over the period in which the IFFT output
occurs. When the IFFT is not being output (in the case where the interval is larger than the number of points), the sync signal is
0.

Examples
Using fft~ and ifft~ for analysis and resynthesis

See Also
Name Description
cartopol Convert cartesian to polar coordinates
cartopol~ Signal Cartesian to Polar coordinate conversion
fft~ Fast Fourier transform
fftin~ Input for a patcher loaded by pfft~
fftinfo~ Report information about a patcher loaded by pfft~
fftout~ Output for a patcher loaded by pfft~
frameaccum~ Compute "running phase" of successive phase deviation frames
framedelta~ Compute phase deviation between successive FFT frames
pfft~ Spectral processing manager for patchers
poltocar Convert polar to cartesian coordinates
poltocar~ Signal Polar to Cartesian coordinate conversion
vectral~ Vector-based envelope follower
MSP Tutorial 25: Using the FFT MSP Tutorial 25: Using the FFT
in
Message input for a patcher loaded by poly~ or pfft~

Description
in defines a message inlet for a patcher loaded by poly~ or pfft~.

Arguments
Name Units Type Opt Description
inlet- int Obligatory. Each in object is identified by a unique index number which specifies
number/positioning which message inlet in a poly~ or pfft~ object it corresponds to. The first outlet is
1.

Messages
comment inlet-description [list] Sets a comment for display on poly object inlet mouseover

Attributes
Name Type g/s Description
attr_comment symbol Defines the comment displayed whenever the mouse is rolled over the inlet which
corresponds to the in of the actual poly~ or pfft~ object.

Information for box attributes common to all objects

Output
message: Each in object in a patcher loaded by the poly~ or pfft~ objects appears as an inlet at the top of the object. Messages
received at the first message inlet of the poly~ or pfft~ object are sent to the first in object (i.e., the in 1 object) in the loaded
patcher, and so on. The number of total inlets in a poly~ or pfft~ object is determined by whether there are a greater number of
in~ or in objects in the loaded patch (e.g., if your loaded poly~ patcher has three in~ objects and only two in objects, the poly~
object will have three inlets, two of which will accept both signals and anything else, and a third inlet which only takes signal
input).

Examples

Message inlets of the poly~ object correspond to the in objects inside the loaded patcher

See Also
Name Description
in~ Signal input for a patcher loaded by poly~
inlet Receive messages from outside a patcher
out Message output for a patcher loaded by poly~ or pfft~
out~ Signal output for a patcher loaded by poly~
outlet Send messages out of a patcher
pfft~ Spectral processing manager for patchers
poly~ Manage polyphony/DSP for patchers
thispoly~ Control poly~ voice allocation and muting
MSP Tutorial 21: Using the poly~ MSP Tutorial 21: Using the poly~ Object
Object
in~
Signal input for a patcher loaded by poly~

Description
Use the in~ object inside a patcher loaded by the poly~ object to create a patcher signal inlet.

Arguments
Name Units Type Opt Description
inlet-number int Specifies the signal inlet number in a poly object. The first inlet is 1.

Messages
comment inlet-description [list] Sets a comment for display on poly object inlet mouseover
signal Receives a signal sent to a loaded poly object.

Attributes
Name Type g/s Description
attr_comment symbol Comment to be displayed on poly object inlet mouseover

Information for box attributes common to all objects

Output
signal: Each in~ object in a patcher loaded by the poly~ object appears as an inlet at the top of the poly~ object. Signals received
at the first message inlet of the poly~ object are sent to the first in~ object (i.e., the in~1 object) in the loaded patcher, and so
on. The number of total inlets in a poly~ object is determined by whether there are a greater number of in~ or in objects in the
loaded patch (e.g., if your loaded patcher has three in~ objects and only two in objects, the poly~ object will have three inlets,
two of which will accept both signals and anything else, and a third inlet which only takes signal input).

Examples

Signal inlets of the poly~ object correspond to the in~ objects inside the loaded patcher

See Also
Name Description
in Message input for a patcher loaded by poly~ or pfft~
out Message output for a patcher loaded by poly~ or pfft~
out~ Signal output for a patcher loaded by poly~
poly~ Manage polyphony/DSP for patchers
thispoly~ Control poly~ voice allocation and muting
MSP Tutorial 21: Using the poly~ MSP Tutorial 21: Using the poly~ Object
Object
index~
Read from a buffer~ with no interpolation

Description
Use index~ to read from a buffer~ object at a signal-driven sample index with no interpolation on the output.

Arguments
Name Units Type Opt Description
buffer-name symbol Buffer name
buffer-channel- int opt Buffer channel to read
to-index

Messages
(mouse) Double-click to view the buffer~ contents
set buffer-name [symbol] Set name of the buffer~ to read
signal Set sample index

Information for box attributes common to all objects

Output
signal: The output consists of samples at the sample indices specified by the input. No interpolation is performed if the input
sample index is not an integer.

Examples

Look up specific samples in the buffer~, using index~

See Also
Name Description
buffer~ Store audio samples
buffir~ buffer-based FIR filter
count~ Count samples elapsed
fft~ Fast Fourier transform
MSP Tutorial 13: Recording and MSP Tutorial 13: Recording and Playback
Playback
info~
Report information about a sample

Description
Use the info~ object to report the information in a file read into a buffer~ object in response to a bang. If the information is not
present, it will be 0. info~ does not require that the audio be turned on in order to work. Looping and tuning information is found
in AIFF files.

Arguments
Name Units Type Opt Description
buffer-name symbol Names the buffer~ object for which info~ will report information.

Messages
bang In left inlet: Causes a report of information about a sample contained in the
associated buffer~ object.
(mouse) Double-clicking on info~ opens an editing window where you can view the
contents of its associated buffer~ object.
set buffer-name [symbol] The word set followed by the name of a buffer~ object, sets which buffer~ to
which info~ will refer.

Information for box attributes common to all objects

Output
Sample Information: Most of the information reported by info~ is taken from the audio file most recently read into the
associated buffer~. If this information is not present, only the sampling rate is sent out the left outlet. No output occurs for any
item that's missing from the sound file.
float: Out left outlet: The sampling rate of the sample.

Out 3rd outlet: Sustain loop start, in milliseconds.

Out 4th outlet: Sustain loop end, in milliseconds.

Out 5th outlet: Release loop start, in milliseconds.

Out 6th outlet: Release loop end, in milliseconds.

Out 7th outlet: Total time of the associated buffer~ object, in milliseconds.

Out 8th outlet: Name of the most recently read audio file.
list: Out 2nd outlet: Instrument information about the sample, as follows:

1. The MIDI pitch of the sample.

2. The detuning from the original MIDI note number of the sample, in pitch bend units.

3. The lowest MIDI note number to use when playing this sample.

4. The highest MIDI note number to use when playing this sample.

5. The lowest MIDI velocity to use when playing this sample.

6. The highest MIDI velocity to use when playing this sample.

7. The gain of the sample (0-127).


Examples

Check sample rate of a sample use other information contained in a sample

See Also
Name Description
buffer~ Store audio samples
mstosamps~ Convert milliseconds to samples
sfinfo~ Report audio file information
MSP Tutorial 14: Playback with MSP Tutorial 14: Playback with Loops
Loops
MSP Tutorial 20: MIDI Sampler MSP Tutorial 20: MIDI Sampler Control
Control
ioscbank~
Interpolating oscillator bank

Description
ioscbank~ is an interpolated oscillator bank with signal inputs to set oscillator frequency and magnitude.

Arguments
Name Units Type Opt Description
number-of- int opt The number of oscillators.
oscillators
frequency- samples int opt The number of samples across which frequency smoothing is done.
smoothing-factor
amplitude- samples int opt The number of samples across which amplitude smoothing is done.
smoothing-factor

Messages
int inlet-specific-parameter- In left inlet: Sets the frequency of the oscillator whose index is currently
settings [int] referenced to the current floating-point value of the signal. The default value is 0.

In 2nd inlet: Sets the magnitude (amplitude) of the oscillator whose index is
currently referenced.

In 4th inlet: Sets the index of the oscillator currently being referenced.
float inlet-specific-parameter- In left inlet: Sets the frequency of the oscillator whose index is currently
settings [float] referenced to the current floating-point value of the signal. The default value is 0.

In 2nd inlet: Sets the magnitude (amplitude) of the oscillator whose index is
currently referenced.

In 3rd inlet: If framesync is enabled using the framesync 1 message, a value in


the range 0-1.0 sets the phase of the oscillator currently being referenced.

In 4th inlet: Sets the index of the oscillator currently being referenced.
clear The word clear sets the frequency of all oscillators to zero and zeros all
amplitudes.
copybuf buffer-object-name In left inlet: The word copybuf, followed by a symbol that specifies a buffer,
[symbol] copies 4096 samples from the buffer into the ioscbank~ object's internal
offset (samples) [int] wavetable. An optional second integer argument specifies the position in the buffer
at which samples are loaded (offset).
framesync behavioral-flag (0 or The word framesync, followed by a non-zero number, enables frame synchronous
nonzero) [int] operation. When frame synchronous operation is enabled, a given index's values
will only change or begin their interpolated ramps to the next value when the
index input signal is 0 (or once per n sample frame). Otherwise, a given index's
values will change or begin their interpolated ramps to the next value when the
index input signal is equal to that index. The default is off.
freqsmooth frequency-smoothing- The word freqsmooth, followed by a number, sets the number of samples across
factor (samples) [int] which frequency smoothing is done. The default is 1 (no smoothing).
magsmooth amplitude-smoothing- The word magsmooth, followed by a number, sets the number of samples across
factor (samples) [int] which magnitude (amplitude) smoothing is done on an oscillator. The default is 0
(no amplitude smoothing).
set frequency [float] The word set, followed by pairs of floating-point values, sets the frequency and
amplitude [float] amplitude of an oscillator in the oscillator bank. A list of n pairs will set the first n
oscillators in the ioscbank~ object and zero the amplitude of all others.
signal In left inlet: Sets the frequency of the oscillator whose index is currently
referenced to the current floating-point value of the signal. The default value is 0.

In 2nd inlet: Sets the magnitude (amplitude) of the oscillator whose index is
currently referenced.

In 3rd inlet: If framesync is enabled using the framesync 1 message, a signal in


the range 0-1.0 sets the phase of the oscillator currently being referenced.

In 4th inlet: Sets the index of the oscillator currently being referenced.
silence The word silence zeros the amplitude of all the oscillators.
size number-of-oscillators The word size, followed by a number, sets the number of oscillators. The default
[int] is 64. The maximum number of oscillators is set by the argument first argument to
the object.

Information for box attributes common to all objects

Output
signal: A waveform consisting of the sum of the specified frequencies and amplitudes.

Examples

ioscbank~ lets you sound multiple interpolated oscillators with one object

See Also
Name Description
oscbank~ Non-interpolating oscillator bank
kink~
Distort a sawtooth waveform

Description
kink~ takes phasor~ values and distorts them according to a slope factor. If the input times the slope is less than 0.5, that value
is output. Otherwise, a complentary slope is used, equal to 0.5 at the same input value but equal to 1 when the input is 1. This
creates a bend or "kink" in the phase waveform when the slope is not equal to 1.

Arguments
Name Units Type Opt Description
slope-multiplier float opt Sets the default slope multiplier. If a signal is attached to the right inlet, this
argument is ignored.

Messages
float slope-multiplier [float] In right inlet: The multiplier that affects the slope of the output between an output
(Y) value of 0 and 0.5. After the output reaches 0.5, the waveform will increase to 1
so that the entire output moves from 0 to 1 in the same period of time as the
input. A slope multiplier of 1(the default) produces no distortion Slope multipliers
below 1 have a slower rise to 0.5 than the input, and slope multipliers above 1 have
a faster rise to 0.5 than the input. If a signal is attached to the right inlet, float
input is ignored.
signal In left inlet: The input to kink~ should be a sawtooth waveform output from a
phasor~ object that repeatedly goes from 0 to 1.

In right inlet: The multiplier that affects the slope of the output between an output
(Y) value of 0 and 0.5. After the output reaches 0.5, the waveform will increase to 1
so that the entire output moves from 0 to 1 in the same period of time as the
input. A slope multiplier of 1(the default) produces no distortion Slope multipliers
below 1 have a slower rise to 0.5 than the input, and slope multipliers above 1 have
a faster rise to 0.5 than the input.

Information for box attributes common to all objects

Output
signal: The output of kink~ should be fed to the right inlet of cycle~ (at zero frequency) to produce a distorted sine wave (a
technique known as phase distortion synthesis). As the slope multiplier in the right inlet of kink~ deviates from 1, additional
harmonics are introduced into the waveform output of cycle~. If the slope multiplier is rapidly increased and then decreased
using a line~, the output of cycle~ may resemble an attack portion of an instrumental sound.

Examples

Typical use of kink~ between phasor~ and cycle~


See Also
Name Description
phasor~ Generate sawtooth signals
triangle~ Triangle/ramp wavetable
<~
Is less than, comparison of two signals

Description
<~ outputs a 1 signal when the left input is less-than the right input and a 0 when it is greater-than or equal-to the right input.
The right input can be a signal or a float.

Arguments
Name Units Type Opt Description
initial- float opt Sets an initial comparison value for the signal coming into the left inlet. 1 is sent
comparison-value or int out if the signal is less than the argument; otherwise, 0 is sent out. If a signal is
connected to the right inlet, the argument is ignored. If no argument is present,
and no signal is connected to the right inlet, the initial value is 0 by default.

Messages
int comparison-value [int] In right inlet: A number to be used for comparison with the signal coming into the
left inlet. If a signal is also connected to the right inlet, a float or int is ignored.
float comparison-value [float] In right inlet: A number to be used for comparison with the signal coming into the
left inlet. If a signal is also connected to the right inlet, a float or int is ignored.
signal In left inlet: The signal is compared to a signal coming into the right inlet, or a
constant value received in the right inlet. If it is less than the value in the right
inlet, 1 is sent out; otherwise, 0 is sent out.

In right inlet: The signal is used for comparison with the signal coming into the left
inlet.

Information for box attributes common to all objects

Output
signal: If the signal in the left inlet is less than the value in the right inlet, 1 is sent out; otherwise, 0 is sent out.

Examples

Convert any signal to only 1 and 0 values

See Also
Name Description
<=~ Is less than or equal to, comparison of two signals
>~ Is greater than, comparison of two signals
>=~ Is greater than or equal to, comparison of two signals
==~ Is equal to, comparison of two signals
!=~ Not equal to, comparison of two signals
<=~
Is less than or equal to, comparison of two signals

Description
<=~ outputs a 1 signal when the left input is less-than or equal-to the right input and a 0 when it is less-than the right input. The
right input can be a signal or a float.

Arguments
Name Units Type Opt Description
initial- number opt Sets an initial comparison value for the signal coming into the left inlet. 1 is sent
comparison-value out if the signal is less than or equal to the argument; otherwise, 0 is sent out. If a
signal is connected to the right inlet, the argument is ignored. If no argument is
present, and no signal is connected to the right inlet, the initial value is 0 by
default.

Messages
int comparison-value [int] In right inlet: A number to be used for comparison with the signal coming into the
left inlet. If a signal is also connected to the right inlet, a float or int is ignored.
float comparison-value [float] In right inlet: A number to be used for comparison with the signal coming into the
left inlet. If a signal is also connected to the right inlet, a float or int is ignored.
signal In left inlet: The signal is compared to a signal coming into the right inlet, or a
constant value received in the right inlet. If it is less-than or equal-to the value in
the right inlet, 1 is sent out; otherwise, 0 is sent out.

In right inlet: The signal is used for comparison with the signal coming into the left
inlet.

Information for box attributes common to all objects

Output
signal: If the signal in the left inlet is less than or equal to the value in the right inlet, 1 is sent out; otherwise, 0 is sent out.

Examples

See Also
Name Description
<~ Is less than, comparison of two signals
>~ Is greater than, comparison of two signals
>=~ Is greater than or equal to, comparison of two signals
==~ Is equal to, comparison of two signals
!=~ Not equal to, comparison of two signals
levelmeter~
Visual RMS level indicator

Description
Use the levelmeter~ when you need a signal level-meter with ballistics. The meter~ object provides metering in a simpler and
more compact form.

Arguments
None.

Messages
bang The RMS amplitude most recently calculated for an input signal is displayed and
output by the needle of the on-screen level meter.
int input [int] An int sets dB value displayed and output by levelmeter~.
clear The word clear clears the FB delay stage memory.
mode operational-mode [int] The word mode followed by an integer between 0 and 5 will set the operational
mode of levelmeter~ as follows:
0 = "fast"(no ballistics or dB-offset)
1 = "VU" (attack = 330; release = 330; dB-offset = -20)
2 = "DIN 45 406(IEC PPM type IIb)"(attack = 10; release = 1500; dB-offset = -14)
3 = "BBC (IEC PPM type IIa)" (attack = 10; release = 3000; dB-offset = -14)
4 = "Nordic (IEC PPM type I)" (attack = 5; release = 2000; dB-offset = -14)
5 = "EBU Digital" (attack = 0; release = 1500; dB-offset = -14)
(Object defaults to "fast" mode.)
signal The RMS amplitude of the incoming signal is displayed by the needle of the on-
screen level meter.

Attributes
Name Type g/s Description
attack int The word attack, followed by a number, sets the levelmeter~ object attack time,
def.:0 in milliseconds. The default is 0.
bgcolor float Sets the RGBA color values for the background color of the levelmeter~ object.
def.:0.94267 0.94267
0.94267 1.
bordercolor float Sets the RGBA values for the border color of the levelmeter~ object.
def.:0. 0. 0. 1.
coolcolor float Sets the RGBA values for the color for the lower cool range of the levelmeter~
def.:0.70588 0.82353 object.
0.39126 1.
fgcolor float Sets the RGBA color values for the foreground color of the levelmeter~ object
def.:0.78542 0.78542
0.78542 1.
hotcolor float Sets the RGBA values for the color for the upper-middle hot range of the
def.:0.86275 0.39126 levelmeter~ object.
0.39126 1.
interval int Sets the update time interval in milliseconds, of the levelmeter~ display. The
def.:20 minimum update interval is 10 milliseconds, the maximum is 2 seconds, and the
default is 100 milliseconds. This message also sets the rate at which levelmeter~
sends out the peak value received in that time interval.
markercolor float Sets the RGBA values for the markers of the levelmeter~ object.
def.:0. 0. 0. 1.
markers int Sets the locations of the small dots along the colored stripe on the four floating-
def.:-48 -36 -24 -12 - point numbers in the range 0.-1.0, object. Up to 8 markers may be diaplayed.
6 0 6 12
markersused int Specifies the number of markers used in the levelmeter~ object's display.
def.:8
needlecolor float Sets the RGBA values for the color for the needle of the levelmeter~ object.
def.:0. 0. 0. 1.
offset int Sets the levelmeter~ object display's deciBel offset.
def.:0
overloadcolor float Sets the RGBA values for the color for the upper overload range of the
def.:1. 0. 0. 1. levelmeter~ object.
range int Sets the display range of the levelmeter~ object. The default range is -40 dB to 12
def.:-48 12 dB.
release int Sets the levelmeter~ object release time, in milliseconds. The default is 0.
def.:0
rounded int Sets the roundness, in pixels, of the levelmeter~ object box. The default is 6.
def.:8
tepidcolor float Sets the RGBA values for the color for the lower-middle tepid range of the
def.:0.86275 0.78431 levelmeter~ object.
0.39126 1.
warmcolor float Sets the RGBA values for the color for the middle warm range of the
def.:0.86275 0.58824 levelmeter~ object.
0.31373 1.

Information for box attributes common to all objects

Output
float: The RMS (root mean square) value in deciBels of the signal for the current update interval is sent out the outlet when audio
processing is on.

Examples

levelmeter~ displays and sends out the RMS amplitude of a signal in deciBels

See Also
Name Description
average~ Multi-mode signal average
meter~ Visual peak level indicator
scope~ Visualize an audio signal
MSP Tutorial 23: Viewing Signal MSP Tutorial 23: Viewing Signal Data
Data
line~
Linear ramp generator

Description
Use the line~ object to generate a signal ramp or envelope. It uses the Max time format syntax; envelope times can be either
single valued fixed or tempo-relative.

Arguments
Name Units Type Opt Description
initial-value float or int opt Sets an initial value for the signal output. The default value is 0.

Messages
int target-value/delta-time [int] In left inlet: The number is the target value, to be arrived at in the time specified
by the number in the right inlet. If no time has been specified since the last target
value, the time is considered to be 0 and the output signal jumps immediately to
the target value.

In right inlet: The number is the time, in milliseconds, in which the output signal
will arrive at the target value.
float target-value/delta-time In left inlet: The number is the target value, to be arrived at in the time specified
[float] by the number in the right inlet. If no time has been specified since the last target
value, the time is considered to be 0 and the output signal jumps immediately to
the target value.

In right inlet: The number is the time, in milliseconds, in which the output signal
will arrive at the target value.
list target-value [float] In left inlet: The first number specifies a target value and the second number
delta-time [number] specifies a total amount of time (in milliseconds) in which line~ should reach the
target value. In the specified amount of time, line~ generates a ramp signal from
its current value to the target value.
line~ accepts up to 128 target-time pairs in a list, to generate compound ramps.
(An example would be 0 1000 1 1000, which would go from the current value to
0 in a second, then to 1 in a second.) Once one of the ramps has reached its target
value, the next one starts. A subsequent list, float, or int in the left inlet clears all
ramps yet to be generated.

In right inlet: A list may be used to specify time in one of the Max time formats.
anything target-value [float] In left inlet: The first number specifies a target value and the second number
delta-time [number] specifies a total amount of time (in milliseconds) in which line~ should reach the
target value. In the specified amount of time, line~ generates a ramp signal from
its current value to the target value.
line~ accepts up to 128 target-time pairs in a list, to generate compound ramps.
(An example would be 0 1000 1 1000, which would go from the current value to
0 in a second, then to 1 in a second.) Once one of the ramps has reached its target
value, the next one starts. A subsequent list, float, or int in the left inlet clears all
ramps yet to be generated.

In right inlet: A list may be used to specify time in one of the Max time formats.
pause In left inlet: Pauses the internal ramp but does not change the target value nor
clear pending target-time pairs. line~ will continue outputting whatever value was
its current value when the pause message was received, until either it receives a
resume message or until a new ramp is input.
stop In left inlet: Stops the internal ramp and clears pending target-time pairs. line~
will continue outputting whatever value was its current value when the stop
message was received, resetting its target value to that value.
resume In left inlet: Resumes the internal ramp and subsequent pending target-time pairs
if the line~ object was paused as a result of the pause message.

Information for box attributes common to all objects

Output
bang: Out right outlet: When line~ has finished generating all of its ramps, bang is sent out.
signal: Out left outlet: The current target value, or a ramp moving toward the target value according to the currently stored value
and the target time.

Examples

Linearly changing signal, or a function made up of several line segments

See Also
Name Description
adsr~ ADSR envelope generator
click~ Create an impulse
curve~ Exponential ramp generator
transport Control a master clock
zigzag~ Linked list function editor
MSP Tutorial 2: Adjustable MSP Tutorial 2: Adjustable Oscillator
Oscillator
log~
Logarithm of a signal

Description
Use the log~ object to output a signal composed of the logarithms of its input values. You can specify the logarithmic base.

Arguments
Name Units Type Opt Description
logarithmic-base number opt Sets the base of the logarithm. The default value is 0.

Messages
signal In left inlet: log~ sends out a signal that is the logarithm of the input signal, to the
base specified by the typed-in argument or the value most recently received in the
right inlet. If a value in the signal is less than or equal to 0, log~ sends out a value
of 0.00000001.

Information for box attributes common to all objects

Output
signal: The logarithm of the input signal to the base specified by the initial argument or the value most recently received in the
right inlet.

Examples

Logarithm of a signal, to a specified base can be used for creating curves

See Also
Name Description
pow~ Signal power function
curve~ Exponential ramp generator
sqrt~ Square root of a signal
lookup~
Transfer function lookup table

Description
lookup~ allows you to use a table of samples (buffer~ object) to do waveshaping on a signal, in which the Y values of an input
signal are used as X values to look up new signal values. Input values of -1 to +1 are mapped to table values between 0 (or the
specified sample offset) and the size of the table.

Arguments
Name Units Type Opt Description
buffer-name symbol Names the buffer~ object whose sample memory is used by lookup~ for table
lookup.
sample-offset int opt After the buffer~ name, you may specify the sample offset in the sample memory
of the buffer~ used for a signal value of -1. The default offset is 0. The offset value
is followed by an optional table size that defaults to 512. Note that the actual
lookup~ table size is equal to the table size (set using the second argument)
minus the offset (set using first argument), so raising the offset value will decrease
the table size. The lookup~ object always uses the first channel in a multi-channel
buffer~. The

Messages
int offset [int] The settings of offset and table size can be changed with a number in the middle
table-size [int] or right inlets. If a signal is connected to one of these inlets, a number in the
corresponding inlet is ignored.
float offset [int] The settings of offset and table size can be changed with an number in the middle
table-size [int] or right inlets. If a signal is connected to one of these inlets, a number in the
corresponding inlet is ignored.
(mouse) Double-clicking on lookup~ opens an editing window where you can vieW the
contents of its associated buffer~ object.
set buffer-name [symbol] The word set, followed by a symbol, changes the associated buffer~ object.
signal In left inlet: Signal values are mapped by amplitude to values stored in a buffer~.
Each sample in the incoming signal within the range -1 to 1 is mapped to a
corresponding value in the current table size number of samples of the buffer~.
Signal values between -1 and 0 are mapped to the first half of the total number of
samples after the current sample offset. Signal values between 0 and 1 are mapped
to the next half of the samples. Input amplitude exceeding the range from -1 to 1
results in an output of 0.

In middle inlet: Sets the offset into the sample memory of a buffer~ used to map
samples coming in the left inlet. The sample at the specified offset corresponds to
an input value of -1.

In right inlet: Sets the number of samples in a buffer~ used for the table. Samples
coming in the left inlet between -1 and 1 will be mapped by amplitude to the
specified range of samples. The default value is 512. lookup~ changes the table
size before it computes each vector but not within a vector. It uses the first sample
in a signal vector coming in the right inlet as the table size.

Information for box attributes common to all objects

Output
signal: Each sample in the incoming signal within the range -1 to 1 is mapped to a corresponding position in the current table
size number of samples of the named buffer~ object, and the stored value is sent out.
Examples

See Also
Name Description
buffer~ Store audio samples
peek~ Read and write sample values
MSP Tutorial 12: Waveshaping MSP Tutorial 12: Waveshaping
lores~
Resonant lowpass filter

Description
lores~ implements an inexpensive lowpass with an adjustment that lets you add a specified resonance. The middle inlet sets a
kind of cutoff frequency, but the sharpness of the filter depends on the resonance passed in through the right inlet (0 is a little bit
sharp and 1 as sharp as possible).

Arguments
Name Units Type Opt Description
cutoff number opt A number sets the initial cutoff frequency. The default value is 0. If a signal is
connected to the inlet, the argument corresponding to the inlet is ignored.
response number opt A number sets the filter resonance. The default value is 0. If a signal is connected
to the inlet, the argument corresponding to the inlet is ignored.

Messages
int cutoff-frequency/resonance An int can be sent in the middle or right inlets to change the cutoff frequency or
[int] resonance. If a signal is connected one of the inlets, a number received in that inlet
is ignored.
float cutoff-frequency/resonance float can be sent in the middle or right inlets to change the cutoff frequency or
[float] resonance. If a signal is connected one of the inlets, a number received in that inlet
is ignored.
clear Clears the filter's memory. Since lores~ is a recursive filter, this message may be
necessary to recover from blowups.
signal In left inlet: Any signal to be filtered.

In middle inlet: Sets the lowpass filter cutoff frequency.

In right inlet: Sets a "resonance factor" between 0(minimum resonance) and


1(maximum resonance). Values very close to 1 may produce clipping with certain
types of input signals.

Information for box attributes common to all objects

Output
signal: The filtered input signal. The equation of the filter is

yn = scale * xn - c1 * yn-1 + c2 * yn-2

where scale, c1, and c2 are parameters calculated from the cutoff frequency and resonance factor.

Examples
Specify cutoff frequency and resonance of lowpass filter

See Also
Name Description
biquad~ Two-pole, two-zero filter
buffir~ buffer-based FIR filter
comb~ Apply a comb filter effect
cross~ Third-order crossover filter
onepole~ Single-pole lowpass filter
svf~ State-variable filter with simultaneous outputs
reson~ Resonant bandpass filter
Audio Filtering Audio Filtering
matrix~
Signal routing and mixing matrix

Description
matrix~ is an array of signal connectors and mixers (adders). It can have any number of inlets and outlets. Signals entering at
each inlet can be routed to one or more of the outlets, with a variable amount of gain. If an outlet is connected to more than one
inlet, its output signal is the sum of the signals from the inlets.

Arguments
Name Units Type Opt Description
inlets int The first argument specifies the number of inlets.
outlets int The second argument specifies the number of outlets.
connection-gain float opt If a float value is provided as a third argument, matrix~ operates in its non-binary
mode. The argument sets the gain value that will be used when connections are
created.

Messages
list inlet-to-outlet indices In left inlet: A list of three ints may be used to connect inlets and outlets when the
[list] matrix~ object is in binary mode. The first int specifies the inlet, the second int
specifies the outlet, and a third int is used to specify connection or disconnection.
If the third int is nonzero value, the inlet of the first int will be connected to the
outlet specified by the second int. A zero value for the third int in the list
disconnects the inlet-outlet pair.

If the matrix~ object is operating in non-binary mode, A list of two ints followed
by a float sets the gain of the connection between inlet i and outlet o to the value
specified by the float.

Note: To specify the gain of individual connections, you must use three-element
list messages rather than the connect message. Connections formed with the
connect message always have a gain specified by the third argument initially given
to the matrix~ object. However, subsequent list messages can alter the gain of
connections formed with the connect message. The addition of an optional fourth
element to the list message can be used to specify a ramp time, in milliseconds, for
the individual connection (e.g., 1 2 .8 500 would connect the first inlet to the
second outlet and specify a gain of .8 and a ramp time of .5 seconds).
clear In left inlet: The word clear removes all connections.
connect inlet-to-outlet indices In left inlet: The word connect, followed by one or more ints, will connect any
[list] inlet specified by the first int to the outlet or outlets specified by the remaining ints
in the list. Inlets and outlets are numbered from left to right, starting at zero. For
example, the message connect 0 0 1 would connect the first inlet from the left to
the leftmost outlet and the second outlet from the left.
disconnect inlet-to-outlet indices In left inlet: The word disconnect, followed by one or more ints, will disconnect
[list] any inlet specified by the first int to the outlet or outlets specified by the remaining
ints in the list.
dump In left inlet: The word dump causes the current state of all matrix~ object
connections to be sent out the rightmost outlet of the object in the form of a list
for each connection. The list consists of two numbers which specify the inlet and
outlet, followed by a float which specifies the gain for the connection. Note that in
non-binary mode the current gains are not necessarily the same as the target
gains of all matrix~ object connections, since a connection's gain can ramp to its
new target over time.
dumptarget In left inlet: The word dumptarget causes the target state of all matrix~ object
connections to be sent out the rightmost outlet of the object in the form of a list
for each connection. The list consists of two numbers which specify the inlet and
outlet, followed by a float which specifies the target gain for the connection. Note
that in non-binary mode the target gains are not necessarily the same as the
current gains, which can be accessed with the dump message.
print In left inlet: The word print causes the current state of all matrix~ object
connections to be printed in the Max window in the form of a list for each
connection. The list consists of two numbers which specify the inlet and outlet,
followed by a float which specifies the gain for the connection.

Attributes
Name Type g/s Description
ramp int Ramp Time (ms)

Information for box attributes common to all objects

Output
list: Out right outlet: A set of lists describing the current or target state of all matrix~ object connections will be sent out the right
outlet in response to a dump or dumptarget message.
signal: The output signals for each outlet are the sum of their connected inputs, scaled by the gain values of the connections.

Examples

Multichannel audio routing

See Also
Name Description
gate~ Route a signal to one of several outlets
matrixctrl Matrix switch control
receive~ Signals can be received from any loaded patcher, without patch cords
router Route messages to multiple locations
selector~ Assign one of several inputs to an outlet
send~ Send signals without patch cords
maximum~
Compare two signals, output the maximum

Description
maximum~ outputs a signal which is the maximum of two input signals.

Arguments
Name Units Type Opt Description
initial- number opt Sets an initial comparison value for the signal coming into the left inlet. If a signal
comparison-value is connected to the right inlet, the argument is ignored.

Messages
int comparison-value [int] In right inlet: A number to be used for comparison with the signal coming into the
left inlet. If a signal is also connected to the right inlet, a float or int is ignored.
float comparison-value [float] In right inlet: A number to be used for comparison with the signal coming into the
left inlet. If a signal is also connected to the right inlet, a float or int is ignored.
signal In left inlet: The signal is compared to a signal coming into the right inlet, or a
constant value received in the right inlet. The greater of the two values is sent out
the outlet.

In right inlet: The signal is used for comparison with the signal coming into the left
inlet.

Information for box attributes common to all objects

Output
signal: The greater of the two signal values received in the left and right inlets is sent out.

Examples

Find the maximum of two signals

See Also
Name Description
<=~ Is less than or equal to, comparison of two signals
>~ Is greater than, comparison of two signals
>=~ Is greater than or equal to, comparison of two signals
==~ Is equal to, comparison of two signals
!=~ Not equal to, comparison of two signals
minimum~ Compare two signals, output the minimum
meter~
Visual peak level indicator

Description
Use the meter~ object to monitor any signal in the range -1 and 1 (other signals should be scaled first).

Arguments
None.

Messages
int input-peak-value [int] Converted to float. A value will set the meter to react as though a signal with equal
amplitude peak-value has been passed to its input. Corresponding LEDs will light
up and the peak-level value will be passed out the outlet (0.0 will show silence, 0.0
through 1.0 will light up to any but the overload LED, and anything above 1.0 will
light all LEDs including overload).
float input-peak-value [float] A float value will set the meter to react as though a signal with equal amplitude
peak-value has been passed to its input. Corresponding LEDs will light up and the
peak-level value will be passed out the outlet (0.0 will show silence, 0.0 through
1.0 will light up to any but the overload LED, and anything above 1.0 will light all
LEDs including overload).
(mouse) When the patcher window is unlocked, you can reorient a meter~ from horizontal
to vertical by dragging its resize area and changing its shape.
signal The peak amplitude of the incoming signal is displayed by the LEDs of the on-
screen level meter.

Attributes
Name Type g/s Description
bgcolor float Sets the RGBA values for the background color of the meter~ object.
bordercolor float Sets the RGBA values for the border color of the meter~ object.
coldcolor float Sets the RGBA values for the cold signal color of the meter~ object.
dbperled int Sets the amount of signal level in deciBels represented by each LED. By default
def.:3 each LED represents a 3dB change in volume from its neighboring LEDs.
hotcolor float Sets the RGBA values for the LED color for the upper "hot" range of the meter~
object.
interval int Sets the update-time interval, in milliseconds, of the meter~ display. The
def.:50 minimum update-interval is 10 milliseconds, the maximum is 2 seconds, and the
default is 50 milliseconds. This message also sets the rate at which meter~ sends
out the peak value received in that time interval.
nhotleds int Sets the total number "hot" warning LEDs displayed on the meter~ object
def.:3 (corresponding to the color set by the rgba2 message).
ntepidleds int Sets the total number "tepid" mid-range LEDs displayed on the meter~ object
def.:3 (corresponding to the color set by the rgba5 message).
numleds int The word numleds, followed by a number between 10 and 20, sets the total
def.:12 number of LEDs displayed on the meter~ object. The range is 10-20 LEDs.
nwarmleds int Sets the total number "warm" lower-mid-range LEDs displayed on the meter~
def.:3 object (corresponding to the color set by the rgba4 message).
overloadcolor float Sets the RGBA values for the LED color for the "over" indicator of the meter~
object.
tepidcolor float Sets the RGBA values for the LED color for the lower-middle "tepid" range of the
meter~ object.
warmcolor float Sets the RGBA values for the LED color for upper-middle "warm" range of the
meter~ object.

Information for box attributes common to all objects

Output
float: The peak (absolute) value received in the previous update interval is sent out the outlet when audio processing is on.

Examples

meter~ displays and sends out the peak amplitude of a signal

See Also
Name Description
average~ Multi-mode signal average
scope~ Visualize an audio signal
MSP Tutorial 23: Viewing Signal MSP Tutorial 23: Viewing Signal Data
Data
minimum~
Compare two signals, output the minimum

Description
minimum~ outputs a signal which is the minimum of two input signals.

Arguments
Name Units Type Opt Description
initial- number opt Sets an initial comparison value for the signal coming into the left inlet. If a signal
comparison-value is connected to the right inlet, the argument is ignored.

Messages
int comparison-value [int] In right inlet: A number to be used for comparison with the signal coming into the
left inlet. If a signal is also connected to the right inlet, a float or int is ignored.
float comparison-value [float] In right inlet: A number to be used for comparison with the signal coming into the
left inlet. If a signal is also connected to the right inlet, a float or int is ignored.
signal In left inlet: The signal is compared to a signal coming into the right inlet, or a
constant value received in the right inlet. The lesser of the two values is sent out
the outlet.

In right inlet: The signal is used for comparison with the signal coming into the left
inlet.

Information for box attributes common to all objects

Output
signal: The lesser of the two signal values received in the left and right inlets is sent out.

Examples

Find the minimum of two signals

See Also
Name Description
<=~ Is less than or equal to, comparison of two signals
>~ Is greater than, comparison of two signals
>=~ Is greater than or equal to, comparison of two signals
==~ Is equal to, comparison of two signals
!=~ Not equal to, comparison of two signals
maximum~ Compare two signals, output the maximum
minmax~
Compute minimum/maximum signal values

Description
minmax~ computes the minimum and maximum values of an input signal and outputs signals which are the maximum signal
and the minimum signal as well as outputs of the minimum and maximum floats.

Arguments
None.

Messages
bang Sends floating-point values corresponding to the minimum and maximum signal
values out the 3rd and 4th outputs.
reset Resets the current minimum and maximum values to the default (0).
signal Signal to be evaluated for minimum and maximum values.

Information for box attributes common to all objects

Output
float: Out 3rd outlet: When minmax~ receives a bang message, a floating-point value which corresponds to the minimum signal
value received since startup or the last reset message is output.

Out 4th outlet: When minmax~ receives a bang message, a floating-point value which corresponds to the maximum signal value
received since startup or the last reset message is output.
signal: Out 1st outlet: Signal value which corresponds to the minimum signal value received since startup or the last reset
message.

Out 2nd outlet: Signal value which corresponds to the maximum signal value received since startup or the last reset message.

Examples

Find the hi/low peaks of a signal

See Also
Name Description
meter~ Visual peak level indicator
peakamp~ Report the maximum amplitude of a signal
snapshot~ Convert signal values to numbers
-~
Signal subtraction

Description
Use the -~ object to perform signal subtraction (to output a signal which is the difference between two signals).

Arguments
Name Units Type Opt Description
initial- number opt Sets an initial amount to subtract from the signal coming into the left inlet. If a
subtraction-value signal is connected to the right inlet, the argument is overidden. If no argument is
present, and no signal is connected to the right inlet, the initial value is 0 by
default.

Messages
int input [int] In left inlet: Subtracts the signal coming into the right inlet from this value. If a
signal is also connected to the left inlet, a float or int is ignored.

In right inlet: An amount to subtract from the signal coming into the left inlet. If a
signal is also connected to the right inlet, a float or int is ignored.
float input [float] In left inlet: Subtracts the signal coming into the right inlet from this value. If a
signal is also connected to the left inlet, a float or int is ignored.

In right inlet: An amount to subtract from the signal coming into the left inlet. If a
signal is also connected to the right inlet, a float or int is ignored.
signal In left inlet: The signal coming into the right inlet or a constant value received in
the right inlet is subtracted from this signal.

In right inlet: The signal is subtracted from the signal coming into the left inlet, or
a constant value received in the left inlet.

Information for box attributes common to all objects

Output
signal: The difference between the two inputs.

Examples

Negative DC offset... Subtraction used to invert a signal before adding it in

See Also
Name Description
+~ Add signals
!-~ Signal subtraction (inlets reversed)
%~
Divide two signals, output the remainder

Description
%~ is a signal remainder operator. If signals are connected to both inlets, the left signal is divided by the right signal, and the
remainder is output. If a signal is only connected to left inlet, it is divided to the argument or a float in the right inlet. Note that
multiple signals in the same inlet add together automatically.

Arguments
Name Units Type Opt Description
initial-divisor number opt Sets an initial value by which to divide the signal coming into the left inlet. If a
signal is connected to the right inlet, the argument is ignored. If no argument is
present, and no signal is connected to the right inlet, the initial value is 1 by
default.

Messages
int dividend/divisor [int] In left inlet: The number is divided by the signal coming into the right inlet. If a
signal is also connected to the left inlet, a float or int is ignored.

In right inlet: A number by which to divide the signal coming into the left inlet. If a
signal is also connected to the right inlet, a float or int is ignored.
float dividend/divisor [float] In left inlet: The number is divided by the signal coming into the right inlet. If a
signal is also connected to the left inlet, a float or int is ignored.

In right inlet: A number by which to divide the signal coming into the left inlet. If a
signal is also connected to the right inlet, a float or int is ignored.
signal In left inlet: The signal is divided by a signal coming into the right inlet, or a
constant value received in the right inlet, and the remainder is sent out the outlet.

In right inlet: The signal is used as the divisor, to be divided into the signal coming
into the left inlet, or the constant value received in the left inlet.

Information for box attributes common to all objects

Output
signal: When the two signals in the inlets are divided, the remainder is sent out the outlet. % is called the modulo operator.

Examples

See Also
Name Description
!/~ Divide input from a number
/~ Divide one signal by another
mstosamps~
Convert milliseconds to samples

Description
Use the mstosamps~ object to convert an incoming signal carrying a millisecond value and output a signal which converts those
millisecond values to a number of samples (at the current sampling rate).

Arguments
None.

Messages
int millisecond-value [int] Millisecond values received in the inlet are converted to a number of samples at
the current sampling rate and sent out the object's right outlet. The output might
contain a fractional number of samples. For example, at 44.1 kHz sampling rate,
3.2 milliseconds is 141.12 samples.
float millisecond-value [float] Millisecond values received in the inlet are converted to a number of samples at
the current sampling rate and sent out the object's right outlet. The output might
contain a fractional number of samples. For example, at 44.1 kHz sampling rate,
3.2 milliseconds is 141.12 samples.
signal Incoming millisecond values in the signal are converted to a number of samples at
the current sampling rate and output as a signal out the mstosamps~ object's left
outlet. The output may contain a fractional number of samples.

Information for box attributes common to all objects

Output
float: Out right outlet: The number of samples corresponding to the millisecond value received as a float or int in the inlet.
signal: Out left outlet: The number of samples corresponding to the millisecond values in the input signal.

Examples

Time expressed in milliseconds comes out expressed in samples

See Also
Name Description
dspstate~ Report current DSP settings
sampstoms~ Convert time from samples to milliseconds
mtof~
Convert a MIDI note number to frequency at signal rate

Description
Use the mtof~ object to perform signal-rate MIDI-to-Frequency conversion.

Arguments
None.

Messages
signal A signal representing a MIDI note number value (from 0 to 127). The
corresponding frequency is output as a signal.

Attributes
Name Type g/s Description
base float Sets the "base frequency" used when calculating frequency values (e.g., A = 440.).
The default is 440.

Information for box attributes common to all objects

Output
signal: The frequency corresponding to the received MIDI pitch value, output as a signal.

Examples

Design a vibrato that has an even width with respect to perceived pitch

See Also
Name Description
expr Evaluate a mathematical expression
ftom Convert frequency to a MIDI note number
ftom~ Convert frequency to MIDI note numbers at signal-rate
mtof Convert a MIDI note number to frequency
MSP Tutorial 19: MIDI Synthesizer MSP Tutorial 19: MIDI Synthesizer Control
Control
mute~
Disable signal processing in a subpatch

Description
mute~ provides an easy way to disable only the signal objects in a subpatcher. (An alternative is to use pcontrol, but this disables
all objects (i.e. MIDI) and is slightly slower.)

Arguments
None.

Messages
int behaviorial-flag [int] 1 turns off the signal processing in all objects contained in the subpatch connected
to the mute~ object's outlet, 0 turns it back on.
list enable-flag [int] Sending the list 1 1 to the mute~ object will mute any subpatchers of the patcher
subpatcher-flag [int] object to which the message is sent. Similarly, sending the list 0 1 to the mute~
object will unmute any subpatchers of the patcher object.

Information for box attributes common to all objects

Output
Signal-Processing: Connect the mute~ object's outlet to any inlet of a subpatch you wish to control. You can connect mute~ to
as many subpatch objects as you wish.

Examples

You can mute all processing in any patcher or other subpatch

See Also
Name Description
begin~ Define a switchable part of a signal network
pass~ Eliminate noise in a muted subpatcher
MSP Tutorial 5: Turning Signals MSP Tutorial 5: Turning Signals On and Off
On and Off
mxj~
Java in MSP

Description
The mxj~ object (and its Max equivalent mxj) instantiate specially-written Java classes and acts as a Max-level peer object,
passing data that originates in Max to the Java object and vice versa.

Arguments
Name Units Type Opt Description
Java-class symbol The mxj~ object must be given the name of a valid Java class as the first
argument. The Java class file must exist somewhere within the classpath, and it
must be a class that was designed for use with the mxj~ object (the class must
subclass com.cycling74.max.MaxObject). The number of inlets that an instance of
mxj~ creates and the messages that it will respond to are determined by
declarations made in the peer Java class.
attributes list The mxj~ object supports the definition of attributes within the Java code for a
peer class. The attributes that are settable at the time of instantiation using the @
paradigm. For instance, if a particular class Foo defined an integer attribute called
intBar, one could create an instance of the class with the attribute set to the value
74 by typing mxj~ Foo @intBar 74 in an object box.

Messages
bang Function depends on Java class instantiated
int input [int] Function depends on Java class instantiated
float input [float] Function depends on Java class instantiated
list input [list] Function depends on Java class instantiated
anything input [list] Function depends on Java class instantiated
benchmark benchmark-flag [int] The word benchmark, followed by a zero or one and a number that specifies a
post-interval [int] posting interval (number of executions of the perform method), disables
benchmarking the mxj~ object's perform method, posting into the Max Window.
The default is zero (disabled)
(mouse) Double-clicking with the mouse on the mxj~ object displays its contents as text in
an editing window which the user can modify.
exceptioncheck exception-flag [int] The word exceptioncheck, followed by a zero or one, disables/enables Java
exception checking in the mxj~ object's perform method. The default is zero
(disabled).
get attribute-name [list] The word get followed by an attribute-name will post the attribute value in the
Max window.
viewsource The viewsource message brings up a text editor window and loads the source code
for the peer Java object. If the source code is not in the same directory as the peer
class's .java file, a decompilation of the class file is attempted and the resulting
decompiled source is presented. From within the editor window it's possible to
make edits to the source, save the file, and recompile the class.
zap When a zap message is sent to an mxj~ object with Java peer class Foo, the next
mxj~ object that's instantiated with the same peer Java class Foo (ie typing "mxj
Foo" in an object box) will cause the class to reload itself from disk. This is most
useful in a programming context: if one makes a change to Foo.java and
recompiles a new Foo.class the zap message allows one to create an instance of
the new class without having to quit and restart the Max environment. Without
sending the zap message Max would simply use the cached definition of the class
that was loaded when a Foo object was instantiated prior to the changes being
made.
Information for box attributes common to all objects

Output
various: The number of outlets that an instance of mxj~ creates is determined by declarations made in the constructor of the
peer Java class. The furthest outlet to the right may or may not be an info outlet whose sole responsibility is to report
information about the attributes when queried.

Examples

An mxj~ object producing noise

See Also
Name Description
mxj Execute Java in Max
noise~
Generate white noise

Description
Use the noise~ object to generate a signal consisting of uniformly distributed random white-noise with values between -1.0 and
1.0.

Arguments
None.

Information for box attributes common to all objects

Output
signal: The noise~ object generates a signal consisting of uniformly distributed random white-noise values between -1 and 1.

Examples

Random samples create white noise, which can be filtered in various ways

See Also
Name Description
biquad~ Two-pole, two-zero filter
pink~ Pink noise generator
reson~ Resonant bandpass filter
MSP Tutorial 3: Wavetable MSP Tutorial 3: Wavetable Oscillator
Oscillator
MSP Tutorial 29: Flanging MSP Tutorial 29: Flanging
normalize~
Scale on the basis of maximum amplitude

Description
normalize~ performs real-time normalization of its input by multiplying each input sample value by a scaling factor - computed
as the maximum output value (sent either as a signal or a float in the right inlet) over the maximum signal input value received
thus far.

Arguments
Name Units Type Opt Description
initial-maximum- float opt The initial maximum output amplitude. The default is 1.
output-amplitude

Messages
int maximum-output-amplitude Converted to float.
[int]
float maximum-output-amplitude In right inlet: The maximum output amplitude may be sent as a float instead of a
[float] signal. If a signal is connected to the right inlet, a float received in the right inlet
is ignored.
reset maximum-input-amplitude In left inlet: The word reset, followed by a number, resets the maximum input
[float] amplitude to the number. If no number follows reset, or if the number is 0, the
maximum input amplitude is set to 0.000001.
signal In left inlet: The input signal is normalized -- scaled so that its peak amplitude is
equal to a specified maximum.

In right inlet: The maximum output amplitude; an over-all scaling of the output.

Information for box attributes common to all objects

Output
signal: The input signal is scaled by the maximum output amplitude divided by the maximum input amplitude.

Examples
When precise scaling factor varies or is unknown, normalize~ sets peak amplitude

See Also
Name Description
*~ Multiply two signals
MSP Tutorial 28: Delay Lines with MSP Tutorial 28: Delay Lines with Feedback
Feedback
!=~
Not equal to, comparison of two signals

Description
!=~ outputs a 1 signal when the left input is not-equal to the right input and a 0 when it is equal to the right input. The right input
can be a signal or a float.

Arguments
Name Units Type Opt Description
initial- number opt Sets an initial comparison value for the signal coming into the left inlet. 1 is sent
comparison-value out if the signal is not equal to the argument; otherwise, 0 is sent out. If a signal is
connected to the right inlet, the argument is ignored. If no argument is present,
and no signal is connected to the right inlet, the initial value is 0 by default.

Messages
int comparison-value [int] In right inlet: A number to be used for comparison with the signal coming into the
left inlet. If a signal is also connected to the right inlet, a float or int is ignored.
float comparison-value [float] In right inlet: A number to be used for comparison with the signal coming into the
left inlet. If a signal is also connected to the right inlet, a float or int is ignored.
signal In left inlet: The signal is compared to a signal coming into the right inlet, or a
constant value received in the right inlet. If it is not-equal to the value in the right
inlet, 1 is sent out; otherwise, 0 is sent out.

In right inlet: The signal is used for comparison with the signal coming into the left
inlet.

Information for box attributes common to all objects

Output
signal: If the signal in the left inlet is not equal to the value in the right inlet, 1 is sent out; otherwise, 0 is sent out.

Examples

Use !=~ to detect the non-zero portion of a signal or envelope

See Also
Name Description
==~ Is equal to, comparison of two signals
<~ Is less than, comparison of two signals
<=~ Is less than or equal to, comparison of two signals
>~ Is greater than, comparison of two signals
>=~ Is greater than or equal to, comparison of two signals
change~ Report signal direction
edge~ Detect logical signal transitions
number~
Signal monitor and constant generator

Description
Use the number~ object to display signal values or generate them.

Arguments
None.

Messages
bang In signal output mode, a bang message will output the current signal value.
int input [int] Converted to float.
In left inlet: The value is sent out the left outlet as a constant signal. When
number~ is in Signal Output display mode, the value is displayed. If the current
ramp time is non-zero, the output signal will ramp between its previous value and
the newly set value.
In right inlet: Sets a ramp time in milliseconds. The default time is 0.
float input [float] In left inlet: The value is sent out the left outlet as a constant signal. When
number~ is in Signal Output display mode, the value is displayed. If the current
ramp time is non-zero, the output signal will ramp between its previous value and
the newly set value.
In right inlet: Sets a ramp time in milliseconds. The default time is 0.
(inlet1) input [float] In right inlet: Sets a ramp time in milliseconds. The default time is 0.
list input-value [number] The first number sets the value of the signal sent out the left outlet, and the second
ramp-time [int] number sets the ramp time in milliseconds.
allow display-mode-availability The word allow, followed by a number, sets what display modes can be used.
[int] allow 1 restricts number~ to signal output display mode. allow 2 restricts
number~ to input monitor display mode. allow 3 allows both modes, and lets the
user switch between them by clicking on the left triangular area of number~.
flags appearance/behavior [int] The flags message is provided for legacy support of the number~ object; all the
original functionality is now provided by object attributes.
max maximum-value [number] The word max, followed by an optional number, sets the maximum value of
number~ for signal output. Note that unlike a floating-point number box, the
maximum value of number~ is not restricted to being an integer value. If the
word max is not followed by a number, any maximum value is removed.
min minimum-value [number] The word min, followed by an optional number, sets the minimum value of
number~ for signal output. Note that unlike a floating-point number box, the
minimum value of number~ is not restricted to being an integer value. If the word
min is not followed by a number, any minimum value is removed.
mode display-mode [int] The word mode, followed by a number, sets the current display mode, if it is
currently allowed (see the allow message). mode 1 sets signal output display
mode. mode 2 sets signal input monitor display mode.
(mouse) Clicking on the triangular area at the left side of number~ will toggle between
Signal Monitor display mode (green waveform) and Signal Output display mode
(yellow or green downward arrow). When in Signal Output display mode, clicking
in the area that displays the number changes the value of the signal sent out the
left outlet of number~ and/or selects it for typing.
set set-input [float] The word set followed by a number sets the number~ object to display that
number without causing output.
signal Any signal, the value of which is sampled and sent out the right outlet at regular
intervals. When number~ is in Signal Monitor display mode, the signal value is
displayed.
Attributes
Name Type g/s Description
bgcolor float Sets the color for the number~ box object's displayed/unclicked background.
bgcolor2 float Sets the color for the left portion of the number box object's background.
def.:0.706 0.706
0.706 1.
bordercolor float Sets the color for the number box object's outline.
ft1 float The word ft1, followed by a number, sets the interpolation ramp time in
def.:0. milliseconds. The default time is 0.
hbgcolor float Sets the RGBA values for the background of the number~ box when it is
def.:0. 0. 0. 1. highlighted or being updated.
htextcolor float Sets the RGBA values for the number values displayed by the number~ box when
def.:0.87 0.87 it is highlighted or being updated.
0.87 1.
interval float Sets the update interval, in milliseconds. This controls the rate at which the
def.:100. display is updated when number~ is input monitor display mode, as well as the
rate that numbers are sent out the object's right outlet.
maximum atom Sets the maximum value that can be displayed or sent out by the object.
def.:<none>
minimum atom Sets the minimum value that can be displayed or sent out by the object.
def.:<none>
monitormode int Toggles the signal monitor mode. The default is 1 (on).
def.:1
numdecimalplaces int Number of decimal places displayed
def.:0
sigoutmode int Toggles the signal output mode. The default is 1 (on).
def.:1
textcolor float Sets the color for the number~ box object's displayed/unclicked number values.
Legacy
brgba list (3 ints) brgba is a legacy RGB alias for the bgcolor RGBA attribute. See here for more
information.
frgba list (3 ints) frgba is a legacy RGB alias for the textcolor RGBA attribute. See here for more
information.
rgba2 list (3 ints) rgba2 is a legacy RGB alias for the htextcolor RGBA attribute. See here for more
information.
rgba3 list (3 ints) rgba3 is a legacy RGB alias for the hbgcolor RGBA attribute. See here for more
information.
rgba4 list (3 ints) rgba4 is a legacy RGB alias for the bordercolor RGBA attribute. See here for
more information.

Information for box attributes common to all objects

Output
float: Out right outlet: Samples of the input signal are sent out at a rate specified by the interval message.
signal: Out left outlet: When audio is on, number~ sends a constant signal out its left outlet equal to the number most recently
received in the left inlet (or entered by the user). It sends out this value independent of its signal input, and whether or not it is
currently in Signal Output display mode. If the ramp time most recently received in the right inlet is set to a non-zero value, the
output will interpolate between its previous value and a newly set value over the specified time.

Examples
Several uses for the number~ object

See Also
Name Description
line~ Linear ramp generator
sig~ Convert numbers into audio signals
snapshot~ Convert signal values to numbers
MSP Tutorial 23: Viewing Signal MSP Tutorial 23: Viewing Signal Data
Data
omx.4band~
OctiMax 4-band Compressor

Description
omx.4band~ delivers the signal-processing power of Octimax in a 4-band compressor.

Arguments
None.

Messages
choosePreset preset-number [int] The word choosePreset, followed by a number in the range 0-2, selects a preset
for the omx.4band~ object. These presets are to be considered "starting points"
and should be tweaked for your particular purpose or desired sound. The preset
options are:

0: Standard - Appropriate for anything, all genres of music, movies, television


viewing, etc.
1; Pop - Great for any modern genre including rock, country, trance.
2; Movies - Similar to standard but optimized for dynamic movie soundtracks.
bypass bypass-flag [int] The word bypass followed by a non-zero number will output the dry unchanged
input signal straight out the outlet without any processing; followed by a 0, will
output the signal effected by omx.4band~.
gating_threshold release-gate- The word gating_threshold, followed by a number, sets the release gate
threshold [float] threshold (in dB below full scale). When the signal is below this threshold, the
release time of the compressor will be slowed by a factor of 3.
inagc_b1_atk attack-rate- The word inagc_b1_atk, followed by a number, sets the attack rate for the input
coefficient [int] compressor. The attack rate determines how quickly the compressor applies gain
reduction. The value range is 0-150 on a logarithmic scale, with larger values
indicating faster attack.
inagc_b1_rel release-rate- The word inagc_b1_rel, followed by a number, sets the release rate for the input
coefficient [int] compressor. The release rate determines how quickly the compressor returns to
unity gain. The value range is 0-150 on a logarithmic scale, with larger values
indicating faster release.
inagc_range maximum-dB [int] The word inagc_range, followed by a number, sets the maximum amount of gain
in dB applied by the input compressor . The compression ratio is fixed at infinity:1.
mbagc_b1_atk b1attack-rate- The word mbagc_b1_atk, followed by a number, sets the attack rate for band 1.
coefficient [int] The attack rate determines how quickly the compressor applies gain reduction. The
value range is 0-150 on a logarithmic scale, with larger values indicating faster
attack.
mbagc_b1_drv b1drive-rate- The word mbagc_b1_drv, followed by a number, sets the gain in dB applied to
coefficient [int] band 1 before compression. Increasing the drive for a particular band applies more
compression to those frequencies.
mbagc_b1_rel b2release-rate- The word mbagc_b1_rel, followed by a number, sets the release rate for band 1.
coefficient [int] The release rate determines how quickly the compressor returns to unity gain. The
value range is 0-150 on a logarithmic scale, with larger values indicating faster
release.
mbagc_b2_atk b2attack-rate- The word mbagc_b2_atk, followed by a number, sets the attack rate for band 2.
coefficient [int] The attack rate determines how quickly the compressor applies gain reduction. The
value range is 0-150 on a logarithmic scale, with larger values indicating faster
attack.
mbagc_b2_drv b2drive-rate- The word mbagc_b2_drv, followed by a number, sets the gain in dB applied to
coefficient [int] band 2 before compression. Increasing the drive for a particular band applies more
compression to those frequencies.
mbagc_b2_rel b2release-rate- The word mbagc_b2_rel, followed by a number, sets the release rate for band 2.
coefficient [int] The release rate determines how quickly the compressor returns to unity gain. The
value range is 0-150 on a logarithmic scale, with larger values indicating faster
release.
mbagc_b3_atk b3attack-rate- The word mbagc_b3_atk, followed by a number, sets the attack rate for band 3.
coefficient [int] The attack rate determines how quickly the compressor applies gain reduction. The
value range is 0-150 on a logarithmic scale, with larger values indicating faster
attack.
mbagc_b3_drv b3drive-rate- The word mbagc_b3_drv, followed by a number, sets the gain in dB applied to
coefficient [int] band 3 before compression. Increasing the drive for a particular band applies more
compression to those frequencies.
mbagc_b3_rel b3release-rate- The word mbagc_b3_rel, followed by a number, sets the release rate for band 3.
coefficient [int] The release rate determines how quickly the compressor returns to unity gain. The
value range is 0-150 on a logarithmic scale, with larger values indicating faster
release.
mbagc_b4_atk b4attack-rate- The word mbagc_b4_atk, followed by a number, sets the attack rate for band 4.
coefficient [int] The attack rate determines how quickly the compressor applies gain reduction. The
value range is 0-150 on a logarithmic scale, with larger values indicating faster
attack.
mbagc_b4_drv b4drive-rate- The word mbagc_b4_drv, followed by a number, sets the gain in dB applied to
coefficient [int] band 4 before compression. Increasing the drive for a particular band applies more
compression to those frequencies.
mbagc_b4_rel b4release-rate- The word mbagc_b4_rel, followed by a number, sets the release rate for band 4.
coefficient [int] The release rate determines how quickly the compressor returns to unity gain. The
value range is 0-150 on a logarithmic scale, with larger values indicating faster
release.
meterData The word meterData will cause output (by instantaneous command as opposed to
metering-interval described by the meterRate message) of values which describe
the current state of various internal levels of the compressor, and can be used to
drive GUI objects to provide visual feedback.
meterRate output-interval [int] The word meterRate, followed by a number, specifies the interval (in
milliseconds) at which the meter data described above will be sent.
meters metering-output- The word meters, followed by a 1 or 0, turns the metering output on or off. When
flag [int] metering is on, a list of values will be sent from the rightmost outlet at a rate
specified by the meterRate message. These values describe the current state of
various internal levels of the compressor, and can be used to drive GUI objects to
provide visual feedback.
lim_drive pre-peak-limiting- The word lim_drive, followed by a number, sets the overall gain in dB before peak
gain [float] limiting is applied.
ngenabled noise-gate-enable- The word ngenabled, followed by a 1 or 0, turns the noise gate on or off. A noise
flag [int] gate is effective for reducing background hiss when no other signal is present.
omx.4band~ features two noise gates: one that operates on the entire signal, and
one that only affects higher frequencies, such as hiss.
ngthresh1 noise-gate- The word ngthresh1, followed by a number, sets the threshold level (in dB below
threshold [float] full scale) at which the overall noise gate will be engaged.
ngthresh2 treble-noise-gate- The word ngthresh2, followed by a number, sets the threshold level (in dB below
threshold [float] full scale) at which a noise gate will be applied to the treble frequencies only.
noisegate dB value [int] The word noisegate followed by a number which specifies a value in dB, sets the
noisegate threshold.
mbagc_range maximum-dB [float] The word mbagc_range, followed by a number, sets the maximum amount of
gain in dB applied by the multiband compressor. This affects all four frequency
bands. The compression ratio is fixed at infinity:1.
outmix1 output-gain [float] The word outmix1, followed by a number, sets the gain in dB applied to band 1
after compression.
outmix2 output-gain [float] The word outmix2, followed by a number, sets the gain in dB applied to band 2
after compression.
outmix3 output-gain [float] The word outmix3, followed by a number, sets the gain in dB applied to band 3
after compression.
outmix4 output-gain [float] The word outmix4, followed by a number, sets the gain in dB applied to band 4
after compression.
saveSettings The word saveSettings causes all parameter values to be sent out the third outlet.
signal Audio input, the signal or pair of signals to be compressed.

Information for box attributes common to all objects

Output
list: Out third outlet: parameter values in response to saveSettings message.

Out fourth outlet: meter data. When metering is turned on, lists of values will be output that describe various internal levels. See
the description of the meters message, above.

signal: Out leftmost two outlets: the input signals (if present), with dynamics processing applied.

Examples

See Also
Name Description
omx.5band~ OctiMax 5-band Compressor
omx.comp~ OctiMax Compressor
omx.peaklim~ OctiMax Peak Limiter
MSP Compression Tutorial 5: MSP Compression Tutorial 5: Multiband Compression 1
Multiband Compression 1
MSP Compression Tutorial 6: MSP Compression Tutorial 6: Multiband Compression 2
Multiband Compression 2
omx.5band~
OctiMax 5-band Compressor

Description
omx.5band~ delivers the signal-processing power of Octimax in a 5-band compressor.

Arguments
None.

Messages
choosePreset preset- The word choosePreset, followed by a number in the range 0-2, selects a
number [int] preset for the omx.4band~ object. These presets are to be considered
"starting points" and should be tweaked for your particular purpose or desired
sound. The preset options are:

0: Universal - Provides a general boost to the sound, with a 3-to-1


compression and no limiting. Bass enhancement is switched in for a bit of
warmth.
1; Pop - Sets a 50:1 compression with hard driven limiting in the lowest two
bands. The gives a solid bottom to the sound.
2: Hit Radio - Is a compromise between the Universal and Pop settings. You
will note that the times are all about the same, with appropriately slower
attack and release in the low bands.
3: FM Radio - Differs from the Pop and Hit radio settings primarily in the
high end, which is compressed a bit tighter.
bands_enum 0/1 [int] The word bands_enum, followed by a zero or one, sets the number of bands.
The option are:

0: 4-band
1: 5-band
bassenhancement low- The word bassenhancement followed by a non-zero number will enable the
frequency- specialized enhancement of low frequencies by the multiband compressor;
emphasis-flag followed by 0, causes no low frequency enhancement to be applied.
[int]
bassenhancement_mixlevel low- The word bassenhancement_mixlevel, followed by a number, sets the
frequency- amount of low-frequency enhancement added into the audio signal before
enhancement- output.
level [int]
bypass bypass-flag The word bypass followed by a non-zero number will output the dry
[int] unchanged input signal straight out the outlet without any processing;
followed by a 0, will output the signal effected by omx.5band~.
gating_threshold release-gate- The word gating_threshold, followed by a number, sets the release gate
threshold threshold (in dB below full scale). When the signal is below this threshold, the
[float] release time of the compressor will be slowed by a factor of 3.
freeze_threshold freeze The word freeze_threshold, followed by a number, sets the freeze threshold
threshold (in dB below full scale). When the input signal drops below the freeze
[float] threshold, release will seize completely. Along with the gating threshold, this
threshold is useful to prevent background hiss amplification.
inagc_atk input- The word inagc_atk, followed by a number, sets the attack rate for the input
compressor- compressor. The attack rate determines how quickly the compressor applies
attack-rate gain reduction. The value range is 0-150 on a logarithmic scale, with larger
[int] values indicating faster attack.
inagc_progressive progressive- The word inagc_progressive, followed by a 1 or 0, enables or disables the
release- Progressive Release mode, which causes the input compressor to release
mode-flag faster during heavy gain reduction.
[int]
inagc_range maximum- The word inagc_range, followed by a number, sets the maximum amount of
input- gain in dB applied by the input compressor .
compressor-
gain [float]
inagc_ratio compressor- The word inagc_ratio, followed by a number, sets the numerator of the
gain- compressor gain reduction ratio, from 1:1 to Infinite:1.
reduction-
ratio-
numerator
[int]
inagc_rel input- The word inagc_rel, followed by a number, sets the release rate for the input
compressor- compressor. The release rate determines how quickly the compressor returns
release-rate to unity gain. The value range is 0-150 on a logarithmic scale, with larger
[int] values indicating faster release.
inagc_threshold compression- The word inagc_threshold, followed by a number, sets the compression
threshold- threshold level (in dB below full scale) for the input compressor.
level [float]
inf_ratio_above_threshold_1 0/1 [int] The word inf_ratio_above_threshold_1, followed by a zero or one,
disables/enables Infinite ratio above threshold (sometimes called "soft
clipping") for band 1. If enabled, the ratio in that band will be Infinite:1 any
time there is gain reduction (i.e. the input signal is above the threshold), no
matter what the Multiband Ratio is set to.
inf_ratio_above_threshold_2 0/1 [int] The word inf_ratio_above_threshold_2, followed by a zero or one,
disables/enables Infinite ratio above threshold (sometimes called "soft
clipping") for band 2. If enabled, the ratio in that band will be Infinite:1 any
time there is gain reduction (i.e. the input signal is above the threshold), no
matter what the Multiband Ratio is set to.
inf_ratio_above_threshold_3 0/1 [int] The word inf_ratio_above_threshold_3, followed by a zero or one,
disables/enables Infinite ratio above threshold (sometimes called "soft
clipping") for band 3. If enabled, the ratio in that band will be Infinite:1 any
time there is gain reduction (i.e. the input signal is above the threshold), no
matter what the Multiband Ratio is set to.
inf_ratio_above_threshold_4 0/1 [int] The word inf_ratio_above_threshold_4, followed by a zero or one,
disables/enables Infinite ratio above threshold (sometimes called "soft
clipping") for band 4. If enabled, the ratio in that band will be Infinite:1 any
time there is gain reduction (i.e. the input signal is above the threshold), no
matter what the Multiband Ratio is set to.
inf_ratio_above_threshold_5 0/1 [int] The word inf_ratio_above_threshold_5, followed by a zero or one,
disables/enables Infinite ratio above threshold (sometimes called "soft
clipping") for band 5. If enabled, the ratio in that band will be Infinite:1 any
time there is gain reduction (i.e. the input signal is above the threshold), no
matter what the Multiband Ratio is set to.
mbagc_b1_atk attack-rate The word mbagc_b1_atk, followed by a number, sets the attack rate for band
[int] 1. The attack rate determines how quickly the compressor applies gain
reduction. The value range is 0-150 on a logarithmic scale, with larger values
indicating faster attack.
mbagc_b1_drv pre- The word mbagc_b1_drv, followed by a number, sets the gain in dB applied
compressor- to band 1 before compression. Increasing the drive for a particular band
gain [float] applies more compression to those frequencies.
mbagc_b1_rel attack-rate The word mbagc_b1_rel, followed by a number, sets the release rate for
[int] band 1. The release rate determines how quickly the compressor returns to
unity gain. The value range is 0-150 on a logarithmic scale, with larger values
indicating faster release.
mbagc_b1_threshold compression- The word mbagc_b1_threshold, followed by a number, sets the compression
threshold threshold level (in dB below full scale) for band 1. A frequency band will be
[float] compressed if its signal level exceeds the threshold.
mbagc_b2_atk attack-rate The word mbagc_b2_atk, followed by a number, sets the attack rate for band
[int] 2. The attack rate determines how quickly the compressor applies gain
reduction. The value range is 0-150 on a logarithmic scale, with larger values
indicating faster attack.
mbagc_b2_drv pre- The word mbagc_b2_drv, followed by a number, sets the gain in dB applied
compressor- to band 2 before compression. Increasing the drive for a particular band
gain [float] applies more compression to those frequencies.
mbagc_b2_rel attack-rate The word mbagc_b2_rel, followed by a number, sets the release rate for
[int] band 2. The release rate determines how quickly the compressor returns to
unity gain. The value range is 0-150 on a logarithmic scale, with larger values
indicating faster release.
mbagc_b2_threshold compression- The word mbagc_b2_threshold, followed by a number, sets the compression
threshold threshold level (in dB below full scale) for band 2. A frequency band will be
[float] compressed if its signal level exceeds the threshold.
mbagc_b3_atk attack-rate The word mbagc_b3_atk, followed by a number, sets the attack rate for band
[int] 3. The attack rate determines how quickly the compressor applies gain
reduction. The value range is 0-150 on a logarithmic scale, with larger values
indicating faster attack.
mbagc_b3_drv pre- The word mbagc_b3_drv, followed by a number, sets the gain in dB applied
compressor- to band 3 before compression. Increasing the drive for a particular band
gain [float] applies more compression to those frequencies.
mbagc_b3_rel attack-rate The word mbagc_b3_rel, followed by a number, sets the release rate for
[int] band 3. The release rate determines how quickly the compressor returns to
unity gain. The value range is 0-150 on a logarithmic scale, with larger values
indicating faster release.
mbagc_b3_threshold compression- The word mbagc_b3_threshold, followed by a number, sets the compression
threshold threshold level (in dB below full scale) for band 3. A frequency band will be
[float] compressed if its signal level exceeds the threshold.
mbagc_b4_atk attack-rate The word mbagc_b4_atk, followed by a number, sets the attack rate for band
[int] 4. The attack rate determines how quickly the compressor applies gain
reduction. The value range is 0-150 on a logarithmic scale, with larger values
indicating faster attack.
mbagc_b4_drv pre- The word mbagc_b4_drv, followed by a number, sets the gain in dB applied
compressor- to band 4 before compression. Increasing the drive for a particular band
gain [float] applies more compression to those frequencies.
mbagc_b4_rel attack-rate The word mbagc_b4_rel, followed by a number, sets the release rate for
[int] band 4. The release rate determines how quickly the compressor returns to
unity gain. The value range is 0-150 on a logarithmic scale, with larger values
indicating faster release.
mbagc_b4_threshold compression- The word mbagc_b4_threshold, followed by a number, sets the compression
threshold threshold level (in dB below full scale) for band 4. A frequency band will be
[float] compressed if its signal level exceeds the threshold.
mbagc_b5_atk attack-rate The word mbagc_b5_atk, followed by a number, sets the attack rate for band
[int] 5. The attack rate determines how quickly the compressor applies gain
reduction. The value range is 0-150 on a logarithmic scale, with larger values
indicating faster attack.
mbagc_b5_drv pre- The word mbagc_b5_drv, followed by a number, sets the gain in dB applied
compressor- to band 5 before compression. Increasing the drive for a particular band
gain [float] applies more compression to those frequencies.
mbagc_b5_rel attack-rate The word mbagc_b5_rel, followed by a number, sets the release rate for
[int] band 5. The release rate determines how quickly the compressor returns to
unity gain. The value range is 0-150 on a logarithmic scale, with larger values
indicating faster release.
mbagc_b5_threshold compression- The word mbagc_b5_threshold, followed by a number, sets the compression
threshold
threshold level (in dB below full scale) for band 5. A frequency band will be
[float] compressed if its signal level exceeds the threshold.
mbagc_progressive progressive- The word mbagc_progressive, followed by a 1 or 0, enables or disables the
release- Progressive Release mode, which causes the multi-band compressor to release
mode-flag faster during heavy gain reduction.
[int]
mbclip_b1_threshold clipping- The word mbclip_b1_threshold, followed by a number, sets the bass
threshold [int] clipping threshold level (in dB below full scale).

mblim_b1_threshold peak-limiter- The word mblim_b1_threshold, followed by a number, sets the threshold
threshold signal level in dB for the peak limiter of band 1.
[float]
mblim_b2_threshold peak-limiter- The word mblim_b2_threshold, followed by a number, sets the threshold
threshold signal level in dB for the peak limiter of band 2.
[float]
mblim_b3_threshold peak-limiter- The word mblim_b3_threshold, followed by a number, sets the threshold
threshold signal level in dB for the peak limiter of band 3.
[float]
mblim_b4_threshold peak-limiter- The word mblim_b4_threshold, followed by a number, sets the threshold
threshold signal level in dB for the peak limiter of band 4.
[float]
mblim_b5_threshold peak-limiter- The word mblim_b5_threshold, followed by a number, sets the threshold
threshold signal level in dB for the peak limiter of band 5.
[float]
mbrange maximum- The word mbrange, followed by a number, sets the maximum amount of
compressor- gain in dB applied by the multiband compressor. This limits the gain that is
gain [float] applied when the signal is below the compression threshold. Note that this
limiting takes place before the ratio is applied. For example, if the range is set
to 24 dB, and the ratio is 2:1, the most gain amplification you can get (after
the ratio is applied) is in fact 12 dB.
mbratio compressor- The word mbratio, followed by a number, sets the numerator of the
gain- compressor gain reduction ratio, from 1:1 to Infinite:1.
reduction-
ratio-
numerator
[int]
meterData The word meterData will cause output (by instantaneous command as
opposed to metering-interval described by the meterRate message) of values
which describe the current state of various internal levels of the compressor,
and can be used to drive GUI objects to provide visual feedback.
meterRate data-output- The word meterRate, followed by a number, specifies the interval (in
interval [int] milliseconds) at which the meter data described above will be sent.
meters metering- The word meters, followed by a 1 or 0, turns the metering output on or off.
output-flag When metering is on, a list of values will be sent from the rightmost outlet at
[int] a rate specified by the meterRate message. These values describe the current
state of various internal levels of the compressor, and can be used to drive
GUI objects to provide visual feedback.
multiband_limiters peak- The word multiband_limiters, followed by a 1 or 0, enables or disables the
limiting-flag peak limiting function, which limits the signal level of each frequency band
[int] independently, so it does not exceed the threshold set for that band.
lim_drive pre-peak- The word lim_drive, followed by a number, sets the overall gain in dB before
limiter-gain peak limiting is applied.
[float]
lim_smoothrelease limiter- The word lim_smoothrelease, followed by a number, sets the limiter
response-flag response mode as follows:
[int]
0: Punchy. Punchy response yields extremely short attack and release times,
useful for transparent limiting, or to create loudness. However, if over-used,
intermodulation distortion may result.
1: Smooth. Smooth release uses longer attack and release times. The result is
still a fast look-ahead limiter, but with less intermodulation distortion and
less punch.
outlevel_cc ARG_NAME_0 TEXT_HERE
[int]
outlevel_lf level [float] The word outlevel_lf, followed by a number, sets the left channel output level
in dB for the omx.5band~ object.
outlevel_ls ARG_NAME_0 TEXT_HERE
[int]
outlevel_rf level [float] The word outlevel_rf, followed by a number, sets the right channel output
level in dB for the omx.5band~ object.
outlevel_rs ARG_NAME_0 TEXT_HERE
[int]
outlevel_sw ARG_NAME_0 TEXT_HERE
[int]
ng_enabled_maxch noise-gate- The word ng_enabled_maxch, followed by a 1 or 0, enables or disables noise
enable-flag gating for the multi-band compressor. The noise gating itself has multiple
[int] bands, separate from the compressor, allowing independent control via the
ngthresh messages.
ngenabled noise-gate- The word ngenabled, followed by a 1 or 0, turns the noise gate on or off. A
enable-flag noise gate is effective for reducing background hiss when no other signal is
[int] present. omx.4band~ features two noise gates: one that operates on the
entire signal, and one that only affects higher frequencies, such as hiss.
ngthresh1 threshold- The word ngthresh1, followed by a number that specifies a threshold level
level [float] (expressed as dB below full scale), sets the threshold level at which the noise
gate for band 1 will be engaged.
ngthresh2 threshold- The word ngthresh2, followed by a number that specifies a threshold level
level [float] (expressed as dB below full scale), sets the threshold level at which the noise
gate for band 2 will be engaged.
ngthresh3 threshold- The word ngthresh3, followed by a number that specifies a threshold level
level [float] (expressed as dB below full scale), sets the threshold level at which the noise
gate for band 3 will be engaged.
ngthresh4 threshold- The word ngthresh4, followed by a number that specifies a threshold level
level [float] (expressed as dB below full scale), sets the threshold level at which the noise
gate for band 4 will be engaged.
ngthresh5 threshold- The word ngthresh5, followed by a number that specifies a threshold level
level [float] (expressed as dB below full scale), sets the threshold level at which the noise
gate for band 5 will be engaged.
outmix1 post- The word outmix1, followed by a number, sets the gain in dB applied to band
compression- 1 after compression.
gain [float]
outmix2 post- The word outmix2, followed by a number, sets the gain in dB applied to band
compression- 2 after compression.
gain [float]
outmix3 post- The word outmix3, followed by a number, sets the gain in dB applied to band
compression- 3 after compression.
gain [float]
outmix4 post- The word outmix4, followed by a number, sets the gain in dB applied to band
compression- 4 after compression.
gain [float]
outmix5 post- The word outmix5, followed by a number, sets the gain in dB applied to band
compression- 5 after compression.
gain [float]
output_level output level The word output_level, followed by a number, sets the output level. This
[int] setting is used for attenuating the output, but clipping will never occur even if
you set it to gain. The gain for each channel will take both this control and the
controls on the Global Settings page into account, but the gain for each
channel will be clamped below 0 to prevent clipping.
saveSettings The word saveSettings causes all parameter values to be sent out the third
outlet.
signal Audio input, the signal or pair of signals to be compressed.
spatial_enabled 0/1 [int] The word spatial_enabled, followed by a zero or one, disables/enables
spatial enhancement.
spatial_desired difference- The spatial enhancer separates the channels of mixes that are nearly (but not
between- quite) mono by subtracting a bit of left from the right signal and vice versa,
signals (0- but only when the two are nearly the same. The word spatial_desired,
100) [int] followed by a number, sets the difference between the side signal and the
combined (mono) signal,
spatial_maximum maximum- The spatial enhancer separates the channels of mixes that are nearly (but not
gain [int] quite) mono by subtracting a bit of left from the right signal and vice versa,
but only when the two are nearly the same. The word spatial_maximum,
followed by a number, sets the maximum gain on the two difference signals.
spatial_speed response The spatial enhancer separates the channels of mixes that are nearly (but not
speed [int] quite) mono by subtracting a bit of left from the right signal and vice versa,
but only when the two are nearly the same. The word spatial_speed,
followed by a number, sets the speed of response to changes in separation.

Information for box attributes common to all objects

Output
list: Out third outlet: parameter values in response to saveSettings messages.

Out fourth outlet: meter data. When metering is turned on, lists of values will be output that describe various internal levels. See
the description of the meters message, above.

signal: Out leftmost two outlets: the input signals (if present), with dynamics processing applied.

Examples

See Also
Name Description
omx.4band~ OctiMax 4-band Compressor
omx.comp~ OctiMax Compressor
omx.peaklim~ OctiMax Peak Limiter
MSP Compression Tutorial 6: MSP Compression Tutorial 6: Multiband Compression 2
Multiband Compression 2
omx.comp~
OctiMax Compressor

Description
omx.comp~ is a fully-featured signal compressor with limiting, gating, sidechain, and dual-band options.

Arguments
None.

Messages
agcEnabled compression- The word agcEnabled, followed by a 1 or 0, enables or disables the compressor.
enable-flag
[int]
agcThreshold compression- The word agcThreshold, followed by a number, sets the compressor threshold (in
threshold dB below full scale). This is the main compression threshold. Any signal above the
[float] threshold will be reduced, and any signal below the threshold will be amplified,
according to the range and ratio parameters.
attack attack-rate [int] The word attack, followed by a number, sets the rate at which the compressor is
engaged when the signal level exceeds the agcThreshold. The value range is 0-150
on a logarithmic scale, with larger values indicating faster attack.
choosePreset preset-number The word choosePreset, followed by a number in the range 0-4, selects a preset
[int] for the omx.comp~ object. These presets are to be considered "starting points"
and should be tweaked for your particular purpose or desired sound. The preset
options are:

0: Guitar
1: Bass
2: Vocal
3: Drums
4: Program Material - An attempt at smooth "gain riding" of mixed program
material as well as can be done with a non-multiband processor.
bypass bypass-flag The word bypass followed by a non-zero number will output the dry unchanged
[int] input signal straight out the outlet without any processing; followed by a 0, will
output the signal effected by omx.comp~.
delay delay-time [int] The word delay, followed by a number, sets the sidechain delay time (in
milliseconds). This emulates the attack characteristics of vintage "opto"
compressors, and similar effects. The delay is applied to the control signal only,
and hence may result in large peaks at transients.
dualBandEnabled crossover- The word dualBandEnabled, followed by a 1 or 0, turns dual band mode on or off.
enable-flag In dual band, a crossover filter around 200hz splits the audio into two bands,
[int] which are compressed separately. This can reduce bass pumping and other
artifacts of wide-band compression.
channelCoupling keying-source The word channelCoupling, followed by a number, sets the gain control source as
(0, 1, or 2) [int] follows: 0 = stereo, 1 = left, 2 = right. In stereo mode, the gain control signal is
derived from whichever channel is loudest, unlike in left or right mode where the
gain control signal will only be derived from the selected channel. This can be used
for "keying" or "ducking" effects, where the energy of one sound modulates the
level of another.
gatingLevel release-gate- The word gatingLevel, followed by a number, sets the release gate threshold (in
threshold dB below full scale). When the signal is below this threshold, the release time of
[float] the compressor will be slowed by a factor of 3. See freezeLevel.
freezeLevel release-action- The word freezeLevel, followed by a number, sets the freeze threshold (in dB
threshold below full scale). When the signal is below this threshold, the compressor release
[float] action will be suppressed, and the gain will remain constant. In normal operation,
release action takes place when the signal is below the compression threshold,
increasing the gain until the signal returns to its full-scale, uncompressed level. If
there is no usable signal present, this can have the effect of simply amplifying the
noise floor. Release gate and freeze can suppress gain recovery to avoid this
condition.
meterData The word meterData will cause output (by instantaneous command as opposed to
metering-interval described by the meterRate message) of values which describe
the current state of various internal gain levels of the compressor, and can be used
to drive GUI objects to provide visual feedback. omx.comp~ sends a list of six
integers, describing compressor gain (left, right), noise gate gain (left, right), and
limiter gain (left, right).
meterRate data-output- The word meterRate, followed by a number, specifies the interval (in
interval [int] milliseconds) at which the meter data described above will be sent.
meters metering- The word meters, followed by a 1 or 0, turns the metering output on or off. When
enable-flag metering is on, a list of values will be sent from the rightmost outlet at a rate
[int] specified by the meterRate message. These values describe the current state of
various internal gain levels of the compressor, and can be used to drive GUI
objects to provide visual feedback. omx.comp~ sends a list of six integers,
describing compressor gain (left, right), noise gate gain (left, right), and limiter
gain (left, right).
limEnabled peak-limiter- The word limEnabled, followed by a 1 or 0 turns the peak-limiter on or off.
flag [int]
limMode response- The word limMode, followed by a number, sets the limiter response mode as
mode-flag [int] follows: 0 = punchy, 1 = smooth. Punchy response yields extremely short attack
and release times, useful for transparent limiting, or to create loudness. However,
if over-used, intermodulation distortion may result. Smooth response uses longer
attack and release times. The result is still a fast look-ahead limiter, but with less
intermodulation distortion and less punch.
ngEnabled noise-gate-flag The word ngEnabled, followed by a 1 or 0, turns the noise gate on or off. A noise
[int] gate is effective for reducing background hiss when no other signal is present.
Here, it's implemented as a downward expander with a ratio of 2:1.
ngThreshold noise-gate- The word ngThreshold, followed by a number, sets the threshold level (in dB
threshold below full scale) at which the noise gate will be engaged.
[float]
progressiveRelease release-mode- The word ProgressiveRelease, followed by a 1 or 0, enables or disables the
flag [int] Progressive Release mode, which causes the compressor to release faster during
heavy gain reduction. This means that the audio will sound more compressed
when the input signal is louder. This can be used to create an illusion of dynamics.
It is especially useful with the ratio set to Infinite:1, which could sound over-
compressed without this option.
saveSettings The word saveSettings causes all parameter values to be sent out the third outlet.
sidechainFilterEnabled keying- The word sidechainFilterEnabled, followed by a 1 or 0, enables or disables an
attenuation- attenuation filter in the upper midrange that makes the compressor less sensitive
flag [int] to vocal signals, and generally produces a more gentle response. This filter is only
applied internally, to the control signal. Note that it may cause more output
overshoots, where the signal output level exceeds 0dB.
range maximum- The word range, followed by a number, sets the maximum amount of gain
gain- amplification allowed in dB. This limits the gain that is applied when the signal is
amplification below the compression threshold. Note that this limiting takes place before the
[float] ratio is applied. For example, if the range is set to 24 dB, and the ratio is 2:1, the
most gain amplification you can get (after the ratio is applied) is in fact 12 dB.
ratio gain- The word ratio, followed by a number, sets the numerator of the compressor gain
reduction- reduction ratio, from 1:1 to Infinite:1.
ratio-
numerator [int]
release release-rate The word release, followed by a number, sets the rate at which the compressor
[int]
releases its gain adjustment when the signal level no longer exceeds the
agcThreshold. The value range is 0-150 on a logarithmic scale, with larger values
indicating faster release. This rate can be modified by the release gate and freeze
thresholds.
signal Audio input, the signal or pair of signals to be compressed.
smoothGain smoothing-flag The word smoothGain, followed by a 1 or 0, enables or disables gain smoothing.
[int] This applies a low-pass filter to the control signal, and is useful both to prevent
artifacts (gain fluttering) from high attack/release rates, and to intentionally make
the compressor sluggish, adding extra "snap" to transients.

Information for box attributes common to all objects

Output
list: Out right outlet: when metering is turned on (via the meters message), a list will be output describing various internal levels.
See meters, above.
signal: Out leftmost two outlets: the input signals (if present), with dynamics processing applied.

Examples

See Also
Name Description
omx.4band~ OctiMax 4-band Compressor
omx.5band~ OctiMax 5-band Compressor
omx.peaklim~ OctiMax Peak Limiter
MSP Compression Tutorial 2: MSP Compression Tutorial 2: Basic Compression
Basic Compression
MSP Compression Tutorial 3: MSP Compression Tutorial 3: Tweaking Compression
Tweaking Compression
omx.peaklim~
OctiMax Peak Limiter

Description
omx.peaklim~ is a peak-limiter which allows for the specified control of signal amplitude.

Arguments
None.

Messages
bypass bypass-flag [int] The word bypass followed by a non-zero number will output the dry unchanged
input signal straight out the outlet without any processing; followed by a 0, will
output the signal effected by omx.peaklim~.
ingain pre-limiter-gain [float] The word ingain, followed by a number, sets the gain in dB applied to the signal
before limiting.
meterData When metering is on, the word meterData will cause a list of two values to be sent
from the rightmost outlet at a rate specified by the meterRate message. These
values describe the gain reduction in dB currently applied to the two input signals.
meterRate data-output-interval [int] The word meterRate, followed by a number, specifies the interval (in
milliseconds) at which the meter data described above will be sent.
meters metering-flag [int] The word meters, followed by a 1 or 0, turns the metering output on or off. Whe N
metering is on, a list of two values will be sent from the rightmost outlet at a rate
specified by the meterRate message. These values describe the gain reduction in
dB currently applied to the two input signals.
mode response-mode-flag [int] The word mode, followed by a number, sets the limiter response mode as follows:
0 = punchy, 1 = smooth. Punchy response yields extremely short attack and release
times, useful for transparent limiting, or to create loudness. However, if over-
used, intermodulation distortion may result. Smooth response uses longer attack
and release times. The result is still a fast look-ahead limiter, but with less
intermodulation distortion and less punch.
outgain post-limiter-gain [float] The word outgain, followed by a number, sets the gain in dB applied to the signal
after limiting.
saveSettings The word saveSettings causes all parameter values to be sent out the third outlet.
threshold limiter-threshold [float] The word threshold, followed by a number, sets the limiter threshold (in dB
below full scale). When the input signal level exceeds this threshold, it will be
attenuated as necessary to keep the level below the threshold.
signal Audio input, the signal or pair of signals to be compressed.

Information for box attributes common to all objects

Output
list: Out third outlet: parameter values in response to saveSettings message.

Out fourth outlet: meter data. When metering is turned on, lists of values will be output that describe various internal levels. See
the description of the meters message, above.

signal: Out leftmost two outlets: the input signals (if present), with dynamics processing applied.

Examples

See Also
Name Description
omx.4band~ OctiMax 4-band Compressor
omx.5band~ OctiMax 5-band Compressor
omx.comp~ OctiMax Compressor
MSP Compression Tutorial 1: MSP Compression Tutorial 1: Peak Limiting
Peak Limiting
onepole~
Single-pole lowpass filter

Description
The onepole~ object implements the simplest of IIR filters, providing a 6dB per octave attenuation. This filter is very efficient
and useful for gently rolling off harsh high end and for smoothing out control signals.

Arguments
Name Units Type Opt Description
center-frequency hz float opt Sets the center frequency for the filter, as described above.
Hz/linear/radians symbol opt Using the symbols Hz, linear, or radians for an optional second argument sets
the frequency input mode. The default mode is Hz (which is the same as providing
no mode argument). Using the linear argument sets the frequency input mode to
linear (0 - 1). Using the radians argument sets the frequency input mode to
radians (0 - 1).

Messages
int center-frequency (Hz) [int] In right inlet: Sets the frequency for the filter (if no signal is connected). By
default, frequency is expressed in Hz, where the allowable range is from 0 to one
fourth of the current sampling rate. For convenience, onepole~ has two
additional input modes that use the more conventional input range, 0 - 1 (see the
linear and radians messages).
float center-frequency (Hz or 0 In right inlet: Sets the frequency for the filter (if no signal is connected). By
through 1 specified by object- default, frequency is expressed in Hz, where the allowable range is from 0 to one
argument) [float] fourth of the current sampling rate. For convenience, onepole~ has two
additional input modes that use the more conventional input range, 0 - 1 (see the
linear and radians messages).
Hz In either inlet: Sets the frequency input mode to Hz (the default).
clear In either inlet: Clears the internal state of onepole~. Since onepole~ does not have
the inherent instability of other filter types, this should never be necessary.
linear In either inlet: Sets the frequency input mode to linear (0 - 1). Linear mode is
simply a scaled version of the standard Hz mode, except that values in the 0-1
range traverses the full frequency range.
radians In either inlet: Sets the frequency input mode to radians (0 - 1). Radians mode lets
you set the center frequency (f_c) of the equation directly, while the input has the
same range (0-1), the output has a curved frequency response that is closer to the
exponential pitch scale of the human ear.
signal In left inlet: Signal to be filtered.

In right inlet: A signal can be used to set the frequency for the filter, with the same
effect as a float. If a signal is connected to this inlet, its value is sampled once every
signal vector.

Information for box attributes common to all objects

Output
signal: The filtered signal.

Examples
onepole~ provides efficient filtering for a simple sample player

See Also
Name Description
biquad~ Two-pole, two-zero filter
comb~ Apply a comb filter effect
cross~ Third-order crossover filter
lores~ Resonant lowpass filter
reson~ Resonant bandpass filter
svf~ State-variable filter with simultaneous outputs
Audio Filtering Audio Filtering
oscbank~
Non-interpolating oscillator bank

Description
oscbank~ is a non-interpolating oscillator bank with signal inputs to set oscillator frequency and magnitude.

Arguments
Name Units Type Opt Description
number-of-oscillators int opt The number of oscillators.
frequency-smoothing- int opt The number of samples across which frequency smoothing is done.
factor (samples)
amplitude-smoothing- int opt The number of samples across which amplitude smoothing is done.
factor (samples)
lookup-table-size int opt The size, in samples, of the sinewave lookup table used by the oscbank~ object.
(samples) The default is 4096. Since oscbank~ uses uninterpolated oscillators, you can
choose to use a sinetable of larger size at the expense of CPU.

Note: There is only one wavetable for all oscillators in a given oscbank~ object,

Messages
int inlet-specific-parameter- Performs the same function as float in any inlet (see signal and float messages).
settings [int]
float inlet-specific-parameter- In left inlet: Sets the frequency of the oscillator whose index is currently
settings [float] referenced to the current floating-point value of the signal. The default value is 0.

In 2nd inlet: Sets the magnitude (amplitude) of the oscillator whose index is
currently referenced.

In 3rd inlet: If framesync is enabled using the framesync 1 message, a value in


the range 0-1.0 sets the phase of the oscillator currently being referenced.

In 4th inlet: Sets the index of the oscillator currently being referenced.
clear The word clear sets the frequency of all oscillators to zero and zeros all
amplitudes.
copybuf buffer-object-name In left inlet: The word copybuf, followed by a symbol that specifies a buffer,
[symbol] copies samples from the buffer into the oscbank~ object's internal wavetable. The
offset (samples) [int] number of samples is set using the tabpoints message. An optional second integer
argument specifies the position in the buffer at which samples are loaded (offset).
framesync behavioral-flag (0 or The word framesync, followed by a non-zero number, enables frame synchronous
nonzero) [int] operation. When frame synchronous operation is enabled, a given index's values
will only change or begin their interpolated ramps to the next value when the
index input signal is 0 (or once per n sample frame). Otherwise, a given index's
values will change or begin their interpolated ramps to the next value when the
index input signal is equal to that index. The default is off.
freqsmooth frequency-smoothing- The word freqsmooth, followed by an int, sets the number of samples across
factor (samples) [int] which frequency smoothing is done. The default is 1 (no smoothing).
magsmooth amplitude-smoothing- The word magsmooth, followed by an int, sets the number of samples across
factor (samples) [int] which magnitude (amplitude) smoothing is done on a oscillator. The default is 0
(no amplitude smoothing).
set frequency-amplitude- The word set, followed by pairs of floating-point values, sets the frequency and
pairs (floats) [list] amplitude of an oscillator in the oscillator bank. A list of n pairs will set the first n
oscillators in the oscbank~ object and zero the amplitude of all others.
silence The word silence zeros the amplitude of all the oscillators.
size number-of-oscillators The word size, followed by a number, sets the number of oscillators. The default
[int] is 64. The maximum number of oscillators is set by the argument first argument to
the object.
tabpoints lookup-table-size The word tabpoints, followed by a number, sets the number of wavetable points
(samples) [int] (samples) in the oscbank~ object's internal wavetable. The default is 4096. The
number of wavetable points should be a power or two between 2 and 2 16 . Any
other value will be rounded to the nearest power of two.
signal In left inlet: Sets the frequency of the oscillator whose index is currently
referenced to the current floating-point value of the signal. The default value is 0.

In 2nd inlet: Sets the magnitude (amplitude) of the oscillator whose index is
currently referenced.

In 3rd inlet: If framesync is enabled using the framesync 1 message, a signal in


the range 0-1.0 sets the phase of the oscillator currently being referenced.

In 4th inlet: Sets the index of the oscillator currently being referenced.

Information for box attributes common to all objects

Output
signal: A waveform consisting of the sum of the specified frequencies and amplitudes.

Examples

oscbank~ creates a bank of oscillators that you can control with one object

See Also
Name Description
ioscbank~ Interpolating oscillator bank
out
Message output for a patcher loaded by poly~ or pfft~

Description
out defines a message outlet for a patcher loaded by poly~ or pfft~.

Arguments
None.

Messages
bang Sends bangs out the corresponding outlet of the pfft~ or poly~ object in which it
is embedded.
int output [int] Sends integer values out the corresponding outlet of the pfft~ or poly~ object in
which it is embedded.
float output [float] Sends floating-point values out the corresponding outlet of the pfft~ or poly~
object in which it is embedded.
list output [list] Sends lists out the corresponding outlet of the pfft~ or poly~ object in which it is
embedded.
anything output [list] Sends input out the corresponding outlet of the pfft~ or poly~ object in which it is
embedded.
comment outlet-description [list] Sets a comment for display on poly object outlet mouseover

Attributes
Name Type g/s Description
attr_comment symbol Comment to be displayed on poly object outlet mouseover

Information for box attributes common to all objects

Output
(patcher): Any messages received by an out object in a loaded patcher appear at the signal outlet of the poly~ or pfft~ object
which corresponds to the number argument of the out object. The signal outputs in a poly~ or pfft~ object are a mix of the
outputs of all instances of the patcher's outputs which correspond to that number.

Examples

Message outlets of the poly~ object correspond to the out objects inside the loaded patcher

See Also
Name Description
in Message input for a patcher loaded by poly~ or pfft~
in~ Signal input for a patcher loaded by poly~
Message output for a patcher loaded by poly~ or pfft~
out~ Signal output for a patcher loaded by poly~
pfft~ Spectral processing manager for patchers
poly~ Manage polyphony/DSP for patchers
thispoly~ Control poly~ voice allocation and muting
MSP Tutorial 21: Using the poly~ MSP Tutorial 21: Using the poly~ Object
Object
out~
Signal output for a patcher loaded by poly~

Description
Use the out~ object inside a patcher loaded by the poly~ object to create a patcher signal outlet.

Arguments
Name Units Type Opt Description
outlet-number int Specifies the signal outlet number in a poly object. The first outlet is 1.

Messages
comment outlet-description [list] Sets a comment for display on poly object outlet mouseover
signal Outputs a signal to a loaded poly object.

Attributes
Name Type g/s Description
attr_comment symbol Comment to be displayed on poly object outlet mouseover

Information for box attributes common to all objects

Output
(patcher): Any signals received by an out~ object in a loaded patcher appear at the signal outlet of the poly~ object which
corresponds to the number argument of the out~ object. The signal outputs in a poly~ object are a mix of the outputs of all
instances of the patcher's outputs which correspond to that number.

Examples

Signal outlets of the poly~ object correspond to the out~ objects inside the loaded patcher

See Also
Name Description
in Message input for a patcher loaded by poly~ or pfft~
in~ Signal input for a patcher loaded by poly~
out Message output for a patcher loaded by poly~ or pfft~
poly~ Manage polyphony/DSP for patchers
thispoly~ Control poly~ voice allocation and muting
MSP Tutorial 21: Using the poly~ MSP Tutorial 21: Using the poly~ Object
Object
overdrive~
Soft-clipping signal distortion

Description
The overdrive~ object uses a waveshaping function to distort audio signals. It amplifies signals, limiting the maximum value of
the signal to +/- 1. Values outside of this range are removed using "soft clipping" somewhat like that of an overdriven tube-based
circuit.

Arguments
Name Units Type Opt Description
drive-factor float opt A single number can be provided to set the drive factor. If no argument is
provided, the drive factor is set to 1.0.
drive-factor int Integer inputs are converted to float and set the drive factor.

Messages
int drive-factor [int] Integer inputs are converted to float and set the drive factor. The drive factor
should usually be in the range 1 - 10. Using a factor of 1 creates a linear response
without distortion, and higher values increase the distortion. Values less than 1,
including negative values, produce very heavily distorted signals. Use with caution.
float drive-factor [float] In right inlet: The overdrive~ object accepts a floating-point "drive factor". The
drive factor should usually be in the range 1.0-10.0. Using a factor of 1.0 creates a
linear response without distortion, and higher values increase the distortion.
Values less than 1, including negative values, produce very heavily distorted
signals. Use with caution, this behavior was originally considered a bug until
friends of the object's creator insisted that it should be considered a feature and
left intact.)
signal In left inlet: the signal to be distorted.

In right inlet: the drive factor as a signal value.

Information for box attributes common to all objects

Output
signal: The distorted signal.

Examples

Waveshape a signal similar to an overdriven amplifier

See Also
Name Description
kink~ Distort a sawtooth waveform
lookup~ Transfer function lookup table
pass~
Eliminate noise in a muted subpatcher

Description
pass~ is used above any outlet object that will handle a signal. When the audio in the subpatch is enabled, the pass~ object will
pass its input to its output. However, when the audio in the subpatch is disabled using mute~ or the enable 0 message to
pcontrol, pass~ will send a zero signal out its outlet.

Arguments
None.

Messages
signal The signal input is passed to the object's output unless a signal network is disabled
using mute~ or the enable 0 message sent to pcontrol, in which case, pass~
ensures that the signal network to which it is attached is turned off (outputs a 0-
signal).

Information for box attributes common to all objects

Output
signal: When the audio in a subpatch containing pass~ is enabled, the output is the same as the input. When the audio is
disabled using mute~ or the enable 0 message to pcontrol, the output is a zero signal.

Examples

pass~ ensures that a muted signal is fully silenced

See Also
Name Description
mute~ Disable signal processing in a subpatch
MSP Tutorial 5: Turning Signals MSP Tutorial 5: Turning Signals On and Off
On and Off
peakamp~
Report the maximum amplitude of a signal

Description
Use the peakamp~ object to monitor an incoming signal and reports the absolute value of the peak amplitude of the signal it has
received since the last time it was reported.

Arguments
Name Units Type Opt Description
output-interval ms int opt Sets the internal clock interval, in milliseconds. If it is 0, the internal clock is not
used, so peakamp~ will only output data when it receives a bang message. If it is
non-zero, peakamp~ will repeatedly send out the peak amplitude received in that
interval of time. By default, the interval is 0.

Messages
bang In left inlet: Sends out a report of the greatest (absolute value) signal amplitude
received since the previous report.
signal In left inlet: Signal to be evaluated for its peak amplitude.

Information for box attributes common to all objects

Output
float: When peakamp~ receives a bang or its internal clock is on, the absolute value of the peak signal value from the input
signal is sent out its outlet.

Examples

Report the maximum of a signal's absolute value

See Also
Name Description
meter~ Visual peak level indicator
snapshot~ Convert signal values to numbers
peek~
Read and write sample values

Description
Use peek~ to read and write sample values to a named buffer~. Unlike related objects index~ and poke~, values and indices are
specified as Max messages, and the object will function even when the audio is not turned on.

Arguments
Name Units Type Opt Description
buffer-name symbol Buffer name
buffer-channel int opt Buffer channel to read/write
clipping-enable- int opt If set to 1, then values written to the buffer~ will be clipped to within -1.0 to 1.0.
flag See the clip message.

Messages
int sample-index [int] The value stored at the specified sample-index is sent out the peek~ object's
outlet. However, if a value has just been received in the middle inlet, peek~ stores
that value in the buffer~ at the specified sample index instead. If the sample-
index is out of range for the buffer~, no data is read or written.
(inlet2) buffer-channel [int] Set buffer~ channel for reading/writing
float sample-index/buffer- Floating-point values are converted to int values.
channel [float]
In left inlet: Set the sample to be stored.
In right inlet: Set the buffer channel.
(inlet1) sample-value [float] Set sample value to be stored in the associated buffer~. The next sample-index
received in the left inlet causes this sample-value to be stored at that index.
list sample-index [int] The value is stored in the buffer~ at the specified sample-index and buffer-
value [number] channel. If the buffer-channel is omitted, the most recent channel is used. If the
buffer-channel [int] sample-index is out of range for the buffer~, no data is written.
clip clipping-enable-flag [int] If set to 1, then values written to the buffer~ will be clipped to within -1.0 to 1.0.
Disable by setting to 0.
(mouse) Double-click to view the buffer~ contents
set buffer-name [symbol] Set buffer~ to read/write

Information for box attributes common to all objects

Output
float: The sample value in a buffer~, located at the table index specified by a float or int received in the left inlet, is sent out the
peek~ object's outlet.

Examples

Peek at samples in a buffer~, and/or set the value of the samples


See Also
Name Description
buffer~ Store audio samples
buffir~ buffer-based FIR filter
index~ Read from a buffer~ with no interpolation
poke~ Write sample values to a buffer by index
table Store and edit an array of numbers
pfft~
Spectral processing manager for patchers

Description
The pfft~ object is designed to simplify spectral audio processing using the Fast Fourier Transform (FFT). In addition to
performing the FFT and the Inverse Fast Fourier Transform (IFFT), pfft~ (with the help of its companion fftin~ and fftout~
objects) manages the necessary signal windowing, overlapping and adding needed to create a real-time Short Term Fourier
Transform (STFT) analysis/resynthesis system.

Arguments
Name Units Type Opt Description
subpatch- symbol Name of subpatch to load
name
FFT-size samples int opt Specifies the FFT size, in samples, of the overlapped windows which are
transformed to and from the spectral domain by the FFT/IFFT. The window size
must be a power of 2, and defaults to 512. (Note: The size of the spectral "frames"
processed by the pfft~ object's subpatch will be half this size, as the 2nd half of
the spectrum is a mirror of the first, and thus redundant.)
overlap-factor int opt The third argument determines the overlap factor for FFT analysis and resynthesis
(hop-size- windows. The hop size (number of samples between each successive FFT window)
denominator) of Fast Fourier transforms performed is equal to the size of the Fast Fourier
transform divided by the overlap factor (e.g. if the frame size is 512 and the overlap
is set to 2 then the hop size is 256 samples). The value must be a power of 2 and
defaults to 2.
start-onset samples int opt The fourth argument specifies the start onset in samples for the Fast Fourier
transform. It must be a multiple of the current signal vector size and defaults to 0.
full-spectrum- int opt A non-zero fifth argument may be used to specify "full-spectrum mode". In this
flag (0 or mode, the pfft~ object will internally compute a complex FFT and process full DC
nonzero) to SR mirrored spectra (instead of simply eliminating the redundant half of the
spectrum). This takes up extra computing power, but may be potentially useful in
some of the more esoteric spectral processing applications.

Messages
bang Patchers loaded into a pfft~ object can only accept bang messages by in objects
within the patch. The number of inputs is determined by the in objects in the
enclosed subpatch. See in for details.
int input [int] Integer values sent to the pfft~ object cause the object to act according to the user-
defined functionality within it.
float input [float] Floating-point values sent to the pfft~ object cause the object to act according to
the user-defined functionality within it.
list input [list] Lists sent to the pfft~ object cause the object to act according to the user-defined
functionality within it.
anything input [list] Messages sent to the pfft~ object cause the object to act according to the user-
defined functionality within it.
(mouse) Double-clicking with the mouse on the pfft~ object opens a Max patcher window
containing the patcher loaded by the object.
clear Clears all of the pfft~ object's internal buffers.
mute mute-flag (0 or 1) [int] The word mute, followed by a 1 or 0, will mute or unmute the pfft~, turning off
signal processing within the enclosed subpatch.
open subpatch-filename [int] The word open will open the subpatch loaded into the pfft~ object.
wclose subpatch-filename [int] Closes the enclosed subpatch if it is open.
Attributes
Name Type g/s Description

Information for box attributes common to all objects

Output
message: Any messages received by an out object in a loaded patcher appear at the message outlet of the pfft~ object which
corresponds to the number argument of the out object. The message outlets of a pfft~ object appear to the right of the rightmost
signal outlet.
signal: The output is the result of the FFT-based signal processing subpatch. As with the fft~ and ifft~ objects, pfft~ introduces a
slight delay from input to output (although it is less than half the delay than with an fft~ / ifft~ combination). The I/ O delay is
equal to the window size minus the hop size (e.g., for a 1024-sample FFT window with an overlap factor of 4, the hop size is
equal to 256, and the overall delay from input to output is 768 samples). The number of outlets is determined by the number of
fftout~ and/or out objects in the loaded subpatcher. Patchers loaded into a pfft~ object can be given outlets by fftout~ or out
objects within the patch. See fftout~ and out for details.

Examples

pfft~ loads subpatchers specially designed for frequency domain processing

See Also
Name Description
cartopol Convert cartesian to polar coordinates
cartopol~ Signal Cartesian to Polar coordinate conversion
fft~ Fast Fourier transform
fftin~ Input for a patcher loaded by pfft~
fftinfo~ Report information about a patcher loaded by pfft~
fftout~ Output for a patcher loaded by pfft~
frameaccum~ Compute "running phase" of successive phase deviation frames
framedelta~ Compute phase deviation between successive FFT frames
ifft~ Inverse fast Fourier transform
in Message input for a patcher loaded by poly~ or pfft~
out Message output for a patcher loaded by poly~ or pfft~
poltocar Convert polar to cartesian coordinates
poltocar~ Signal Polar to Cartesian coordinate conversion
vectral~ Vector-based envelope follower
MSP Tutorial 25: Using the FFT MSP Tutorial 25: Using the FFT
MSP Tutorial 26: Frequency MSP Tutorial 26: Frequency Domain Signal Processing with pfft~
Domain Signal Processing with
pfft~
phaseshift~
Distort the phase of a signal

Description
The phaseshift~ object is a 2nd-order allpass filter.

Arguments
Name Units Type Opt Description
frequency number opt Center frequency of the phase transition band
q number opt Q (bandwidth) of the phase transition band

Messages
float frequency/Q [float] Middle inlet: frequency at which signals will be shifted by 180 degrees

Right inlet: "Q" factor (steepness with which the phase shifts from 0 to 360
degrees)
clear Reset filter state to zero internal feedback
signal Left inlet: the signal to be shifted in phase

Middle inlet: frequency at which signals will be shifted by 180 degrees

Right inlet: "Q" factor (steepness with which the phase shifts from 0 to 360
degrees)

Information for box attributes common to all objects

Output
signal: The input signal, its the frequency components or harmonics shifted in phase from zero to 360 degrees, dependent upon
their frequency and the values of the object's frequency and Q parameters.

Examples

Simulate an analog phase shifter using phaseshift~ and an LFO

See Also
Name Description
allpass~ Apply an allpass filter effect
comb~ Apply a comb filter effect
phasewrap~
Wrap a signal between and -

Description
phasewrap~ takes any input signal and wrap it between and - values.

Arguments
None.

Messages
signal The signal to be wrapped. If the input signal value exceeds (3.14159), the output
signal value is "wrapped" to a range whose lower bound is - (-3.14159). Thus a
signal of increasing value outputs a sawtooth waveform with - and as lower and
upper values.

Information for box attributes common to all objects

Output
signal: The wrapped input signal value.

Examples

Use phasewrap~ to make sure that signals stay within normal radial values

See Also
Name Description
cartopol~ Signal Cartesian to Polar coordinate conversion
pfft~ Spectral processing manager for patchers
pong~ Variable range signal folding
MSP Tutorial 26: Frequency MSP Tutorial 26: Frequency Domain Signal Processing with pfft~
Domain Signal Processing with
pfft~
phasor~
Generate sawtooth signals

Description
Use the phasor~ object to generate sawtooth waves suitable for sample-accurate control and timing tasks. For smoother sounding
sawtooth generation, use the bandlimited saw~ object instead. The ramp rate can be set by frequency (Hz), or as an interval using
the the tempo-relative Max time format syntax.

Arguments
Name Units Type Opt Description
initial- time-value list opt Set the initial frequency in Hz, or as an interval using the the tempo-relative Max
frequency time format syntax.

Messages
int frequency [int] In left inlet: Set the frequency of the sawtooth waveform (Hz). If a signal is
connected to this inlet, this message is ignored.

In right inlet: Set the phase of the waveform (from 0 to 1). Signal output continues
from this phase.
float frequency [float] In left inlet: Set the frequency of the sawtooth waveform (Hz). If a signal is
connected to this inlet, this message is ignored.

In right inlet: Set the phase of the waveform (from 0 to 1). Signal output continues
from this phase.
list transport/time-settings [list] Set ramp interval in Max time format.
anything transport/time-settings [list] Set ramp interval in Max time format.
signal Set frequency in Hz

Attributes
Name Type g/s Description
frequency atom Frequency
lock int 'Scheduler in Overdrive' and 'in Audio Interrupt' must be enabled for accurate
timing. These settings can be changed in 'Options'-> 'Audio Status'.

Information for box attributes common to all objects

Output
signal: Sawtooth waveform that increases from 0 to 1 repeatedly at the specified frequency.

Examples

A repeating ramp is useful both at audio and at sub-audio frequencies

See Also
Name Description
2d.wave~ Two-dimensional wavetable
cycle~ Sinusoidal oscillator
line~ Linear ramp generator
saw~ Antialiased sawtooth oscillator
sync~ Synchronize MSP with an external source
techno~ Signal-driven step sequencer
transport Control a master clock
trapezoid~ Trapezoidal wavetable
triangle~ Triangle/ramp wavetable
wave~ Variable size wavetable
MSP Tutorial 3: Wavetable MSP Tutorial 3: Wavetable Oscillator
Oscillator
MSP Tutorial 15: Variable-length MSP Tutorial 15: Variable-length Wavetable
Wavetable
pink~
Pink noise generator

Description
pink~ generates pink noise, as distinguished from white noise (which the MSP object noise~ generates). White noise has constant
spectral power per hertz of bandwidth, while pink noise has constant power per octave. Subjectively, pink noise sounds less hissy
than white noise.

Arguments
None.

Information for box attributes common to all objects

Output
signal: The pink~ object generates a signal consisting of random value in the range -1.0 to 1.0, with an even distribution of
power per octave of frequency. Noise with this power distribution is known as "pink noise". "White noise", as generated by the
object noise~, has an even distribution of power over all frequencies. Perceptually, white noise sounds bright and harsh, and
pink noise sounds more even and "natural".

Examples

pink~ generates random numbers such that the frequency content is equal power per octave

See Also
Name Description
noise~ Generate white noise
play~
Position-based sample playback

Description
Use the play~ object as a playback interface for a buffer~. that plays back samples based on an offset within the buffer. It is
typically used with the line~ object, but can be used with any signal that generates a changing position value in milliseconds. The
groove~ object provides another option for sample playback.

Arguments
Name Units Type Opt Description
buffer-name symbol The first argument names the buffer~ object whose sample memory is used by
play~ for playback.
number-of- int opt Specifies the number of output channels: 1, 2, or 4. The default number of
output-channels channels is one. If the buffer~ being played has fewer channels than the number
of play~ output channels, the extra channels output a zero signal. If the buffer~
has more channels, channels are mixed.

Messages
int start/stop-playback [int] In left inlet: 1 (or non-zero value) begins playback of the currently set buffer~
object, and 0 stops playback.
(mouse) Double-clicking on buffer~ opens a display window where you can view the
contents of the buffer~. object that the play~ object references.
interptime crossfade-duration [float] In left inlet: the word interptime, followed by a duration in milliseconds, sets the
crossfade time for loop interpolation (see loopinterp message). If the value given
is greater than the total loop duration, the total loop duration is used. The default
crossfade duration is 50 milliseconds.
loop loop-flag [int] In left inlet: the word loop, followed by a non-zero number, enables loop
playback. In loop mode, when playback reaches the end time (see start message)
it continues again from the start time. loop 0 disables loop playback. In this case,
playback will continue until the end time is reached. Loop mode is off by default.
loopinterp interpolation-flag [int] In left inlet: the word loopinterp, followed by a non-zero number, enables
interpolation around the start and end points for a loop. loop 0 turns off
interpolation. By default, loop interpolation mode is off.
pause In left inlet: Sending the message pause causes the playback to pause at its
current playback position. Playback can be restarted with the resume message.
set buffer-name [symbol] The word set, followed by the name of a buffer~ object, uses that buffer~ for
playback.
signal In left inlet: The position (in milliseconds) into the sample memory of a buffer~
object from which to play. If the signal is increasing over time, play~ will play the
sample forward. If it is decreasing, play~ will play the sample backward. If it
remains the same, play~ outputs the same sample repeatedly, which is equivalent
to a DC offset of the sample value.

The direction and speed of playback of a play~ object can be set using integer
messages provided to the play~ object at signal rate. Typically, this is done using a
line~ object.

Integer messages come in pairs - an initial integer that specifies the position in the
buffer (in milliseconds) at which to start, followed by a second pair of numbers
that specify the ending position in the buffer and the time (in milliseconds) over
which the playback will occur. These messages are often sent as messages
separated by a comma. Here are some examples:

0, 2000 2000- Starting at the beginning of the buffer, play 2 seconds of audio at
normal speed
500, 0 500- Play the first half second of a buffer backwards at normal speed.
0, 1000 500- Play the first second of a buffer at double speed (i.e. transpose it up
an octave)
start start-time [list] In left inlet: The word start, followed by a start time in milliseconds, moves to the
end-time [list] specified position in the current buffer~ and begins playing. After the start time,
duration [list] an optional end time can be specified, which will set a point for playback to stop. A
third optional value can be provided to set the playback duration from the start
point to the end point. When used without arguments, start will begin at the
beginning of the buffer~ and play to the end (equivalent to using the integer value
1 to start playback). The start time may be greater than the end time, in order to
play a segment of the buffer in reverse.
stop In left inlet: The stop message causes the playback to stop at its current playback
position. (This is equivalent to sending the integer value 0 to stop playback).
resume In left inlet: If playback was paused, playback resumes from the paused point in
the audio buffer.

Information for box attributes common to all objects

Output
signal: Sample output read from a buffer~. If play~ has two or four output channels, the left outlet's signal contains the left
channel of the sample, and the other outlets' signals contain the samples from the additional channels.

Examples

play~ is usually driven by a ramp signal from line~, but other signals create novel effects

See Also
Name Description
2d.wave~ Two-dimensional wavetable
buffer~ Store audio samples
buffir~ buffer-based FIR filter
groove~ Variable-rate looping sample playback
record~ Record sound into a buffer
wave~ Variable size wavetable
index~ Read from a buffer~ with no interpolation
MSP Tutorial 13: Recording and MSP Tutorial 13: Recording and Playback
Playback
plot~
Visualize sets of data on a two-dimensional graph

Description
Use the plot~ object to graph sets of data as points across a domain. The source of the data to be visualized may be a Max list, an
MSP buffer~, or an audio signal. The number of plots may be changed with the @numplots attribute, and each of these
"subplots" is addressed through a dedicated inlet. A variety of out-of-the-box configurations are provided as Max object
prototypes.

Arguments
None.

Messages
int input [int] Set the first value of a subplot.
float input [float] Set the first value of a subplot.
list numbers-to-plot [list] Data set to be plotted across the domain. The inlet at which the list is received
determines which subplot graphs the data. If the list is larger than the number of
points in the plot, then the list will be truncated.
definedomain domain-start Define the domain for the subplot associated with the inlet at which the message
[number] is received. The number of actual points will not change, as that is set with the
domain-end [number] @numpoints attribute. This message sets the domain of numbers spanned by
those points. For example, there may be 256 points representing a domain of [0.0,
domain-style [symbol] 1.0]. An optional third argument specifies 'linear' vs 'log' scaling of the domain.

definecolor color [color] Define the color used for drawing the subplot associated with the inlet at which
the message is received. The order of the color components is red, green, blue, and
alpha.
definefilter filter-name [symbol] Defines a filter to be applied to the data set before it is graphed. There are
currently two options available ('none' and 'atodb').
defineline line-style [symbol] Define the style used to display lines in the subplot associated with the inlet at
which the message is received. Options are 'linear', 'lines', 'curve', 'origin', or
'none'.

While 'lines' will display more quickly than 'linear', the 'linear' option will look
better in some cases (usually when working with high thickness values). The
difference between the display styles is related to how line segments are joined at
the elbows: 'lines' does nothing, while the 'linear' option makes smooth
connections.
definenumber number-style Define the style used displaying numbers in the subplot associated with the inlet
[symbol] at which the message is received. Options are 'above', 'below', 'center', or 'none'.
definepoint point-style [symbol] Define the style used to display points in the subplot associated with the inlet at
which the message is received. Options are 'dot', 'circle', 'square', or 'none'.
definerange range-start [number] Define the range for the subplot associated with the inlet at which the message is
range-end [number] received. Values in the displayed data sets that are out of this range will be out of
range-style [symbol] range of the plot drawing.
definethickness line-thickness Define the thickness of the lines for the subplot associated with the inlet at which
[number] the message is received. A thickness of 1 indicates a 1 'pixel' linewidth.
definexgrid x-axis-points [list] Define the points along the domain at which a vertical marker-line should be
drawn for the subplot associated with the inlet at which the message is received.
The points along the domain should be within the range specified by the
'definedomain' message.
defineygrid y-axis-points [list] Define the points along the range at which a horizontal marker-line should be
drawn for the subplot associated with the inlet at which the message is received.
The points along the range should be within the range specified by the
'definerange' message.
definexlabels pairs-of-points-and- Defines the labels for points along the domain for the subplot associated with the
labels [list] inlet at which the message is received. For each point that you wish to be labeled,
you must provide a float-symbol pair defining the location in the domain (as
defined using the 'definedomain' message) and the label for that location.
defineylabels pairs-of-points-and- Defines the labels for points along the range for the subplot associated with the
labels [list] inlet at which the message is received. For each point that you wish to be labeled,
you must provide a float-symbol pair defining the location in the range (as defined
using the 'definerange' message) and the label for that location.
dictionary dictionary-name Configure a subplot. The dictionary may contain the subplot's data, appearance, or
[symbol] both.
edit Open a dictionary editor window for a subplot. After making edits to the plot,
simply close the window and the changes will take effect.
getdictionary subplot-number [int] Retrieve the state of a subplot. The returned dictionary will contain the subplot's
complete state including both data and appearance configuration.
(mouse) Send mouse position and behavior to the outlet
signal Signal whose samples will be collected and used as the dataset to display. The
samples will be collected into blocks that are the same size as the numpoints
attribute unless an audioframesize has been defined.
refer buffer-name [symbol] Set the subplot for the given inlet to reference the data in a named buffer~ object.
channel-number If a second argument is given to this message, it will determine the channel within
[number] the buffer~ that should be displayed.
start-time [number]
end-time [number]

Attributes
Name Type g/s Description
audioframerate float Speed for display update when a plot~ is visualizing an audio signal. The drawing
def.:15. for such cases is driven by a clock operating at the specified number of frames per
second.
audioframesize int Number of samples collected from audio input to create a single frame of data. By
def.:0 default, audio signals will be visualized by collecting sample values until the
number of points in the plot is full (audioframesize=0). Then all points will be
updated and drawn. An alternate audioframesize value must be greater than the
value of the numpoints attribute.

In some cases it is desirable to collect a larger set of samples and then visualize
only a portion of those samples. To visualize the output of an FFT, for example, it
is often desirable to only view either the first or second half of a frame because
they are mirror images of each other. By setting the audioframesize, the number of
points in @audioframesize will be collected, and only the first @numpoints will
actually be drawn.
bgcolor float Background Color
def.:1. 1. 1. 1.
domainlabel symbol Label for the Domain
def.:
fontname symbol Font Name
def.:Verdana
fontsize float Font Size
def.:10.
margins float Margins
def.:8. 8. 8. 8.
numplots int Number of data sets to be plotted. The object will grow/absorb inlets as needed.
def.:1 Each 'subplot' will be addressed through its dedicated inlet.
numpoints int Sets the number of points to be displayed across the domain of all plots
def.:4
rangelabel symbol Label for the Range
def.:
thinmode symbol Data-thinning behavior when the size of the data set (number of points) exceeds
def.:sample the number of pixels available to display each point discretely.
'none' = All points will be drawn, and will overlap as needed
'sample' = Number of points will be reduced according to thinto prior to drawing
thinthresh int The point at which the thinmode is invoked to begin reducing the data set. By
def.:10 default this attribute is set to a value of 10, meaning that once there are 10 points
being drawn at the same pixel location on the screen the thinmode will be invoked.
thinto float Factor by which the data set is reduced when the thinmode is invoked. By default
def.:0.2 the factor is 0.2, which results in 5 values being overlapped at a given pixel
location.

Information for box attributes common to all objects

Output
list: The 'mouse' message is sent together with normalized mouse coordinates and the mouse button state.

Examples

See Also
Name Description
filterdetail Detail the characteristics of a filter
scope~ Visualize an audio signal
multislider Display data as sliders or a scrolling display
waveform~ buffer~ viewer and editor
filtergraph~ Edit a filter interactively
spectroscope~ Signal spectrogram or sonogram
Audio Filtering Audio Filtering
plugin~
Define a Max for Live device's audio inputs

Description
The plugin~ object receives its input from the Live application as part of a Max for Live audio device.

Arguments
None.

Messages
signal By convention, a Max for Live gets all its audio from the Live application using the
plugin~ object and sends its audio output using the plugout~ object. This audio
output is limited to two channels. This behavior is modified when Max for Live is
in Preview Mode.

Information for box attributes common to all objects

Output
signal: When used in Max, the signal output of the plugin~ object is simply its signal input. When used in the runtime plug-in
environment, the signal output will be the left and right channels of the audio input to the plug-in from the host. If the plug-in is
inserted in a mono context, it's possible that only the left channel will contain the incoming audio signal and the right channel
will be 0. The exact nature of the audio input to the plug-in is up to the host mixer.

Examples

See Also
Name Description
plugout~ Define a Max for Live Device's audio outputs
plugout~
Define a Max for Live Device's audio outputs

Description
The plugout~ object sends its output to the Live application as part of a Max for Live Audio device or Instrument.

Arguments
Name Units Type Opt Description
output-channel- int opt Although the plugout~ object will accept one or two int arguments as a courtesy
destination to Max 4 users who wish to port older plug-ins, output channel specifications are
disabled. This behavior is modified when Max for Live is in Preview Mode.

Messages
signal By convention, a Max for Live gets all its audio from the Live application using the
plugin~ object and sends its audio output using the plugout~ object. This audio
output is limited to two channels.

Information for box attributes common to all objects

Output
signal: When used in Max, the signal output of the plugout~ object is simply its signal input. When used in the runtime plug-in
environment, the signal output to the outlets is undefined, and the input is copied to the audio outputs of the plug-in.

Examples

See Also
Name Description
plugin~ Define a Max for Live device's audio inputs
plugphasor~
Host-synchronized sawtooth wave

Description
The plugphasor~ object outputs an audio-rate sawtooth wave that is sample-synchronized to the beat of the Ableton Live
sequencer. The waveform can be fed to other audio objects to lock audio processes to the audio of the host.

Arguments
None.

Information for box attributes common to all objects

Output
signal: The output of plugphasor~ is analogous to phasor~: it ramps from 0 to 1.0 over the period of a beat. If the current host
environment does not support synchronization or the host's transport is stopped, the output of plugphasor~ is a zero signal.

Examples

Drive an oscillator with a beat-synced ramp wave

See Also
Name Description
plugsync~ Report host synchronization information
plugreceive~
Receive audio from another plug-in

Description
Note: plug-in building for hosts other than Ableton Live is no longer supported. For more information to help
you make the transition to creating plug-ins in Max for Live, see Max for Live for Pluggo Developers.
The use of the plugsend~ and plugreceive~ objects to pass audio between Max for Live devices is not supported.

The plugreceive~ and plugsend~ objects were used to send audio signals from one pluggo plug-in to another. They were used in
the implementation of the PluggoBus feature of many of the plug-ins included with pluggo.

Arguments
Name Units Type Opt Description
object-name symbol Gives the plugreceive~ object a name used for connecting with one or more
plugsend~ objects.

Messages
set object-name [symbol] The word set, followed by a symbol naming a plugsend~ object, connects the
plugreceive~ object to the specified plugsend~ object(s), and the plugreceive~
object's audio output becomes the input to the plugsend~. If the symbol doesn't
name a plugsend~ object, the audio output becomes zero.
signal The input to the plugreceive~ object comes from a plugsend~ object to which it
is currently connected. Initially, this will be a plugsend~ having the same name as
the plugreceive~ object's argument.

Information for box attributes common to all objects

Output
signal: The audio signal input to the plugsend~ objects connected to this object. If no plugsend~ objects are connected, the
audio output is zero.

There may be a delay of one processing (I/O) vector size of the host mixer between the plugreceive~ output and the inputs to
the plug-in which the plugreceive~ is located. This occurs when a plugsend~ occurs later in the processing chain than the
plugreceive~ to which it is sending audio.

Examples

See Also
Name Description
plugsend~ Send audio to another plug-in
plugsend~
Send audio to another plug-in

Description
Note: plug-in building for hosts other than Ableton Live is no longer supported. For more information to help
you make the transition to creating plug-ins in Max for Live, see Max for Live for Pluggo Developers.
The use of the plugsend~ and plugreceive~ objects to pass audio between Max for Live devices is not supported.

The plugsend~ and plugreceive~ objects are used to send audio signals from one pluggo plug-in to another. They are used in
the implementation of the PluggoBus feature of many of the plug-ins included with pluggo.

Arguments
Name Units Type Opt Description
object-name symbol Gives the plugsend~ object a name used for connecting with other plugsend~
and plugreceive~ objects.

Messages
signal The input to the plugsend~ object is mixed with other plugsend~ objects, which
can be in the same plug-in or a different plug-in, and is then sent out the signal
outlets of any connected plugreceive~ objects.

Information for box attributes common to all objects

Examples

See Also
Name Description
plugreceive~ Receive audio from another plug-in
plugsync~
Report host synchronization information

Description
The plugsync~ object provides information about the current state of Ableton Live host applicaiton.

Arguments
None.

Messages
bang bang message may be used to manually poll the plugsync~ object that cause it to
output timing information.

Information for box attributes common to all objects

Output
float: Out 4nd outlet: The current beat fraction, from 0 to 1.0. If the host does not support synchronization, the output is 0. If the
host does not support synchronization, there is no output from this outlet.
float: Out 6th outlet: The current tempo in samples per beat. This number can be converted to beats per minute using the
following formula: (sampling-rate / samples-per-beat) * 60. If the host does not support synchronization, there is no output from
this outlet.
float: Out 7th outlet: The current number of beats, expressed in 1 PPQ. This number will contain a fractional part between beats.
If the host does not support synchronization, there is no output from this outlet.
int: Out left outlet: 1 if the host's transport is currently running; 0 if it is stopped or paused.
int: Out 2nd outlet: The current bar count in the host sequence, starting at 1 for the first bar. If the host does not support
synchronization, there is no output from this outlet.
int: Out 3rd outlet: The current beat count in the host sequence, starting at 1 for the first beat. If the host does not support
synchronization, there is no output from this outlet.
int: Out 8th outlet: The current sample count, as defined by the host.
int: Out 9th outlet: A number representing the validity of the other information coming from plugsync~. Mask with the
following values to determine if the information from plugsync~ will be valid.

Sample Count Valid - 1 (always true)

Beats Valid - 2 (2nd, 3rd, 4th, and 7th outlets valid)

Time Signature Valid - 4 (5th outlet valid)

Tempo Valid - 8 (6th outlet valid)

Transport Valid - 16 (left outlet valid)


list: Out 5th outlet: The current time signature as a list containing numerator followed by denominator. For instance, 3/4 time
would be output as the list 3 4. If the host does not support time signature information, there is no output from this outlet.

Examples

See Also
Name Description
plugphasor~ Host-synchronized sawtooth wave
+~
Add signals

Description
Use the +~ object to add two signals together, or to add an offset value to a signal.

Arguments
Name Units Type Opt Description
initial-offset number opt Sets an initial offset to add to the signal coming into the left inlet. If a signal is
connected to the right inlet, the argument is ignored. If no argument is present,
and no signal is connected to the right inlet, the initial value is 0 by default.

Messages
int offset [int] In left inlet: An offset to add to the signal coming into the right inlet. If a signal is
also connected to the left inlet, a float or int is ignored.

In right inlet: An offset to add to the signal coming into the left inlet. If a signal is
also connected to the right inlet, a float or int is ignored.
float offset [float] In left inlet: An offset to add to the signal coming into the right inlet. If a signal is
also connected to the left inlet, a float or int is ignored.

In right inlet: An offset to add to the signal coming into the left inlet. If a signal is
also connected to the right inlet, a float or int is ignored.
signal In left inlet: The signal is added to the signal coming into the right inlet, or a
constant value received in the right inlet.

In right inlet: The signal is added to the signal coming into the right inlet, or a
constant value received in the left inlet.

Information for box attributes common to all objects

Output
signal: The sum of the two inputs.

Examples

Mix signals... or add a DC offset to a signal

See Also
Name Description
+=~ Signal accumulator
-~ Signal subtraction
!-~ Signal subtraction (inlets reversed)
+=~
Signal accumulator

Description
+=~ adds all the values it receives. The result can grow very large, very fast.

Arguments
Name Units Type Opt Description
initial-sum float opt Sets the initial value for the sum. The default is 0.

Messages
bang Resets the sum to 0.
set stored-sum [float] The word set, followed by a number, sets the stored value to that number, without
triggering output.
signal Each sample of the input is added to all previous samples to produce a running
sum. For instance, assuming the sum started at 0, an input signal consisting of 1,
1, 1, 1 would produce 1, 2, 3, 4 as an output signal.

Information for box attributes common to all objects

Output
signal: Each sample of the output is the sum of all previous input samples.

Examples

See Also
Name Description
+~ Add signals
poke~
Write sample values to a buffer by index

Description
poke~ allows you to write samples into a buffer~ at sample locations specified by a signal.

Arguments
Name Units Type Opt Description
buffer-object- symbol Obligatory. Names the buffer~ where poke~ will write its incoming samples.
name
channel-number int opt Sets the channel number of a multichannel buffer~ where the samples will be
written. The default channel is 1.

Messages
int value/sample-index [int] In left inlet: Converted to float.

In middle inlet: Sets the sample index for writing subsequent sample values
coming in the left inlet. If there is a signal connected to this inlet, a float is ignored.
(inlet2) channel-number [int] In right inlet: Sets the channel of the buffer~ where sample values are written.
The first (left) channel is specified as 1.
float value/sample- Like the peek~ object, poke~ can write float values into a buffer~. Note,
index/channel-number however, that the left two inlets are reversed on the poke~ object compared to the
[float] peek~ object.

In left inlet: Sets the value to be written into the buffer~ at the specified sample
index. If the sample index is not -1, the value is written.

In middle inlet: Converted to int.

In right inlet: Converted to int.


list value, sample-index, and In left inlet: A list of two or more values will write the first value at the sample
channel-number [list] index specified by the second value. If a third value is present, it specifies the audio
channel within the buffer~ for writing the sample value.
(mouse) Double-clicking on poke~ opens an editing window where you can view the
contents of its associated buffer~ object.
set buffer-object-name [symbol] The word set, followed by the name of a buffer~, changes the buffer~ where
poke~ will write its incoming samples.
signal In left inlet: Signal values you want to write into a buffer~.

In middle inlet: The sample index where values from the signal in the left inlet will
be written. If the signal coming into the middle inlet has a value of -1, no samples
are written.

Information for box attributes common to all objects

Examples
Write into a buffer~ using either signals or numbers

See Also
Name Description
buffer~ Store audio samples
buffir~ buffer-based FIR filter
peek~ Read and write sample values
poltocar~
Signal Polar to Cartesian coordinate conversion

Description
poltocar~ will take any given signal as a polar coordinate and output the cartesian conversion of that signal.

Arguments
None.

Messages
signal In left inlet: The magnitude (amplitude) of the frequency bin to be converted into a
cartesian (real/imaginary) signal pair.

In right inlet: The phase of the frequency bin to be converted into a cartesian
(real/imaginary) signal pair.

Information for box attributes common to all objects

Output
signal: Out left outlet: The real part of a frequency domain signal suitable for input into an ifft~ or fftout~ object.

Out right outlet: The imaginary part of a frequency domain signal suitable for input into an ifft~ or fftout~ object.

Examples

poltocar~ converts amplitude/phase pairs into the Cartesian pairs that fftout~ uses

See Also
Name Description
cartopol Convert cartesian to polar coordinates
cartopol~ Signal Cartesian to Polar coordinate conversion
fft~ Fast Fourier transform
fftin~ Input for a patcher loaded by pfft~
fftinfo~ Report information about a patcher loaded by pfft~
fftout~ Output for a patcher loaded by pfft~
frameaccum~ Compute "running phase" of successive phase deviation frames
framedelta~ Compute phase deviation between successive FFT frames
ifft~ Inverse fast Fourier transform
pfft~ Spectral processing manager for patchers
poltocar Convert polar to cartesian coordinates
vectral~ Vector-based envelope follower
MSP Tutorial 26: Frequency MSP Tutorial 26: Frequency Domain Signal Processing with pfft~
Domain Signal Processing with
pfft~
poly~
Manage polyphony/DSP for patchers

Description
Use the poly~ to encapsulate a patcher inside an object box, to specify the patcher filename and the number of instances you want
to load as arguments to the poly~ object, and to control object processing and routing in the loaded patcher instances.

Arguments
Name Units Type Opt Description
patcher-name symbol The first argument must specify the name of a patcher to be loaded which already
exists and is in the Max search path. A subpatch window is not automatically
opened for editing when a patcher argument is supplied for the poly~ object.
number-of- int opt The number of patcher instances corresponds to the number of available "voices"
instances This number can be any number between 1 and 1023, and may be dynamically
changed by using the voices message.
local and flag (0 or symbol opt The arguments local 1 toggle local scheduling for the poly~ object's loaded
1) patcher; the poly~ object maintains its own scheduler that runs during its audio
processing rather than using the global Max scheduler, allowing finer resolution
for events generated by multiple patcher instances. No scheduling occurs if audio
processing is turned off, either globally or locally for the poly~ object or one or
more of its instances. Local scheduling is disabled by default - Scheduler locality is
permanent for any patcher which is loaded, and cannot be changed by sending
messages to the poly~ object.
'up' and up- symbol opt Use the up argument followed by a number which is a power of two to upsample
sampling-factor local DSP processing on the currently loaded patcher (e.g., up 2 specifies 88200
Hz at a sampling rate of 44100 Hz). Upsampling may be dynamically changed by
using the up message.
'down' and down- symbol opt Use the down argument followed by a number which is a power of two to
sampling factor downsample local DSP processing on the currently loaded patcher (e.g., down 2
specifies 22050 Hz at a sampling rate of 44100 Hz). Downsampling may be
dynamically changed by using the down message.
'args' and list-of- symbol opt Use the argument args followed by an argument value to initialize any pound-sign
argument-values arguments in the loaded patcher (e.g., args #1). If used, the args argument must
be the last argument word used; everything which appears after the word args will
be treated as an argument value.

Messages
bang Sends a bang to the patcher loaded into the poly object. The result of the message
is determined by the loaded patcher.
int input [int] Performs functions which are specific to the user-designed poly~ patcher itself.
float input [float] Performs functions which are specific to the user-designed poly~ patcher itself.
list message [list] To send a message to a poly~ instance that starts with one of the words used to
control the poly~ object itself, begin the message with the word list. For example,
the message list target 2 sent to the left inlet of poly~ will output target 2 out
the outlet of all in 1 objects, rather than changing the current target instance to
the second patcher.
anything message [list] The number of inlets and outlets for poly~ is determined by the patcher that is
loaded. The inlets for the patcher loaded by a poly~ object accept both signal and
event connections.

The signals are routed inside of the loaded patcher by using the in~ objects for
signals or the in object for events. The number of total inlets in a poly~ object is
determined by the highest number of an in~ or in object in the loaded patcher
(e.g., if there is an in~ with argument 3 and an in with argument 4, the poly~
object will have four inlets. All the inlets accept signal connections even though
there may not be an in~ object corresponding to each inlet.

Signal inputs are fed to all instances.


(drag) Loads a file when dragging a patch from the Max File Browser to a poly~ object.
allnotesoff Disables all playing notes by sending a message to each instance with a playing
note consisting of the MIDI pitch most recently received via the note or midinote
message followed by a zero velocity (note off message).
busymap message-outlet-number Reports the voice busy state for the number specified as the argument out the
[int] specified message outlet of the poly~ object.
(mouse) Double-clicking on the poly~ opens a display window where you can view the
contents of a loaded patcher.
down 'down' and sampling- Use the up argument followed by a number which is a power of two to
factor [int] downsample local DSP processing on the currently loaded patcher (e.g., down 2
specifies 22050 Hz at a sampling rate of 44100 Hz). Downsampling may be
dynamically changed by using the down message. Although both up and down
are permissible messages to the poly~ object, the down message takes precedence
over up.
exclude voice-number [int] Sending the word exclude, followed by a voice number and a one, prevents a
status [int] poly~ instance from being sent messages via note allocation when the poly~
receives a note or midinote message. By default, all voices are enabled for note
allocation. The word exclude, followed by a voice number and a zero re-enables
the instance to receive messages when the poly~ receives a note or midinote
message.
mute instance [int] Turns off signal processing for the specified instance of of a patcher loaded by the
on/off-flag [int] poly~ object and sends a bang message to the thispoly~ object for the specified
instance. Sending a 0 as the second argument turns the patcher instance on. The
message mute 0 1 mutes all instances, and mute 0 0 turns on signal processing
for all instances of the patcher. If all are muted using a mute 0 1 message,
individual instances cannot be unmuted until all are unmuted with a mute 0 0
message.
open instance-index [int] The word open, followed by a number, opens the specified instance of the
patcher. You can view the activity of any instance of the patcher up to the number
of voices (set by the voices message or by an argument to the poly~ object). With
no arguments, the open message opens the instance that is currently the target
(see the target message).
note voice-allocated-data [list] The word note, followed by a message, will send the data to the first in object of
the first instance of the patcher that has not marked itself "busy" by sending a 1 to
a thispoly~ object inside the patcher instance.
midinote voice [int] The midinote message is followed by two or more values. While note values are
note-values [list] ordinarily two numbers that specify a MIDI note number and a velocity value, any
numbers may be used for patches which work differently than the standard MIDI
model.

If the second note value is not 0, the poly~ object routes the pitch velocity to the
first available instance. If the velocity is 0 (i.e. a MIDI note-off message), the pitch
velocity will be sent to the poly~ instance that generated the note. To determine
which instance of the loaded patcher the midinote message will be sent to, send a
0 (non-busy) or 1 (busy) message to a thispoly~ object located in the loaded
patcher.
mutemap outlet-number [int] Report voice mutes out of a specified poly~ message outlet
up 'up' and sampling-factor Use the up argument followed by a number which is a power of two to upsample
[int] local DSP processing on the currently loaded patcher (e.g., up 2 specifies 88200
Hz at a sampling rate of 44100 Hz). Upsampling may be dynamically changed by
using the up message. Although both up and down are permissible messages to
the poly~ object, the down message takes precedence over up.
threadcount number of threads [int] The word threadcount, followed by a number, sets the number of threads used to
divide poly~ instances' audio processing. The default is the number of processor
cores available in your computer. Typically, the number of threads should be set to
the number of processor cores in your computer for best performance. This can
also be accomplished by sending the message threadcount 0. If a poly~ object
has sixteen instances and the threadcount is 4, four of the poly~ instances will
process audio in each of four threads.
wclose instance-index [int] Closes the window for the numbered instance specified by the argument. If no
number argument is used, wclose will close the patcher window with the highest
numbered index.

Attributes
Name Type g/s Description
args atom When using messages to specifie arguments for a poly~ object's loaded patch, the
patch must be reloaded by setting the patchername attribute for new arguments
to take effect after initial load.
parallel int When this attribute is set to enable parallel processing, the poly~ object enables
the use of multiple threads to run audio processing for all patcher instances. If
disabled poly~ runs all patcher instances in the audio processing thread. The DSP
chain must be restarted whenever the parallel attribute is changed. This attribute
is disabled it when Max is hosted by the Live application.

Note: At this time, you cannot specify a single subpatcher on a different core.
When enabled, this attribute splits up the number of voices between the number
of processors available. It is primarily intended for patches that use a significant
amount of CPU within multiple voices of the same poly~ object, and the
multithreading overhead is primarily useful for larger signal vector sizes (at least
32 or greater). Other situations will not benefit. Using the default threadcount
(which is equal to the number of physical cores) is best.
patchername symbol The filename of a patcher file loaded into the poly~ object.
resampling int Toggles the use of high-quality resampling filters. These filters are enabled by
default.
steal int Voice stealing enable causes the poly~ object sends the data from the note or
midinote messages to instances that are still marked "busy"; this can result in
clicks depending on how the instances handle the interruption. Voice stealing is
disabled by default.
target int The poly~ instance that will receive subsequent messages (other than messages
specifically used by the poly~ object itself) arriving at the poly~ object's inlets -
for example, The message target 2 routes messages to the second instance. If the
target message specifies a value greater than the current number of instances
(copies) of the loaded patcher, the message will be sent to the highest numbered
instance (e.g., sending the message target 2 to a poly~ object containing only a
single instance will send subsequent messages to the first instance). The message
target 0 sends input to all instances, and using any negative number value with
the target message will disable input to all instances.
voices int Number of Voices
vs int Specifies the signal vector size for the poly~ object's loaded patch. The signal
vector size will be set on the next compilation of the DSP chain. The vs message
does not force a recompilation of the DSP chain. vs 0 specifies no fixed vector size.
The default is the current signal vector size.

Information for box attributes common to all objects

Output
anything: The number of outlets of a poly~ object is determined by the sum of the highest argument numbers of the out and
out~ objects in the loaded patcher. For instance, if there is an out 3 object and an out~ 2 object, the poly~ object will have five
outlets. The signal outputs corresponding to the out~ objects are leftmost in the poly~ object, followed by the event outlets
corresponding to the out objects.

Signals sent to the inlet of out~ objects in each patcher instance are mixed if there is more than one instance and appear at the
corresponding outlets of the poly~ object.

Examples

The poly~ object manages multiple instances of a subpatch

See Also
Name Description
in Message input for a patcher loaded by poly~ or pfft~
in~ Signal input for a patcher loaded by poly~
out Message output for a patcher loaded by poly~ or pfft~
out~ Signal output for a patcher loaded by poly~
patcher Create a subpatch within a patch
thispoly~ Control poly~ voice allocation and muting
MSP Tutorial 20: MIDI Sampler MSP Tutorial 20: MIDI Sampler Control
Control
MSP Tutorial 21: Using the poly~ MSP Tutorial 21: Using the poly~ Object
Object
polybuffer~
Manage multiple buffer~ objects

Description
polybuffer~ lets you operate with a group of buffer~ objects. Each buffer~ will be named after polybuffer~ first argument and
an index (aka for a polybuffer~ toto object, each buffer~ will be named toto.N where N is the index).

Arguments
Name Units Type Opt Description
name symbol Sets the name of the polybuffer~ and defines the names of the buffer~. For
instance, if the polybuffer~ object's name is toto , the buffer~ will be named
toto.1 , toto.2 , toto.3 .... polybuffer~ objects with the same name share the same
buffer~.

Messages
(drag) Drag a sound file and a buffer~ will be added to the list. Drag a folder and the
sound files contained in the folder will be loaded in buffer~ objects.
append filename [list] Display a dialog box to choose a sound file to add to polybuffer~ or load the
sound file specified in argument.
appendempty length () [float] Adds an empty buffer~ of the specified lenght and channels.
channels [int]
(mouse) Double-click on the polybuffer~ object in a locked patcher to open a window
where you can see information about the buffers.
clear Delete every buffer~.
dump Outputs list with the following information: index, buffer name, path of the sound
file, length, channel and sampling rate.
getcount Outputs the message count, followed by the number of buffer~ objects contained
in the polybuffer~ object.
getbufferlist Outputs the message bufferlist followed by the name of the buffer~. When every
buffer~ name has been sent out the outlet, the done message is sent.
getsize Outputs the memory size used by polybuffer~ in Bytes.
getshortname Outputs the buffer~ name followed by the sound files name without the extension.
Outputs done when the iteration is finished.
open Open polybuffer~ object's window see information about the buffers.
readfolder name [list] Loads multple sound files from the specified folder. If no argument is provided a
dialog box will show up.
send index [int] Sends messages to the buffer~ objects. The index corresponds to the buffer~
anything [list] index, and an index of 0 send the message to every buffer~. For instance, send 0
clear sends the message clear to every buffer~ contained in this polybuffer~.
wclose Close the window editor
writetofolder name [list] Writes every buffer~ in a folder. If no argument is provided a dialog box will show
up.

Attributes
Name Type g/s Description
embed int Save the buffer references in the patcher, on save. Note: empty buffers will be
stored as empty buffer: their size and number of channels will be saved, but not
the contents.
quiet int Suppress the warning when loading multiple patches with polybuffer~ with the
same name.
Information for box attributes common to all objects

Examples

See Also
Name Description
buffer~ Store audio samples
pong~
Variable range signal folding

Description
Use the pong~ object to either fold or wrap its input within the range of a low value and a high value.

Arguments
Name Units Type Opt Description
folding-mode int opt An optional argument is used to set the mode of the pong~ A 0 sets signal folding
(the default), and a 1 sets signal wrapping (see the mode message).
low-value float opt When used with the optional mode argument, the low range value for the pong~
object can be specified by a float argument. If only one argument is given following
the mode argument (e.g., pong~ 0 .1), it specifies the low range value of the
pong~ object above which folding occurs, and the high range value is set to 1.0
(the default).
high-value float opt When used with the optional mode argument, the high range value for the pong~
object can be specified by a float argument.

Messages
float input [float] In left inlet: All incoming signal or float values which exceed the high or low value
ranges specified by arguments to the pong~ object are either folded back into this
range (i.e., values greater than one are reduced by one plus the amount that they
exceed one, and negative values are handled similarly) or wrapped (i.e., values
greater than one are reduced by two, and negative values are increased by two),
according to the mode of the pong~ object (see the mode message).

In center or right inlet: The pong~ objects accepts low and high range values for
the range outside of which folding occurs. If the pong~ object has either one or no
arguments, pong~ will have two inlets. The right inlet is used to set the high range
value above which signal folding occurs, the low range value is assumed to be zero.

If the pong~ object has two arguments, the object has three inlets. The center inlet
specifies the low value range below which folding occurs, and the right inlet
specifies the high range limit. The default object has no arguments, and the right
inlet specifies the upper value.

If the current low range value is greater than the high range value, their behavior
is swapped.
mode folding-mode [int] The word mode, followed by a zero or one, sets the folding mode of the pong~
object.

pong 0 sets the pong~ object to signal folding. Values greater than one are
reduced by one plus the amount that they exceed one, and negative values are
handled similarly. This is the default mode of the object.

pong 1 sets the pong~ object to signal wrapping. Values greater than one are
reduced by two, and negative values are increased by two.
signal In left inlet: All incoming signal or float values which exceed the high or low value
ranges specified by arguments to the pong~ object are either folded back into this
range (i.e., values greater than one are reduced by one plus the amount that they
exceed one, and negative values are handled similarly) or wrapped (i.e., values
greater than one are reduced by two, and negative values are increased by two),
according to the mode of the pong~ object (see the mode message).
In center or right inlet: The pong~ objects accepts low and high range values for
the range outside of which folding occurs. If the pong~ object has either one or no
arguments, pong~ will have two inlets. The right inlet is used to set the high range
value above which signal folding occurs, the low range value is assumed to be zero.

If the pong~ object has two arguments, the object has three inlets. The center inlet
specifies the low value range below which folding occurs, and the right inlet
specifies the high range limit. The default object has no arguments, and the right
inlet specifies the upper value.

If the current low range value is greater than the high range value, their behavior
is swapped.

Information for box attributes common to all objects

Output
signal: The folded signal or float value.

Examples

pong~ distorts a signal by folding it or wrapping it around an upper and lower threshold level

See Also
Name Description
phasewrap~ Wrap a signal between and -
pow~
Signal power function

Description
pow~ raises the base value (set in the right inlet) to the power of the exponent (set in the left inlet). Either inlet can receive a
signal, float or int.

Arguments
Name Units Type Opt Description
base-value number opt Sets the base value. The default value is 0. If a signal is connected to the right
inlet, the argument is ignored.

Messages
float exponent/base-value [float] In left inlet: Sets the exponent. If there is a signal connected to the left inlet, a
number received in the left inlet is ignored.

In right inlet: Sets the base value. If there is a signal connected to the right inlet, a
number received in the right inlet is ignored.
signal In left inlet: Sets the exponent.

In right inlet: Sets the base value.

Information for box attributes common to all objects

Output
signal: The base value (from the right inlet) raised to the exponent (from the left inlet).

Examples

Computes the mathematical expression xy for converting to logarithmic or exponential scale

See Also
Name Description
log~ Logarithm of a signal
curve~ Exponential ramp generator
rampsmooth~
Smooth an incoming signal

Description
Smooths an incoming signal across n samples. Each time an incoming value changes, it begins a linear ramp to reach this value.

Arguments
Name Units Type Opt Description
ramp-up-samples int opt Number of samples for ramp-up
ramp-down-samples int opt Number of samples for ramp-down

Messages
signal Each time an incoming value changes, the object begins a linear ramp over a
specified number of samples to reach the new value.
ramp sample-count [int] Specifies the number of samples over which a signal will be smoothed. Each time
an incoming value changes, the rampsmooth~ object begins a linear ramp of the
specified number of samples to reach the new value. The default value is 0.
rampdown ramp-down samples [int] Specifies the number of samples over which a signal will be smoothed when an
incoming value less than the current value arrives.
rampup ramp-up samples [int] Specifies the number of samples over which a signal will be smoothed when an
incoming value greater than the current value arrives.

Information for box attributes common to all objects

Output
signal: The smoothed signal is sent out the outlet.

Examples

rampsmooth~ performs linear smoothing on an input signal

See Also
Name Description
line~ Linear ramp generator
slide~ Filter a signal logarithmically
MSP Compression Tutorial 1: MSP Compression Tutorial 1: Peak Limiting
Peak Limiting
MSP Compression Tutorial 7: MSP Compression Tutorial 7: Keying
Keying
MSP Compression Tutorial 8: MSP Compression Tutorial 8: Microsounds
Microsounds
MSP Compression Tutorial 9: MSP Compression Tutorial 9: Ducking
Ducking
rand~
Band-limited random signal

Description
Use the rand~ object to generate a signal consisting of random values between -1 and 1 generated at a frequency specified by its
input. It interpolates linearly between these values.

Arguments
Name Units Type Opt Description
initial-frequency hz number opt Sets the initial frequency. The default value is 0. If a signal is connected to the
inlet, the argument is ignored.

Messages
int input [int] The frequency at which a new random number between -1 and 1 is generated.
rand~ interpolates linearly between random values chosen at the specified rate. If
there is a signal connected to the inlet, the int is ignored.
float input [float] The frequency at which a new random number between -1 and 1 is generated.
rand~ interpolates linearly between random values chosen at the specified rate. If
there is a signal connected to the inlet, the float is ignored.
signal The frequency at which a new random number between -1 and 1 is generated.
rand~ interpolates linearly between random values chosen at the specified rate.

Information for box attributes common to all objects

Output
signal: A signal consisting of line segments between random values in the range -1 to 1. The random values occur at the
frequency specified by the input.

Examples

Use rand~ to create roughly band-limited noise, or as a control signal to create random variation

See Also
Name Description
line~ Linear ramp generator
noise~ Generate white noise
pink~ Pink noise generator
MSP Tutorial 29: Flanging MSP Tutorial 29: Flanging
MSP Tutorial 30: Chorus MSP Tutorial 30: Chorus
rate~
Time-scale the output of a phasor~

Description
The rate~ object accepts an input signal from a phasor~ and time scales it by a multiplier received as a float in its right inlet.
Numbers less than 1 create several ramps per phase cycle. Numbers greater than 1 create fewer ramps. This can be useful for
implementing a phasor~-synchronized system in MSP.

Arguments
Name Units Type Opt Description
multiplier float opt The multiplier value used to scale the output signal.
sync-mode-flag int opt Sets the sync mode (see the sync message).

Messages
int phase/multiplier [int] In left inlet: Sets the phase value for the rate~ object's signal output.

In right inlet: The signal multiplier value used to scale the phasor~ signal input.
Integer values greater than 1 create fewer ramps. This can be useful for
synchronizing multiple processes to a single reference phasor~ object, preserving
their ratio relationships.
float phase/multiplier [float] In left inlet: Sets the phase value for the rate~ object's signal output.

In right inlet: The signal multiplier value used to scale the phasor~ signal input.
Float values less than 1.0 create several ramps per phase cycle. Numbers greater
than 1.0 create fewer ramps. This can be useful for synchronizing multiple
processes to a single reference phasor~ object, preserving their ratio
relationships.
goto jump-to-value [float] In left inlet: The word goto, followed by a float, causes the rate~ object to jump
time-of-action [float] immediately to the specified value. An optional second argument may be used to
specify the time at which to jump to the value (e.g., goto 1.0 .5 will output a
value of 1.0 at the halfway point of the phasor~ object's input signal ramp).
oneshot loop-flag (0 or nonzero) [int] The message oneshot 1 will turn on "oneshot"-mode whereby rate~ outputs only
one cycle of a ramp. The message oneshot 0 will turn "oneshot"-mode off
whereby rate~ can cycle through ramps continuously when instructed to do so
(i.e. by the sync cycle message).
reset In left inlet: The word reset will lock the output to the input on its next reset. It is
equivalent to the message goto 0. 0.
signal In left inlet: An input signal from a phasor~ object.

In right inlet: The rate~ object time scales the input signal from a phasor~ by a
multiplier value. The multiplier value can be specified as an argument or received
as a float to the rate~ object's right inlet.
sync sync-mode-flag (0 through In left inlet: The word sync, followed by a number between 0 and 2 or the words
2) [list] cycle, lock, or off, sets the sync mode of the rate~ object. The sync mode
determines whether or not the rate~"in" will stay in phase with the input signal,
and the method used for synchronization. When the output of the rate~ object is
"in phase," the input and output signals align precisely at the least common
multiple of their periods (i.e., they pass through zero and begin a new cycle at
precisely the same time). If the signals are in phase, and a new multiplier value is
received, the rate~ object changes the frequency of its output ramp accordingly.
However, the change in multiplier values means that the two signals may be out of
phase. The rate~ object handles this situation in one of three different ways,
depending on the sync mode:
The sync modes are:

cycle: The messages sync 0 or sync cycle set the cycle mode of the rate~ object
(the default mode). In cycle mode, the rate~ object does not change the phase of
its output until the end of the current cycle. When the input ramp reaches its peak
and starts over from zero, the rate~ object immediately restarts the output ramp,
causing a discontinuity in the output signal, and immediate phase synchronization.

lock: The messages sync 1 or sync lock set the lock mode of the rate~ object. In
sync lock mode, the rate~ object performs synchronization whenever a new
multiplier is received. The rate~ object immediately calculates the proper ramp
position which corresponds to being "in phase" with the new multiplier value, and
jumps to that position.

off: The messages sync 2 or sync off disables the sync mode of the rate~ object.
In this mode rate~ never responds to phase differences; when a new multiplier is
received, the rate~ object adjusts the speed of its output ramps and they continue
without interruption. Since this mode never introduces a discontinuous jump in
the ramp signal, it may be useful if phase is unimportant.

Information for box attributes common to all objects

Output
signal: The synchronized signal is sent out the outlet.

Examples

Use rate~ to generate synchronized waveforms or control sources

See Also
Name Description
phasor~ Generate sawtooth signals
sync~ Synchronize MSP with an external source
techno~ Signal-driven step sequencer
!/~
Signal division (inlets reversed)

Description
The !/~ object functions just like the /~ object, but the inlet order is reversed.

Arguments
Name Units Type Opt Description
initial-divisor number opt Sets an initial value by which to divide the signal coming into the left inlet. If a
signal is connected to the right inlet, the argument is ignored. If no argument is
present, and no signal is connected to the right inlet, the initial value is 1 by
default.

Messages
int input [int] In left inlet: A number by which to divide the signal coming into the right inlet. If a
signal is also connected to the left inlet, a float or int is ignored.

In right inlet: The number is divided by the signal coming into the left inlet. If a
signal is also connected to the right inlet, a float or int is ignored.
float input [float] In left inlet: A number by which to divide the signal coming into the right inlet. If a
signal is also connected to the left inlet, a float or int is ignored.

In right inlet: The number is divided by the signal coming into the left inlet. If a
signal is also connected to the right inlet, a float or int is ignored.
signal In left inlet: The signal is used as the divisor, to be divided into the signal coming
into the right inlet, or the constant value received in the right inlet.

In right inlet: The signal is divided by a signal coming into the left inlet, or a
constant value received in the left inlet.

Information for box attributes common to all objects

Output
signal: The ratio of the two inputs, i.e. the right input divided by the left input.

Examples

/~ with the inlets reversed

See Also
Name Description
*~ Multiply two signals
receive~
Signals can be received from any loaded patcher, without patch cords

Description
Use the receive~ object to grab signals put out by send~ objects and outputs them out its signal outlet.

Arguments
Name Units Type Opt Description
object-name symbol Sets the name of the receive~ object.

Messages
set object-name [symbol] The word set, followed by a symbol, changes the name of the receive~ so that it
connects to different send~ objects that have the symbol as a name. If no send~
objects exist with the name, the output of receive~ is 0.
signal The receive~ object receives signals from all send~ objects that share its name. It
adds them together and sends the sum out its outlet. If no send~ objects share the
current name, the output of receive~ is 0. The send~ objects need not be in the
same patch as the corresponding receive~.

Information for box attributes common to all objects

Output
signal: The combination of all signals coming into all send~ objects with the same name as the receive~.

Examples

Signals can be received from any loaded patcher, without patch cords

See Also
Name Description
send~ Send signals without patch cords
MSP Tutorial 4: Routing Signals MSP Tutorial 4: Routing Signals
record~
Record sound into a buffer

Description
record~ records a signal into a buffer~ object. You can record up to 4 channels by specifying the optional argument. Recording
stops when the buffer~ is filled.

Arguments
Name Units Type Opt Description
buffer-name symbol Obligatory. Names the buffer~ where record~ will write the recorded samples.
input-channels int opt Specifies the number of input channels (1, 2, or 4). This determines the number of
inlets record~ has. The two rightmost inlets always set the record start and end
points.

Messages
int recording-flag (0 or nonzero) In left inlet: Any non-zero number starts recording; 0 stops recording. Recording
[int] starts at the start point unless append mode is on.

In the inlet to the left of the right inlet: Set the start point within the buffer~ (in
milliseconds) for the recording. By default, the start point is 0 (the beginning of
the buffer~).

In right inlet: Sets the end point of the recording. By default, the end point is the
end of the buffer~ object's allocated memory.
float recording-flag (0 or nonzero) In left inlet: Any non-zero number starts recording; 0 stops recording. Recording
[float] starts at the start point unless append mode is on.

In the inlet to the left of the right inlet: Set the start point within the buffer~ (in
milliseconds) for the recording. By default, the start point is 0 (the beginning of
the buffer~).

In right inlet: Sets the end point of the recording. By default, the end point is the
end of the buffer~ object's allocated memory.
list loop-start/loop-end/timing- list can be used to specify loop-start and loop-end points or
parameters [list] timing/synchronization settings for transport.
anything loop-start/loop-end/timing- list can be used to specify loop-start and loop-end points or
parameters [list] timing/synchronization settings for transport.
append append-record-flag [int] The word append, followed by a non-zero number, enables append mode. In this
mode, when recording is turned on, it continues from where it was last stopped.
append 0 disables append mode. In this case, recording always starts at the start
point when it is turned on. Append mode is off initially by default.
(mouse) Double-clicking on record~ opens an editing window where you can view the
contents of its associated buffer~ object.
loop loop-record-flag [int] The word loop, followed by a non-zero number, enables loop recording mode. In
loop mode, when recording reaches the end point of the recording (see above) it
continues at the start point. loop 0 disables loop recording mode. In this case,
recording stops when it reaches the end point. Loop mode is off initially by
default. The record~ object also takes into account any changes in the buffer~
object's sampling rate if the buffer~ object's length is modified for the purpose of
establishing loop points.
set buffer-name [symbol] The word set, followed by the name of a buffer~, changes the buffer~ where
record~ will write the recorded samples.
reset The word reset resets the record-loop points to the default values (which record
through the whole duration of the assigned buffer~).
signal In left inlet: When recording is turned on, the signal is recorded into the sample
memory of a buffer~ at the current sampling rate.

In middle inlets: If record~ has more than one input channel, these inlets record
the additional channels into the buffer~.

Attributes
Name Type g/s Description
loopend atom Sets the loop end point for the object. The sampling interval can be specified in
any of the time formats used in Max.
loopstart atom Sets the loop start point for the object. The sampling interval can be specified in
any of the time formats used in Max.
transport symbol The name of a transport object with which to associate. By default the global
transport is used.

Information for box attributes common to all objects

Output
signal: Sync output. During recording, this outlet outputs a signal that goes from 0 when recording at the start point to 1 when
recording reaches the end point. When not recording, a zero signal is output.

Examples

Store a signal excerpt for future use

See Also
Name Description
2d.wave~ Two-dimensional wavetable
buffer~ Store audio samples
groove~ Variable-rate looping sample playback
play~ Position-based sample playback
transport Control a master clock
MSP Tutorial 13: Recording and MSP Tutorial 13: Recording and Playback
Playback
rect~
Antialiased rectangular (pulse) oscillator

Description
Use the rect~ object to generate an anti-aliased rectangle wave.

Arguments
Name Units Type Opt Description
frequency number opt First argument sets the initial frequency of the oscillator. The default is 0.
pulse-width number opt An optional second argument sets the pulse width. The default is 0.5.

Messages
int frequency [int] In left inlet: Sets the frequency of the oscillator.

In middle inlet: Sets the pulse width of the oscillator. Signal is wrapped into the
range 0-1. A value of 0.5 will produce a rectangular wave that spends equal
amounts of time on the positive and negative edges of its cycle.
float frequency [float] In left inlet: Sets the frequency of the oscillator.

In middle inlet: Sets the pulse width of the oscillator. Signal is wrapped into the
range 0-1. A value of 0.5 will produce a rectangular wave that spends equal
amounts of time on the positive and negative edges of its cycle.
signal In left inlet: Sets the frequency of the oscillator.

In middle inlet: Sets the pulse width of the oscillator. Signal is wrapped into the
range 0-1. A value of 0.5 will produce a rectangular wave that spends equal
amounts of time on the positive and negative edges of its cycle.

In right inlet: (optional) A sync signal. When the control signal crosses from below
0.5 to above 0.5, the oscillator resets itself. A phasor~ object works well for this
purpose. The classic use is to set this control signal to your fundamental frequency
and "sweep" the left frequency input in a range somewhere several octaves higher
than the fundamental.
synctrig sync-value (0 through 1) The word synctrig followed by a floating-point number changes the value at
[float] which the object resets itself (i.e., when the input signal crosses from below the
specified number to being above it, rect~ will reset itself).

Information for box attributes common to all objects

Output
signal: An antialiased rectangular waveform. An ideal, straight-line rectangular wave generated in a computer contains aliased
frequencies that can sound irritating. rect~ produces a nice, analog-esque output waveform.

Examples
Spectral comparison of rect~ and an ideal rectangular wave driven by a phasor~

See Also
Name Description
cycle~ Sinusoidal oscillator
phasor~ Generate sawtooth signals
saw~ Antialiased sawtooth oscillator
techno~ Signal-driven step sequencer
tri~ Antialiased triangular oscillator
MSP Tutorial 3: Wavetable MSP Tutorial 3: Wavetable Oscillator
Oscillator
reson~
Resonant bandpass filter

Description
Use the reson~ object when you need a resonant bandpass filter.

Arguments
Name Units Type Opt Description
initial-gain float opt Sets the initial gain. The default value is 0.
center-frequency hz float opt Sets the initial center frequency for the filter. The default value is 0.
Q float opt Sets the initial Q value for the filter. The default value is 0.01.

Messages
int initial-gain [int] An int can be sent in the three right inlets to change the filter-gain, center-
center-frequency [int] frequency, and Q. If a signal is connected to one of the inlets, a number received in
Q [int] that inlet is ignored.
float initial-gain [float] float can be sent in the three right inlets to change the filter-gain, center-
center-frequency [float] frequency, and Q. If a signal is connected to one of the inlets, a number received in
Q [float] that inlet is ignored.
list initial-gain [number] In left inlet: The first number sets the filter-gain. The second number sets the filter
center-frequency [number] center-frequency. The third number sets the filter-Q. If any of the inlets
Q [number] corresponding to these parameters have signals connected, the corresponding
value in the list is ignored.
clear Clears the filter's memory. Since reson~ is a recursive filter, this message may be
necessary to recover from blowups.
signal In left inlet: Any signal to be filtered.

In left-middle inlet: Sets the bandpass filter gain. This value should generally be
less than 1.

In right-middle inlet: Sets the bandpass filter center frequency in hertz.

In right inlet: Sets the bandpass filter "Q"-roughly, the sharpness of the filter -
where Q is defined by the center-frequency divided by the filter-bandwidth. Useful
Q values are typically between 0.01 and 500.

Information for box attributes common to all objects

Output
signal: The filtered input signal.

Examples
Control gain, center frequency, and Q of a bandpass filter to alter a rich signal

See Also
Name Description
biquad~ Two-pole, two-zero filter
comb~ Apply a comb filter effect
cross~ Third-order crossover filter
onepole~ Single-pole lowpass filter
lores~ Resonant lowpass filter
Resonant bandpass filter
svf~ State-variable filter with simultaneous outputs
Audio Filtering Audio Filtering
rewire~
Host ReWire devices

Description
The rewire~ object allows MSP to function as a ReWire mixer.

Arguments
Name Units Type Opt Description
device symbol opt Specify a ReWire device
outputs int opt Sets the number of audio outputs the rewire~ object will have. If no argument is
present, one audio outlet is created. The maximum number of outlets is 256.

Messages
bang In left inlet: If a ReWire device has been loaded, bang causes a list of its output
channel names to be sent out the second-from-right outlet.
int start/stop [int] In left inlet: 1 starts the ReWire transport, 0 stops it. No sound can occur without
the transport being started.
anything device [list] In left inlet: The symbol is interpreted as the name of a ReWire device. If the name
is valid, rewire~ attempts to switch to the device.
closepanel In left inlet: Closes the current device's user interface panel if it is open.
device device-index [int] In left inlet: The word device, followed by a number, switches to the ReWire
device associated with the number index. The index is obtained as the order in
which device names appear in a pop-up menu object connected to the second-to-
right outlet.
loadbang Same as bang but the action is performed upon loading the patch within which
the rewire~ object is performed.
loop start-point [int] In left inlet: The word loop, followed by three numbers, sets the current loop
end-point [int] position and mode. The first number sets the loop start position in samples. The
loop-flag (0 or 1) [int] second number sets the loop end position in samples. If the third number is 1,
looping is turned on. If the third number is 0, looping is turned off. However, note
that ReWire clients may ignore looping if they do not produce transport- or time-
based output. For example, a software synthesizer that only responds to MIDI note
commands would probably not be affected by looping.
map device-output-channel The word map, followed by two numbers, maps a ReWire device's output channel
[int] to an outlet of the rewire~ object. ReWire channels start at 1 with a maximum of
object-outlet [int] 256. rewire~ object outlets are specified starting at 1 for the left outlet, or 0 to turn
the ReWire channel off. For example, map 3 2 causes the ReWire device's audio
output channel 3 to be mapped to the second-from-left outlet of the rewire~
object. You can find out the names of the ReWire audio output channels with the
bang message after the rewire~ object has a connection to a ReWire device. By
default, audio outlets map to the first channels of the ReWire device; in other
words, the leftmost signal outlet outputs the first channel of the device.
midi time-stamp [int] In left inlet: The word midi, followed by four or five numbers, sends a MIDI event
MIDI-bus-index [int] to a ReWire device. The first number is a time stamp value and is currently
MIDI-message-status-byte ignored (in other words, the event is sent out immediately). The second number is
[int] the MIDI bus index. ReWire 2 has 256 MIDI busses, indexed from 0 to 255. The
MIDI-message [int] third number is the MIDI message status byte, and the fourth and fifth numbers
extended-MIDI-message are the MIDI message data bytes.
[int]
openpanel In left inlet: If the current device has a user interface panel, the word openpanel
will open it.
play In left inlet: Starts the ReWire transport.
position play-position [int] In left inlet: The word position, followed by a number, sets the current play
position (in samples).
stop In left inlet: Stops the ReWire transport.
tempo bpm [float] In left inlet: The word tempo, followed by a number, sets the tempo to that
number in beats per minute. ReWire handles integer or floating-point valude for
tempos, and tempo is updated on the next call to the client to return audio
samples.

Information for box attributes common to all objects

Output
MIDI: Out third-from-right outlet: MIDI events received from the ReWire device are sent out this outlet preceded by the word
midi. The first argument is always 0 (it is the time stamp), the second argument is the ReWire MIDI bus index, the third
argument is the MIDI status byte, and the fourth and (optional) fifth arguments are the MIDI data bytes.
signal: Out audio outlets (starting at left): The audio signal output from the ReWire device is sent out the rewire~ object's
outlets. By default, the leftmost outlet outputs the first channel of the device, but this mapping can be changed with the map
message.
symbol: Out fourth-from-right outlet: Messages indicating the transport state of the ReWire device. The position message with
an int argument reports the transport position in 15360 PPQ. The play and stop messages report when the transport is started
and stopped.
symbol: Out second-from-right outlet: A list of the currently available ReWire devices in response to the bang message.
symbol: Out right outlet: A list of the currently available device output names (in channel order) for the currently used ReWire
device.

Examples

rewire~ allows MIDI communication to and signal output from ReWire compatible devices

See Also
Name Description
vst~ Host VST and Audio Unit plug-ins
!-~
Signal subtraction (inlets reversed)

Description
The !-~ object functions just like the -~ object, but the inlet order is reversed.

Arguments
Name Units Type Opt Description
initial- number opt Sets an initial amount to subtract from the signal coming into the right inlet. If a
subtraction-value signal is connected to the left inlet, the argument is overidden. If no argument is
present, and no signal is connected to the left inlet, the initial value is 0 by default.

Messages
int input [int] In left inlet: An amount to subtract from the signal coming into the right inlet. If a
signal is also connected to the left inlet, a float or int is ignored.

In right inlet: Subtracts the signal coming into the left inlet from this value. If a
signal is also connected to the right inlet, a float or int is ignored.
float input [float] In left inlet: An amount to subtract from the signal coming into the right inlet. If a
signal is also connected to the left inlet, a float or int is ignored.

In right inlet: Subtracts the signal coming into the left inlet from this value. If a
signal is also connected to the right inlet, a float or int is ignored.
signal In left inlet: The signal is subtracted from the signal coming into the right inlet, or
a constant value received in the right inlet.

In right inlet: The signal coming into the left inlet or a constant value received in
the left inlet is subtracted from this signal.

Information for box attributes common to all objects

Output
signal: The difference between the two inputs.

Examples

-~ with the inlets reversed

See Also
Name Description
+~ Add signals
-~ Signal subtraction
round~
Round an input signal value

Description
Use the round~ object to round a signal input to an integer multiple.

Arguments
Name Units Type Opt Description
int or float number opt Sets the value to which the input signal will be rounded. The default value is 0. (no
modification).

Messages
int rounding-multiple-specifier In right inlet: an int will cause the input to be rounded to the nearest multiple of
[int] the specified number. If a signal is attached to the inlet, int messages are ignored.
float rounding-multiple-specifier In right inlet: a float will cause the input to be rounded to the nearest multiple of
[float] the specified number. If a signal is attached to the inlet, float messages are
ignored.
signal In left inlet: A signal whose values will be rounded.

In right inlet: A signal whose value is used for rounding. Signal values received in
the left inlet will be rounded to either the absolute nearest integer multiple or the
nearest integer multiple between the value received in this inlet or 0 (see the
nearest message for more information).

Attributes
Name Type g/s Description
nearest int When set to 1 (the default), the round~ object will round to the nearest multiple of
the specified signal value.

Note: This attribute does not set the rounding step (which is set using round~
object's right inlet), It specifies that rounding to the nearest signal value will occur.
Here are some examples:

With the rounding interval set to 3 and the nearest attribute set to 1:
an input signal value of 5.8 will return 6
an input signal value of 3.7 will return 3
an input signal value of -1 will return 0
an input signal value of -2.7 will return -3

With the rounding interval set to 3 and the nearest attribute set to 0:
an input signal value of 5.8 will return 3
an input signal value of 3.7 will return 3
an input signal value of -1 will return 0
an input signal value of -2.7 will return 0

Information for box attributes common to all objects

Output
signal: The rounded input signal.

Examples
round~ takes floating-point signals and rounds them to a specific increment

See Also
Name Description
rampsmooth~ Smooth an incoming signal
slide~ Filter a signal logarithmically
trunc~ Truncate fractional signal values
round Round to a value
sah~
Sample and hold a signal according to a trigger

Description
Use sah~ to capture ("sample") and continually output ("hold") the value of an input signal whenever another "control" signal
rises above a specified threshold value. The sampled value is "held" until the control signal drops below and then rises above the
threshold value once more, at which point the input is sampled again. Generally this allows one signal to be synchronized to the
behavior of another.

Arguments
Name Units Type Opt Description
initial-trigger- number opt Initial trigger value
value

Messages
float trigger-value [float] Set trigger threshold
signal In left inlet: A signal to be sampled. When the control signal (in the right inlet)
goes from being at or below the current trigger value to being above the trigger
value, the signal in the left inlet is sampled and its value is sent out as a constant
signal value.

In right inlet: The control signal. In order to cause a change in the output of sah~,
the control signal must go from being at or below the trigger value to above the
trigger value. When this transition occurs, the signal in the left inlet is sampled
and becomes the new output signal value.

Information for box attributes common to all objects

Output
signal: When the control signal received in the right inlet goes from being at or below the trigger value to being above the trigger
value, the output signal changes to the current value of the signal received in the left inlet. This signal value is sent out until the
next time the trigger value is exceeded by the control signal.

Examples

Hold the signal value constant until the next trigger

See Also
Name Description
gate~ Route a signal to one of several outlets
phasor~ Generate sawtooth signals
thresh~ Detect signal above a set level
train~ Pulse train generator
sampstoms~
Convert time from samples to milliseconds

Description
Use the sampstoms~ object to convert an incoming signal carrying a time value in samples and output a signal which converts
that number of samples to a number of milliseconds (at the current sampling rate).

Arguments
None.

Messages
int sample-value [int] A value representing a number of samples received in the inlet is converted to
milliseconds at the current sampling rate and sent out the object's right outlet. The
input may contain a fractional number of samples. For example, at 44.1 kHz
sampling rate, 322.45 samples is 7.31 milliseconds. (A float or int input triggers
output even when audio is off.)
float sample-value [float] A value representing a number of samples received in the inlet is converted to
milliseconds at the current sampling rate and sent out the object's right outlet. The
input may contain a fractional number of samples. For example, at 44.1 kHz
sampling rate, 322.45 samples is 7.31 milliseconds. (A float or int input triggers
output even when audio is off.)
signal Values in the signal represent a number of samples, and are converted to
milliseconds at the current sampling rate to output as a signal out the left outlet.
The input may contain a fractional number of samples.

Information for box attributes common to all objects

Output
float: Out right outlet: A number of milliseconds corresponding to a number of samples received in the inlet.
signal: Out left outlet: A signal consisting of the number of milliseconds corresponding to values representing a number of
samples in the input signal.

Examples

Some objects refer to time in samples, some in milliseconds

See Also
Name Description
dspstate~ Report current DSP settings
mstosamps~ Convert milliseconds to samples
translate Convert between different units of time.
saw~
Antialiased sawtooth oscillator

Description
Use the saw~ object to generate an anti-aliased sawtooth wave.

Arguments
Name Units Type Opt Description
initial-frequency hz number opt Sets the initial frequency of the oscillator. The default is 0.

Messages
int frequency [int] In left inlet: Sets the frequency of the oscillator.
float frequency [float] In left inlet: Sets the frequency of the oscillator.
signal In left inlet: Sets the frequency of the oscillator.

In right inlet: (optional) A sync signal. When the control signal crosses from below
0.5 to above 0.5, the oscillator resets itself. A phasor~ object works well for this
purpose. The classic use is to set this control signal to your fundamental frequency
and "sweep" the left frequency input in a range somewhere several octaves higher
than the fundamental.
synctrig trigger-value [float] Sets the value which an input signal crosses at which the oscillator will reset itself.

Information for box attributes common to all objects

Output
signal: An antialiased sawtooth waveform. An ideal, straight-line sawtooth wave generated in a computer contains aliased
frequencies that can sound irritating. saw~ produces a nice, analog-esque output waveform.

Examples

Spectral comparison of saw~ and phasor~

See Also
Name Description
cycle~ Sinusoidal oscillator
phasor~ Generate sawtooth signals
rect~ Antialiased rectangular (pulse) oscillator
Antialiased sawtooth oscillator
techno~ Signal-driven step sequencer
tri~ Antialiased triangular oscillator
MSP Tutorial 3: Wavetable MSP Tutorial 3: Wavetable Oscillator
Oscillator
scale~
Map an input range of signal values to an output range

Description
Use the scale~ object to map an input range of signal values to an output range. The ranges can be specified with hi and lo
reversed for inverted mapping. If specified, the mapping can also be exponential.

Arguments
Name Units Type Opt Description
minimum-in- number The first argument is the minimum input value used in the scaling operation.
value
maximum-in- number The second argument is the maximum input value used in the scaling operation.
value
minimum-out- number The third argument is the minimum output value used in the scaling operation.
value
maximum-out- number The fourth argument is the maximum output value used in the scaling operation.
value
scaling-curve float opt This optional fifth argument specifies the nature of the scaling curve. This
argument must be a floating-point number greater than 1, with larger values
leading to steeper exponential curves.

In classic mode a typical value for this argument is 1.06 and the number is
converted according to the following expression:
y = b e-a log c ex log c
where x is the input, y is the output, a, b, and c are the three typed-in arguments,
and e is the base of the natural logarithm (approximately 2.718282).

In non- classic (modern) mode the value for the scaling curve is converted
according to the following expression:

y = x^k

where x is the input, y is the output, and k is the curve value. If k = 1 then the
scaling is linear. Higher values of k will result in an exponential mapping, while
lower values of k will result in a logarithmic mapping. The value of k must be
greater than zero.

Note that prior to Max 6.0.4 the exponent was inverted. Thus, if you gave it an
exponent of 2 the object behaved like it had an exponent of 0.5, and if you gave it
an exponent of 0.5 it behaved like it had an exponent of 2. Patches from versions
prior to 6.0.4 may require updating to work properly.

Messages
float input [float] In second inlet: Sets the low input value.

In third inlet: Sets the high input value.

In fourth inlet: Sets the low output value.


In fifth inlet: Sets the high output value.
In sixth inlet: Sets the scaling curve value as described in the object arguments
section.
signal In left inlet: The incoming signal values are scaled according to the mapping
provided by the arguments or values received in the other inlets.

Attributes
Name Type g/s Description
classic int Classic mode uses exponential function that is backward compatible with old
IRCAM patchers.

Information for box attributes common to all objects

Examples

See Also
Name Description
scale Map values to an output range
scope~
Visualize an audio signal

Description
Use the scope~ object to visualize and audio signal using an oscilloscope-style display.

Arguments
None.

Messages
int object-settings [int] Left inlet: Number of samples collected for each value in the display buffer.
Smaller numbers expand the image but make it scroll by on the screen faster. The
minimum value is 2, the maximum is 8092, and the default initial value is 256. In
X or Y mode, the most maximum or minimum value seen within this period is
used. In X-Y mode, a representative sample from this period is used.

Right inlet: Size of the display buffer. This controls the rate at which scope~
redisplays new information as well as the scaling of that information. If the buffer
size is larger, the signal image will stay on the screen longer and be visually
compressed. If the buffer size is smaller, the signal image will stay on the screen a
shorter time before it is refreshed and will be visually expanded.

It might appear that the samples per display buffer element and the display buffer
size controls do the same thing but they have subtly different effects. You may
need to experiment with both controls to find the optimum display parameters for
your application.
(mouse) Click to freeze the display for as long as you hold the click
signal Left inlet: signal to display on the X axis of the oscilloscope
Right inlet: signal to display on the Y axis of the oscilloscope

If signal objects are connected to both the left and right inlets, scope~ operates in
X-Y mode, plotting points whose horizontal position corresponds to the value of
the signal coming into the left (X) inlet and whose vertical position corresponds to
the value of the signal coming into the right (Y) inlet. If the two signals are
identical and in phase, a straight line increasing from left to right will be seen. If
the two signals are identical and 180 degrees out of phase, a straight line
decreasing from left to right will be seen. Other combinations may produce circles,
ellipses, and Lissajous figures.

Attributes
Name Type g/s Description
bgcolor float Background Color
bordercolor float Border Color
bufsize int Buffer Size
def.:128
calccount int Calccount - samples per pixel
def.:256
delay float Onset Delay
def.:0.
drawstyle int Drawing Style
def.:0
fgcolor float Phosphor Color
gridcolor float Grid Color
range float Lo and Hi Display Range (Y-Axis)
def.:-1. 1.
rounded int Round-ness of Box Corners
def.:8
trigger int Trigger mode determines when a new waveform trace begins (following the delay
def.:0 ).
trigger 1 sets an upward trigger in which the signal must go from being below the
triglevel to being equal to it or above it.
trigger 2 sets a downward trigger in which the signal must go from being above
the triglevel level to being equal to it or below it.
The default trigger mode is 0, which does not wait after a non-zero delay period
before collecting samples again.
'None' = TEXT_HERE
'Up' = TEXT_HERE
'Down' = TEXT_HERE
triglevel float Threshold to trip trigger mode. When trigger mode is 1 or 2, the waveform must
def.:0. increase or decrease past this value to trigger a new trace. If you are displaying a
periodic waveform, slight changes to the trigger level will shift the waveform to the
left or right.

Information for box attributes common to all objects

Output
visual: The waveform of the incoming signal is displayed within the oscilloscope display.

Examples

Display a signal, or plot two signals in X-Y mode

See Also
Name Description
meter~ Visual peak level indicator
MSP Tutorial 24: Oscilloscope MSP Tutorial 24: Oscilloscope
selector~
Assign one of several inputs to an outlet

Description
Use the selector~ object to choose between one of several input signals (or none). The selector~ is similar to the Max switch
object but for signals, however if no input is chosen, it outputs a signal composed of zero values.

Arguments
Name Units Type Opt Description
number-of-inputs int opt Number of inputs
initially-open-inlet int opt Specify which input is initially selected. If 0, where all signals are shut off and a
zero signal is sent out.

Messages
int open-inlet [int] Select which input to route to the outlet. If the value is 0 or negative, a zero signal
is sent out. If the value is greater than the number of inputs, the right-most input
is used. If a signal is connected to the left inlet, this message is ignored.
signal In left inlet: If a signal is connected to the left inlet, selector~ operates in a mode
that uses signal values to determine which of its input signals is to be passed to its
outlet. If the signal coming in the left inlet is 0 or negative, the output is shut off
and a zero signal is sent out. If it is 1 but less than 2, the signal coming in the first
inlet to the right of the leftmost inlet is passed to the outlet. If the signal is 2 but
less than 3, the signal coming into the next inlet to the right is used, and so on.

In other inlets: Any signal, to be passed through to the selector~ object's outlet
depending on the value of the most recently received int or float in the left inlet, or
the signal coming into the left inlet. The first signal inlet to the right of the leftmost
inlet is considered input 1, the next to the right input 2, and so on.
If the signal network connected to one or more of the selector~ signal inlets
contains a begin~ object, and a signal is not connected to the left inlet of the
selector~, all processing between the begin~ outlet and the selector~ inlet is
turned off when the input signal is not being passed to the selector~ outlet.

Information for box attributes common to all objects

Output
signal: The output is the signal coming in the "open" inlet, as specified by a number or signal in the left inlet. The output is a zero
signal if all signal inlets are shut off.

Examples

Allow only one of several signals to pass optionally turn off unneeded signal objects

See Also
Name Description
gate~ Route a signal to one of several outlets
switch Accept messages from a specific inlet
MSP Tutorial 5: Turning Signals MSP Tutorial 5: Turning Signals On and Off
On and Off
send~
Send signals without patch cords

Description
The send~ object lets you send a signal to another patcher window or to another location within the same patcher window
without using a patch cord.

Arguments
Name Units Type Opt Description
object-name symbol Sets the name of the send~ object.

Messages
clear The clear message clears all of the receive~ buffers associated with the send~
object. This message is only used with patchers which are being muted inside a
subpatch loaded by the poly~ object.
set object-name [symbol] The word set, followed by a symbol, changes the name of the send~ so that it
connects to different receive~ objects that have the symbol as a name. (If no
receive~ objects with the same name exist, send~ does nothing.)
signal The send~ object sends its input signal to all receive~ objects that share its name.
The send~ object need not be in the same patch as the corresponding receive~
object(s).

Information for box attributes common to all objects

Output
Signal-Routing: Signals are routed remotely (i.e., sans patch-cord-connection).

Examples

Signal coming into send~ comes out any receive~ object with the same name

See Also
Name Description
receive~ Signals can be received from any loaded patcher, without patch cords
MSP Tutorial 4: Routing Signals MSP Tutorial 4: Routing Signals
seq~
Signal-driven event sequencer

Description
The seq~ object is an event sequencer that is driven by a signal input. seq~ can be used to create looping sequences of control
data that are synchronized to a phasor~.

Arguments
None.

Messages
bang Causes information about the seq~ object's current sequence number, mode of
operation (record, overdub, play) and total number of current events to be printed
in the Max window.
int input [int] Same as anything.
float input [float] Same as anything.
list input [list] Same as anything.
anything input [list] The seq~ object is used to record and play back messages. All events received in
the inlet are stored according to the current value of the input signal. Any message
can be sequenced except for commands to the seq~ object itself. The example
shows a simple way to work around this limitation.
Note: seq~ can be used to sequence MIDI data if the MIDI input stream is
converted into lists of MIDI events. This conversion is necessary to avoid
outputting a corrupted MIDI stream which would occur if only the raw int
messages of a MIDI stream were sequenced individually and the seq~ object were
not doing a simple forward linear playback.
add sequence-name (symbol), The word add, followed by an int, a float and a message, inserts a Max event
start time (float), optional specified by the message at the time specified by the float for the sequence number
end time (float) and Max- specified by the int. (e.g., add 2 0.5 honk will insert the message honk to be
Event (message) [list] played at the halfway point of sequence 2.)
clear The word clear, followed by the name of a sequence, erases the sequence. The
message clear all erases all current sequences.
erase Synonym for clear.
delete sequence-number (int), time The word delete, followed by an symbol that specifies a sequence name, a float
(float), and Max-Event and a message, deletes a Max event or events specified by the message at the time
(message) [list] specified by the float for the sequence name specified by the symbol. An additional
end time may also be specified. Here are some examples:

delete mysequence 5.: delete all the events at time 5 in mysequence.


delete mysequence 6.5 8.: delete all the events between time 6.5 and 8 in
mysequence.
delete mysequence -1. 99. explosion: delete only the event explosion
wherever it occurs.
dump sequence-number (int) [int] Causes the contents of the current stored event sequence to be sent out the middle
outlet. The word dump, followed by a number, outputs only the sequence
designated by the number.
play playback-enable-flag (0 or The word play, followed by 1, causes seq~ to begin Max event playback of the
1) [int] current sequence (set by the seqnum message) at the point of the loop specified
by the current value of the signal input. play 0 turns off playback. By default,
playback is off.
offset number-to-offset- The word offset followed by a number will offset the numbering of sequences by
sequence-numbering [int] the specified number.
overdub overdub-enable-flag (0 or 1) The word overdub, followed by 1, causes seq~ to begin Max event recording of
[int] the current sequence (set by the seqnum message) in "overdub" mode. Recording
begins at the current point of the loop and wraps around at the point where the
input signal reaches 1, continuing to record as the signal passes its original value.
The message overdub 0 turns off overdub mode.
seq sequence (int or symbol) [int] Performs the same function as seqnum.

seqnum sequence (int or symbol) [int] The word seqnum, followed by a number or symbol, sets the current Max event
sequence being recorded or played back.
read filename [symbol] Reads a text file containing Max event sequences created using the seq~ object's
write message into the memory of the. seq~ object. If no symbol argument
appears after the word read, a standard open file dialog is opened showing
available text files. The word read, followed by a symbol, reads the file whose
filename corresponds to the symbol into the seq~ object's memory without
opening the dialog box.
record playback-enable-flag (0 or The word record, followed by 1, causes seq~ to begin recording events into the
1) [int] current sequence (set by the seqnum message) at the point of the loop specified
by the current value of the signal input. record 0 turns off recording. Recording is
off by default.
signal An input signal whose output is between 0. and 1.0 (usually the output of a
phasor~) is used to drive the event sequencer.
symbol input [symbol] Same as anything.
write filename [symbol] Saves the contents of all current Max event sequences into a text file. A standard
file dialog is opened for naming the file. The word write, followed by a symbol,
saves the file, using the symbol as the filename, in the same folder as the patch
containing the seq~ object. If the patch has not yet been saved, the seq~ file is
saved in the same folder as the Max application.

Information for box attributes common to all objects

Output
any message: Out left outlet: When playback is enabled with the play 1 message, the seq~ object outputs all events recorded at
the time specified by the input signal.
list: Out right outlet: The dump message will cause the seq~ object to output the contents of a specified sequence to be output in
the form of a list consisting of an int which specifies the sequence number, a float which specifies the signal value associated with
that point in time, and the int, float, symbol or list to be output at that time.

Examples

See Also
Name Description
phasor~ Generate sawtooth signals
techno~ Signal-driven step sequencer
sfinfo~
Report audio file information

Description
sfinfo~ gives you the number of channels, sample size, sampling rate, sampletype, filename, and duration of a soundfile.

Arguments
Name Units Type Opt Description
filename symbol opt Names a file that sfinfo~ will report about when it receives a subsequent bang
message. The file must exist in the Max search path.

Messages
bang If a file has already been opened, either with the open message or specified by an
argument to sfinfo~, bang reports the number of channels, sample size, sample
rate, and length in milliseconds out the sfinfo~ object's outlets.
getnamed object-name [symbol] In left inlet: The word getnamed, followed by a symbol which specifies the name
of an sfplay~ object, interrogates the named sfplay~ object and reports the
number of channels, sample size, sample rate, file length in milliseconds, sample
type, and filename out its outlets.
open filename [symbol] The word open, followed by a name of an audio file, opens the file if it exists in
Max's search path. Without a filename, open brings up a standard open file dialog
allowing you to choose a file. After the file is opened, sfinfo~ interrogates the file
and reports the number of channels, sample size, sample rate, file length in
milliseconds, sample type, and filename out its outlets.

Information for box attributes common to all objects

Output
alaw: 8-bit a-law encoding

Out 6th outlet: The filename of the audio file


float: Out 3rd outlet: The audio file's sampling rate.

Out 4th outlet: The duration of the audio file in milliseconds.


float32: 32-bit floating-point
float64: 64-bit floating-point
int: Out left outlet: The number of channels in the audio file.

Out 2nd outlet: The audio file's sample size in bits (typically 16).
int16: 16-bit integer
int24: 24-bit integer
int32: 32-bit integer
int8: 8-bit integer
mulaw: 8-bit "mu"-law encoding
symbol: Out 5th outlet: the sample type of the audio file.

The following types of sample data are supported:


uint8: unsigned 8-bit integer

Examples
Report information about a specific audio file

See Also
Name Description
info~ Report information about a sample
sflist~ Store audio file cues
sfplay~ Play audio file from disk
MSP Tutorial 16: Record and Play MSP Tutorial 16: Record and Play Audio Files
Audio Files
sflist~
Store audio file cues

Description
sflist~ stores a list of preloaded cues for sound files that can be accessed by multiple sfplay~ objects. Each sflist~ object has a
unique name that sfplay~ objects use to refer to its cues. Defining a cue is the same for sflist~ as for sfplay~. You can preload
cues for sflist~ without the audio being on.

Arguments
Name Units Type Opt Description
object-name symbol Names the sflist~. sfplay~ objects use this name to refer to cues stored inside the
object.
buffer-size int opt Sets the buffer size used to preload audio files. The default and minimum is 16384.
Preloaded buffers are 4 times the buffer size per channel of the audio file.

Messages
clear cue-numbers [list] The word clear with no arguments clears all defined cues. After a clear message is
received, only the number 1 will play anything (assuming there's an open file). The
word clear followed by one or more cue numbers removes them from the sflist~
object's cue list.
cuedump The word cuedump will cause sflist~ to send out the outlet a listing containing all
of its cues.
embed saving-preference-flag [int] The message embed, followed by any non-zero integer, causes sflist~ to save all of
its defined cues and the name of the current open file when the patcher file is
saved. The message embed0 keeps sflist~ from saving this information when the
patcher is saved. By default, the current file name and the cue information is not
saved in sflist~ when the patcher is saved. If an sflist~ object is saved with stored
cues, they will all be preloaded when the patcher containing the object is loaded.
fclose filename [symbol] The word fclose, followed by the name of an open file, closes the file and removes
all cues associated with it. The word fclose by itself closes the current file.
open filename [symbol] The word open, followed by the name of an AIFF, WAV, or NeXT/Sun audio file,
opens the file if it is located in Max's search path. Without a filename, open
brings up a standard open file dialog allowing you to choose a file. When a file is
opened, its beginning is read into memory, and until another file is opened,
playing from the beginning the file is defined as cue 1. Subsequent cues can be
defined referring to this file using the preload message without a filename
argument. When the open message is received, the previous current file, if any,
remains open and can be referred to by name when defining a cue with the
preload message. If any cues were defined that used the previous current file, they
are still valid even if the file is no longer current.
preload cue-number [int] Defines a cue, an integer greater than or equal to 2, to refer to a specific region of a
filename [symbol] file. When that cue number is subsequently received by an sfplay~ object that is
start-time [int] set to use cues from the sflist~ object, the specified region of the file is played by
end-time [int] sfplay~. Cue number 1 is always the beginning of the current file - the file last
directional-flag [int] opened with the open message - and cannot be modified with the preload
playback-speed [float] message.

There are a number of forms for the preload message. The word preload is
followed by an obligatory cue number between 2 and 32767. If the cue number is
followed by a filename - a file that is currently open or one that is in Max's search
path - that cue number will henceforth play the specified file. Note that a file need
not have been explicitly opened with the open message in order to be used in a
cue. If no filename is specified, the currently open file is used.
After the optional filename, an optional start time in milliseconds can be specified.
If no start time is specified, the beginning of the file is used as the cue start point.
After the start time, an end time in milliseconds can be specified. If no end time is
specified, or the end time is 0, the cue will play to the end of the file. If the end
time is less than the start time, the cue is defined but will not play. Eventually it
may be possible to define cues that play in reverse.

After the start and/or end time arguments, a optional directional buffer flag is
used to enable reverse playback of stored cues. Setting this flag to 1 enables reverse
cue playback. The default setting is 0 (bidirectional buffering off).

A final optional argument is used to set the playback speed. A float value sets the
playback speed for an sfplay~ object relative to the object's global playback speed
-- set by the speed message. The default value is 1.

Each cue that is defined requires approximately 40K of memory per sfplay~
channel at the default buffer size (40320), with bidirectional buffering turned off.
With bidirectional buffering turned on, the amount of memory per cue is doubled.
print Prints a list of all the currently defined cues.

Information for box attributes common to all objects

Output
Cues: Cues are stored within the object for reference by other soundfile objects. A listing of internally stored cues is sent out its
outlet with the cuedump message.

Examples

Store a global list of cues that can be used by one or more sfplay~ objects

See Also
Name Description
buffer~ Store audio samples
groove~ Variable-rate looping sample playback
play~ Position-based sample playback
sfinfo~ Report audio file information
sfplay~ Play audio file from disk
sfrecord~ Record to audio file on disk
MSP Tutorial 16: Record and Play MSP Tutorial 16: Record and Play Audio Files
Audio Files
sfplay~
Play audio file from disk

Description
Use the sfplay~ object to play plays AIFF, NeXT/SUN(.au), WAVE, and Raw Data files of 1-32 tracks from disk.

Arguments
Name Units Type Opt Description
sflist-object-name symbol opt If the first argument is a symbol, it names an sflist~ that the sfplay~ object will
use for playing cues. If no symbol argument is given, sfplay~ plays its own
internally defined cues.
number-of- int opt Sets the number of output channels, which determines the number of signal
output-channels outlets that the sfplay~ object will have. The maximum number of channels is 28.
The default is 1. If the audio file being played has more output channels than the
sfplay~ object, higher-numbered channels will not be played. If the audio file has
fewer channels, the signals coming from the extra outlets of sfplay~ will be 0.
buffer-size int opt An additional optional argument can be used to specify the disk buffer size in
samples. The default disk buffer size is 120960, and disk buffer sizes must be
specified as multiples of 20160. If this argument has a value of 0, the default disk
buffer size will be used.
position-outlet- int opt An additional optional argument can be used to create outlets to the sfplay~ object
flag which display positioning information. Specifying a final argument of 1 creates a
single outlet to the left of the rightmost "bang on finish or halt" outlet which
outputs a signal value which corresponds to the current playback position in
milliseconds.

Like all MSP audio signals, this playback position is a 32-bit single precision
floating-point signal. If greater precision is desired, specifying a final argument of
2 creates a second outlet which outputs a second 32-bit single precision floating-
point signal containing the single precision roundoff error. Together these signals
provide near double precision floating-point accuracy. (Note: after several minutes
a single precision floating-point value is no longer sample accurate) Using the two
signals together with objects such as the unsupported Max/ MSP high resolution
signal processing objects like hr.+~ , one may perform sample-accurate
calculations based on file position
object-reference- symbol opt If the last argument is a symbol, it specifies a name by which other objects can
name refer to the sfplay~ object to access its contents.

Messages
int start/stop-playback-of- In left inlet: If a file has been opened with the open message, 1 begins playback
cue-number [int] (of the most recently opened file), and 0 stops playback. Numbers greater than 1
trigger cues that have been defined with the preload message, or that were
defined based on the saved state of the sfplay~ object. When the file is played, the
audio data in the file is sent out the signal outlets according to the number of
channels the object has. When the cue is completed or sfplay~ is stopped with a
0, a bang is sent out the right outlet. If the object is currently assigned to an
sflist~ object (using the set message or with a typed-in argument), an int will
trigger cues stored in the sflist~ object rather than inside the sfplay~. To reset
sfplay~ to use its own cues, send it the set message with no arguments.
float playback-rate [float] In right inlet: Defines the playback rate of an audio file. A value of 1.0 plays the
audio file at normal speed. A playback rate of -1 plays the audio file backwards at
normal speed. A playback rate of 2 plays the audio file at twice the normal speed.
A playback rate of .5 plays the audio file at half the normal speed.
list cues [list] In left inlet: Gives a set of cues for sfplay~ to play, one after the other. The
maximum number of cues is in a list is 128. Cue numbers (set using the preload
message) can be any integer greater than or equal to 2.If a cue number in a list has
not been defined, it is skipped and the next cue, if any, is tried. If the object is
currently assigned to an sflist~ object, a list uses cues stored in the sflist~ object.
Otherwise, cues stored inside the sfplay~ object are used.
anything sflist-object-name [symbol] In left inlet: If the name of an sflist~ object is sent to sfplay~, followed by a
number, the numbered cue from the sflist~ is played if it exists.
cue-number [int]
(drag) When an audio file is dragged from the Max 5 File Browser to an sfplay~ object,
the file will be loaded.
clear cue-numbers [list] In left inlet: The word clear with no arguments clears all defined cues. After a
clear message is received, only the number 1 will play anything (assuming there's
an open file). The word clear followed by one or more cue numbers removes them
from the sfplay~ object's cue list. clear requires the DSP chain to be off.
fclose filename [symbol] In left inlet: The word fclose, followed by the name of an open file, closes the file
and removes all cues associated with it. The word fclose by itself closes the
current file.
embed saving-preference-flag (0 In left inlet: The message embed, followed by any non-zero integer, causes
or nonzero) [int] sfplay~ to save all of its defined cues and the name of the current open file when
the patcher file is saved. The message embed0 keeps sfplay~ from saving this
information when the patcher is saved. By default, the current file name and the
cue information is not saved in sfplay~ when the patcher is saved. If an sfplay~
object is saved with stored cues, they will all be preloaded when the patcher
containing the object is loaded.
loop looping-flag (0 or 1) [int] In left inlet: The word loop, followed by 1, turns on looping. loop 0 turns off
looping. By default, looping is off.
loopone cue-number [int] In left inlet: The word loopone, followed by a cue-number, will set only the cue
specified to loop.
offset sample-start-offset (bytes) In left inlet: The word offset, followed by a number, specifies the sample start
[int] offset in bytes. The default value is 0. This value useful for aligning samples and
avoiding playback of header information.
open filename [symbol] In left inlet: followed by the name of an AIFF, WAV, NeXT/Sun, or raw format
audio file or CD-audio track, opens the file for playback and makes it the current
file. The word open, followed by a filename, opens the file if it exists in Max's
search path. Without a filename, open brings up a standard open file dialog
allowing you to choose a file. When a file is opened, its beginning is read into
memory, and until another file is opened, you can play the file from the beginning
by sending sfplay~ the message 1. When the open message is received, the
previous current file, if any, remains open and can be referred to by name when
defining a cue with the preload message. If any cues were defined that used the
previous current file, they are still valid even if the file is no longer current.
openraw filename [symbol] In left inlet: The openraw message functions exactly like open, but allows you to
open any type of file for playback and make it the current file. The openraw
message assumes that the file being opened is a 16-bit stereo file sampled at a rate
of 44100 Hz, and assumes that there is no header information to ignore (i.e., an
offset of 0). The file types can be explicitly specified using the samptype, offset,
srate, and srchans messages.
name object-reference-name The word name, followed by a symbol, changes the name by which other objects
[symbol] such as sfinfo~ can refer to the sfplay~ object. Objects that were referring to the
sfplay~ under its old name lose their connection to it. Every sfplay~ object should
be given a unique name; if you give an sfplay~ object a name that already belongs
to another sfplay~ object, that name will no longer be associated with the sfplay~
object that first had it.
modout modulo-output-flag [int] In left inlet: The word modout, followed by 1, turns on modulo output. If the
number of channels in a audio file is less than the number of outputs for the
sfplay~ object, the sfplay~ object will reduplicate the audio file's channels across
all of sfplay~ object's outputs (rather than outputting zero) if modulo output is
enabled. For example, a mono audio file loaded into an sfplay~ object with two
outputs will be played with the mono channel sent out both outputs of the object if
modulo output is enabled. Similarly a stereo audio file will be played on an
sfplay~ object with four outlets with the left channel played on outputs 1 and 3,
while the right will be played on outputs 2 and 4. The message modout 0 disables
this feature.
pause In left inlet: The pause message causes the audio file playback to pause at its
current playback position. Playback can be restarted with the resume message.
preload cue-number [int] In left inlet: Defines a cue - an integer greater than or equal to 2 - to refer to a
filename [symbol] specific region of a file. When that cue number is subsequently received, sfplay~
start-time [int] plays that region of that file. Cue number 1 is always the beginning of the current
end-time [int] file - the file last opened with the open message - and cannot be modified with the
directional-flag [int] preload message.
playback-speed [float]
There are a number of forms for the preload message. The word preload is
followed by an obligatory cue number between 2 and 32767. If the cue number is
followed by a filename - a file that is currently open or one that is in Max's search
path - that cue number will henceforth play the specified file. Note that a file need
not have been explicitly opened with the open message in order to be used in a
cue. If no filename is specified, the currently open file is used.

After the optional filename, an optional start time in milliseconds can be specified.
If no start time is specified, the beginning of the file is used as the cue start point.
After the start time, an end time in milliseconds can be specified. If no end time is
specified, or the end time is 0, the cue will play to the end of the file. If the end
time is less than the start time, the cue is defined but will not play. Eventually it
may be possible to define cues that play in reverse.

After the start and/or end time arguments, a optional directional buffer flag is
used to enable reverse playback of stored cues. Setting this flag to 1 enables reverse
cue playback. The default setting is 0 (bidirectional buffering off).

A final optional argument is used to set the playback speed. A float value sets the
sfplay~ object's playback speed relative to the object's global playback speed -- set
set by either the speed message or the sfplay~ object's right inlet. The default
value is 1.

Each cue that is defined requires approximately 40K of memory per sfplay~
channel at the default buffer size (40320), with bidirectional buffering turned off.
With bidirectional buffering turned on, the amount of memory per cue is doubled.

The preload message is always deferred to low priority. The pause, resume, and
int messages are not. If you have problems with these messages arriving before
you want them to in overdrive mode (i.e., before you've preloaded the most recent
cue), use the defer object.
print In left inlet: Prints information about the state of the object, plus a list of all the
currently defined cues.
resume In left inlet: If playback was paused, playback resumes from the paused point in
the file.
samptype sample-type [symbol] In left inlet: The word samptype, followed by a symbol, specifies the sample type
bit-depth [int] to use when interpreting the audio file's sample data (thus overriding the audio
file's actual sample type). This is sometimes called "header munging." When
reading files in response to the openraw message, the assumed sample type is 16-
bit integer. Modifications using samptype make no changes to the file on disk.

The following types of sample data are supported:


The following types of sample data are supported:

int8: 8-bit integer


int16: 16-bit integer
int24: 24-bit integer
int32: 32-bit integer
float32: 32-bit floating-point
float64: 64-bit floating-point
mulaw: 8-bit "mu"-law encoding
alaw: 8-bit a-law encoding
seek start-time [float] In left inlet: The word seek, followed by a start time in milliseconds, moves to the
end-time [float] specified position in the current file and begins playing. After the start time, an
optional end time can be specified, which will set a point for playback to stop. The
seek message is intended to allow you to preview and adjust the start and end
points of a cue.

NOTE: The seek message is always deferred to low priority. If you have problems
with these messages arriving before you want them to in overdrive mode (i.e.
before you've finished seeking to a new location), then use the defer object.
set sflist-object-name [symbol] In left inlet: The message set, followed by a name of an sflist~ object, will cause
sfplay~ to play cues stored in the sflist~ when it receives an int or list. The
message set with no arguments resets sfplay~ to use its own internally defined
cues when receiving an int or list.
signal In left inlet: An input signal may be used for the sample-accurate triggering of
prestored cues. When a signal value is received in the left inlet, the integer portion
of the signal value is monitored. When the integer portion of the input signal
changes to a value equal to the index of a prestored cue, that cue is triggered.
Negative values are ignored.
speed playback-rate [float] In left inlet: The word speed, followed by a number, sets an overall multiplier on
the playback rate of all cues played by the object. A value of 1.0 (the default) plays
all cues at normal speed. A playback rate of -1 plays all cues backward at normal
speed. A playback rate of 2 plays the cues at twice their defined speed. A playback
rate of 0.5 plays cues at half their defined speed. For example, if a cue has a
playback rate of 2, and the speed is set to 3, the cue will play back at 6 times the
normal speed.
srate sample-rate [float] In left inlet: The word srate, followed by a number, specifies the sampling rate
(Hertz) at which to interpret the audio file's sample data (thus overriding the
audio file's actual sampling rate). This is sometimes called "header munging."
When reading files in response to the openraw message, the assumed sampling
rate is 44,100 Hz. Modifications using srate make no changes to the file on disk.
srcchans number-of-channels [int] In left inlet: The word srcchans, followed by a number, specifies the number of
channels in which to interpret the audio file's sample data (thus overriding the
audio file's actual number of channels). This is sometimes called "header
munging." When reading files in response to the openraw message, the assumed
number of channels is 2. Modifications using srcchans make no changes to the
file on disk.

Attributes
Name Type g/s Description
audiofile symbol Specifies the name/pathname of an audio file to be loaded by the sfplay~ object.

Information for box attributes common to all objects

Output
bang: Out right outlet: When the file is done playing, or when playback is stopped with a 0 message, a bang is sent out.
signal: There is one signal outlet for each of the sfplay~ object's specified output channels (set by or as an argument to the
sfplay~ object) that sends out the audio data of the corresponding channel of the audio file when a cue number is received in the
inlet. (The left outlet plays channel 1, and so on.)

If the optional output position argument is specified, there will be one or two signal outputs following the channel outputs whose
signal outputs display positioning information. If the argument is 1, a single outlet to the left of the rightmost "bang on finish or
halt" outputs a signal containing the current playback position in milliseconds. Specifying a final argument of 2 creates a second
outlet which outputs a signal containing the playback position single precision roundoff error in milliseconds (see Arguments for
a more detailed description of the sfplay~ object's position outlets).

Examples

Audio files can be played from the hard disk, without loading the whole file into memory

See Also
Name Description
buffer~ Store audio samples
groove~ Variable-rate looping sample playback
play~ Position-based sample playback
sfinfo~ Report audio file information
sflist~ Store audio file cues
sfrecord~ Record to audio file on disk
MSP Tutorial 16: Record and Play MSP Tutorial 16: Record and Play Audio Files
Audio Files
sfrecord~
Record to audio file on disk

Description
Use the sfrecord~ object to record and save MSP output as an audio file.

Arguments
Name Units Type Opt Description
number-of-input- int opt Sets the number of input channels, which determines the number of inlets that the
channels sfrecord~ object will have. The maximum number of channels is 28, and the
default is 1. The audio file created will have the same number of channels as this
argument. Whether you can actually record the maximum number of channels is
dependent on the speed of your processor and hard disk.

Messages
int recording-start/stop-flag (0 In left inlet: If a file has been opened with the open message, a non-zero value
or nonzero) [int] begins recording, and 0 stops recording and closes the file. sfrecord~ requires
another open message to record again if a 0 has been sent.

Recording may also stop spontaneously if there is an error, such as running out of
space on your hard disk.
format bit-depth [int] A backwards-compatible message for file format. Use the samptype message for
full soundfile specification.
loop looping-flag (0 or 1) [float] In left inlet: The word loop, followed by 1, turns on looping. loop 0 turns off
looping. By default, looping is off.
open file-type [symbol] In left inlet: Opens a file for recording. By default, the file type is AIFF, but
filename [symbol] sfrecord~ also supports NeXT/Sun, and WAV formats. The word open without a
filename argument brings up a standard Save As dialog allowing you to choose a
filename. The optional symbols aiff, au, raw, or wave specify the file format
(which can also be set in the Save As dialog with a Format pop-up menu). If open
is followed by another symbol, it creates a file in the current default volume. An
existing file with the same name will be overwritten. The format symbol (e.g., aiff)
can follow the optional filename argument.
nchans number-of-channels [int] The word nchans, followed by a number in the range 1-28, sets the number of
channels for the audio file to be recorded. The default is 1.
print Outputs cryptic status information about the progress of the recording.
record recording-time [float] In left inlet: If a file has been opened with the open message, the word record,
followed by a time in milliseconds, begins recording for the specified amount of
time. The recording can be stopped before it reaches the end by sending
sfrecord~ a 0 in its left init.
samptype sample-type [symbol] In left inlet: The word samptype, followed by a symbol, specifies the sample type
bit-depth [int] to use when recording the audio file. The following types of sample data are
supported:

int8: 8-bit integer


int16: 16-bit integer
int24: 24-bit integer
int32: 32-bit integer
float32: 32-bit floating-point
float64: 64-bit floating-point
mulaw: 8-bit "mu"-law encoding
alaw: 8-bit a-law encoding
resample sampling-rate-coefficient The word resample, followed by a float, will upsample or downsample the file.
[float] Sample rates are expressed as floating-point values - 1.0 is the current sampling
rate, 0.5 is half the current, 2.0 is twice the current sample rate, etc.
signal Each inlet of sfrecord~ accepts a signal which is recorded to a channel of an audio
file when recording is turned on.

Information for box attributes common to all objects

Output
signal: The time, in milliseconds, since recording of the file began. If recording has stopped, the signal value will remain at the
length of the last recording until a new recording is started.

Examples

Save an audio file containing 'real world' sound and/or sound created in MSP

See Also
Name Description
sfplay~ Play audio file from disk
MSP Tutorial 16: Record and Play MSP Tutorial 16: Record and Play Audio Files
Audio Files
sig~
Convert numbers into audio signals

Description
Use the sig~ object to convert regular numbers into audio signals.

Arguments
Name Units Type Opt Description
initial-output- number opt Initial signal value
value

Messages
int input [int] Number to be sent as a signal
float input [float] Number to be sent as a signal
signal Has no effect.

Information for box attributes common to all objects

Output
signal: sig~ outputs a constant signal consisting of the value of its argument or the most recently received int or float in its inlet.

Examples

Provide constant numerical values to a signal network with sig~

See Also
Name Description
+~ Add signals
begin~ Define a switchable part of a signal network
line~ Linear ramp generator
snapshot~ Convert signal values to numbers
MSP Tutorial 4: Routing Signals MSP Tutorial 4: Routing Signals
MSP Tutorial 14: Playback with MSP Tutorial 14: Playback with Loops
Loops
sinh~
Signal hyperbolic sine function

Description
Use the sinh~ object to calculate and output a signal that is the hyperbolic sine function of each sample of the input signal.

Arguments
None.

Messages
signal Input to hyperbolic sine function

Information for box attributes common to all objects

Output
signal: The hyperbolic sine of the input.

Examples

sinh~ can generate interesting oscillator-synced audio control signals

See Also
Name Description
asin~ Signal arc-sine function
asinh~ Signal hyperbolic arc-sine function
sinx~ Signal sine function
sinx~
Signal sine function

Description
sinx~ is a real sine function whose input expects values between 0 and 2 (similar to cosx~ but unlike cos~ which is designed to
work with phasor~ 's output from 0 to 1).

Arguments
None.

Messages
signal Input to sine function

Information for box attributes common to all objects

Output
signal: The sine of the input.

Examples

sinx~ can generate cycloids for audio control signals

See Also
Name Description
asin~ Signal arc-sine function
asinh~ Signal hyperbolic arc-sine function
sinh~ Signal hyperbolic sine function
slide~
Filter a signal logarithmically

Description
Use the slide~ object for envelope following and lowpass filtering.

Arguments
Name Units Type Opt Description
slide-up float opt Specifies the slide up value. The default is 1. (Also accepts integers for these
arguments as well as the associated messages which address these parameter
settings.)
slide-down float opt A second argument specifies the slide down value. The default is 1. (Also accepts
integers for these arguments as well as the associated messages which address
these parameter settings.)

Messages
int current-output-sample Sets the current output sample value (the value from which the next incoming
[int] value will smoothly transition from).
float current-output-sample Sets the current output sample value (the value from which the next incoming
[float] value will smoothly transition from).
(inlet1) slide-up [float] In middle inlet: Specifies the slide up value to be used when an incoming value is
greater than the current value.
(inlet2) slide-down [float] In right inlet: Specifies the slide down value to be used when an incoming value is
less than the current value.
signal A signal to be filtered. Whenever a new value is received, slide~ filters the input
signal logarithmically between changes in signal value using the formula:

y (n) = y (n-1) + ((x (n) - y (n-1))/slide)

A given sample output from slide~ is equal to the last sample's value plus the
difference between the last sample's value and the input divided by the slide value.
Given a slide value of 1, the output will therefore always equal the input. Given a
slide value of 10, the output will only change 1/10th as quickly as the input. This
can be particularly useful for lowpass filtering or envelope following.
slide_down slide-down [float] The message slide_down followed by a float will specify the slide-down value to be
used when an incoming value is less than the current value.
slide_up slide-up [float] The message slide_up followed by a float will specify the slide-up value to be used
when an incoming value is greater than the current value.
reset Sets the current output sample value to 0(the next incoming value will smoothly
transition from that 0).

Information for box attributes common to all objects

Output
signal: The filtered signal.

Examples
slide~ performs logarithmic smoothing of an input signal

See Also
Name Description
rampsmooth~ Smooth an incoming signal
Audio Filtering Audio Filtering
snapshot~
Convert signal values to numbers

Description
Use the snapshot~ object to convert a signal value into a float message when a bang is received or according to a specified
interval. The interval can be set to a fixed or tempo-relative rate using the Max time format syntax.

Arguments
Name Units Type Opt Description
reporting- time- list opt Set the reporting interval in ms or using the Max time format syntax. If the
interval value interval is 0 snapshot~ will only output data when it receives a bang message.

Messages
bang Report the input signal value
int internal-clock-enable- In left inlet: Any non-zero value turns on interval-based reporting, 0 turns it off.
flag [int] Reporting is on by default if a non-zero interval was specified.
In right inlet: Set the reporting interval in ms. If the interval is 0, automatic
reporting stops.
float internal-clock-enable- In left inlet: Any non-zero value turns on interval-based reporting, 0 turns it off.
flag [float] Reporting is on by default if a non-zero interval was specified.
In right inlet: Set the reporting interval in ms. If the interval is 0, automatic
reporting stops.
list ITM-time-list [list] Set interval in Max time format.
anything ITM-time-list [list] Set interval in Max time format.
offset sample-offset [int] Set the index of the sample within a signal vector that will be reported. The
number is constrained between 0 (least recent, the default) and the current signal
vector size minus one (most recent).
sampleinterval internal-clock-interval Set interval in samples
[int]
signal Signal to evaluate
start Start interval-based reporting
stop Stop interval-based reporting

Attributes
Name Type g/s Description
active int Active
interval atom Sampling Interval

Information for box attributes common to all objects

Output
float: When snapshot~ receives a bang, or its internal clock is on, sample values from the input signal are sent out its outlet.

Examples
See a sample of a signal at a given moment

See Also
Name Description
capture~ Store a signal to view as text
number~ Signal monitor and constant generator
sig~ Convert numbers into audio signals
MSP Tutorial 23: Viewing Signal MSP Tutorial 23: Viewing Signal Data
Data
spectroscope~
Signal spectrogram or sonogram

Description
spectroscope~ serves as a visual spectrogram or sonogram interface for the analysis of signals.

Arguments
None.

Messages
signal In left inlet: The input signal is analyzed and its spectrum is displayed. If the object
is placed inside a pfft~ object's subpatcher, the left inlet is used for the real signal
coming from the left outlet of a fftin~ object.

In right inlet: If the object is placed inside a pfft~ object's subpatcher, the right
inlet is used for the imaginary signal coming from the second outlet of a fftin~
object. When not inside a pfft~ subpatcher, this inlet does nothing.

Attributes
Name Type g/s Description
bgcolor float Sets the Spectrogram Background Color of the spectroscope~ object in RGBA
format.
border int Toggles drawing a border around the spectroscope~ object.
def.:1
bordercolor float Sets the border color of the spectroscope~ object in RGBA format.
curvecolor float Sets the curve color of the spectroscope~ object in RGBA format.
domain float Sets the low and high domain (frequency) values.
def.:0. 22050.
fgcolor float Sets the Spectrogram Foreground Color of the spectroscope~ object in RGBA
format.
interval int Sets the polling interval, in milliseconds.
def.:20
logamp int Toggles between linear (0) and logarithmic (1) amplitude display. By default it is
def.:1 set to logarithmic display.
'Linear Scale' = TEXT_HERE
'Logarithmic Scale' = TEXT_HERE
logfreq int Toggles log frequency display. By default it is off, but when turned on, the
def.:0 spectrogram or sonogram's frequencies are shown on a logarithmic scale.
'Linear Scale' = TEXT_HERE
'Logarithmic Scale' = TEXT_HERE
markercolor float Sets the marker color of the spectroscope~ object in RGBA format.
monochrome int Toggles monochrome display of the sonogram. When turned off, the sonogram
def.:1 display uses a series of five colors.
'Color' = Two-color sonogram display
'Monochrome' = Monochrome sonogram display
orientation int Sets the vertical or horizontal orientation of the spectroscope~ object. By default
def.:0 it is horizontal, which means frequencies are displayed along the horizontal axis
and amplitudes are displayed along the vertical axis in spectrogram mode, and
time is displayed along the horizontal axis and frequency is displayed along the
vertical axis in sonogram mode. In vertical mode the axes are reversed.
'Horizontal' = Horizontal display
'Vertical' = Vertical display
phasespect int Toggles the Amplitude/Phase spectrum display.
def.:0 'Amplitude' = TEXT_HERE
'Phase' = TEXT_HERE
range float Sets the minimum and maximum displayed amplitudes of the spectrum. The
def.:0. 1.2 default values are 0 and 1.2, for the minimum and maximum, respectively. If the
word range is followed by only one number, then it is used as the maximum value,
and the minimum range is set to zero.
rounded int Sets the roundness (radius), in pixels, for the spectroscope~ object.
def.:8
scroll int Sets the sonogram scrolling mode. By default the sonogram scrolling mode is set
def.:0 to Forward Draw.

'Forward Draw' = TEXT_HERE


'Reverse Draw' = TEXT_HERE
'Forward Scroll' = TEXT_HERE
'Reverse Scroll' = TEXT_HERE
sono int Toggles sonogram mode. By default the sonogram display is off (meaning it
def.:0 displays a spectrogram, instead). N.B.: Although the terms "spectrogram" and
"sonogram" are generally used interchangably to refer to a graph of the spectrum
over time, we are using "spectrogram" in its literal sense - to refer to the drawing
of a spectrum as an amplitude/frequency representation.
'Spectrogram' = TEXT_HERE
'Sonogram' = TEXT_HERE
sonohicolor float Sets the color in RGBA format used by the spectroscope~ for displaying
frequencies in the high audio range when the object is in color sonogram mode.
sonolocolor float Sets the color in RGBA format used by the spectroscope~ for displaying
frequencies in the low audio range when the object is in color sonogram mode.
sonomedcolor float Sets the color in RGBA format used by the spectroscope~ for displaying
frequencies in the medium audio range when the object is in color sonogram
mode.
sonomedhicolor float Sets the color in RGBA format used by the spectroscope~ for displaying
frequencies in the medium high audio range when the object is in color sonogram
mode.
sonomedlocolor float Sets the color in RGBA format used by the spectroscope~ for displaying
frequencies in the low medium audio range when the object is in color sonogram
mode.
sonomonobgcolor float Sets the background color of the spectroscope~ display in RGBA format when
the object is displaying sonograms in two-color mode.
sonomonofgcolor float Sets the foreground color of the spectroscope~ display in RGBA format when the
object is displaying sonograms in two-color mode.

Information for box attributes common to all objects

Output
Visual: The frequency/amplitude content of the signal is displayed.

Examples
Display a sonogram in living color

See Also
Name Description
meter~ Visual peak level indicator
scope~ Visualize an audio signal
spike~
Report intervals of zero to non-zero transitions

Description
spike~ reports intervals of zero to non-zero transitions.

Arguments
Name Units Type Opt Description
refractory- ms int or opt Sets the refractory period.
period float

Messages
bang bang will cause the object to restart the countdown of the refractory period from
the time at which the bang was received.
signal In left inlet: A signal to be analyzed. The spike~ object analyzes an incoming signal
and reports the interval, in milliseconds, between transitions between zero and
non-zero signal values. You can specify a refractory period, which defines how
soon after detecting a transition the spike~ object will report the next instance.

Information for box attributes common to all objects

Output
float: The interval, in milliseconds, since the last zero to non-zero signal transition has occurred (which includes the refractory
period, if one is set).

Examples

spike~ reports how often a zero to non-zero transition occurs in its input signal

See Also
Name Description
change~ Report signal direction
edge~ Detect logical signal transitions
zerox~ Detect zero crossings
sqrt~
Square root of a signal

Description
sqrt~ will output a signal which is the square-root function of the input signal.

Arguments
None.

Messages
signal The object outputs a signal that is the square root of the input signal. A negative
input has no real solution, so it causes an output of 0.

Information for box attributes common to all objects

Output
signal: The square root of the input signal.

Examples

Output signal is the square root of the input signal

See Also
Name Description
curve~ Exponential ramp generator
log~ Logarithm of a signal
pow~ Signal power function
stutter~
Signal capture buffer for granular playback

Description
The stutter~ object keeps a history of its signal input (left inlet). Upon receiving an int (left inlet), it copies that number of the
most recently received samples to another playback buffer. This buffer may be cycled through by its phase, 0-1 (right inlet). On
receiving a bang (left inlet) or a trigger signal (middle inlet), the last integer number of samples are copied to the playback buffer.

Arguments
Name Units Type Opt Description
max-buffer- samples int The maximum buffer length, in samples. This determines the memory size of the
length record buffer. Parts of the record buffer are copied to the playback buffer when the
object is triggered.
initial-buffer-size samples int The initial buffer size, in samples, to copy from the record to the playback buffer
upon receiving a trigger.
trigger-polarity int The polarity to use for accepting a trigger signal in the middle inlet. If the
argument is greater than 0, stutter~ accepts a positive trigger; otherwise stutter~
accepts a negative trigger.
number-of- samples int The number of samples which are copied from the record buffer to the playback
copied-samples buffer each iteration of the perform loop (the signal vector size). A larger value will
decrease the stutter~ object's memory requirements and increase the CPU
requirements.
number-of- int opt An optional fifth argument allows you to specify multiple independent signal
outputs outputs the stutter~ object will use when playing back from the playback buffer.
The default is 1, and the maximum is 30. The number of phase signal inputs to the
stutter~ object is also determined by this argument.

Messages
bang In left inlet: A bang causes the last buffer of recorded samples to be copied to the
playback buffer. You can use a bang instead of or in conjunction with the middle
inlet trigger signal.
int playback-buffer-size [int] In left inlet: Specifies the size (in samples) of the playback buffer. This can be any
number up to the maximum memory determined by the first argument to
stutter~.
ampvar random-amplitude-variation The word ampvar, followed by a float, specifies a random amplitude variation in
[float] the output signal(s). The default is 0 (no variation).
clear Clears the object's sample memory.
dropout drop-out-chance [float] The word dropout, followed by a float, determines the percentage chance of a
playback signal dropping out (i.e. 'gapping' or not playing). The default is 0 (no
gapping).
maxsize max-buffer-size [int] The word maxsize, followed by a number, sets the maximum buffer size, in
samples.
polarity trigger-polarity [int] The word polarity, followed by a zero or one, changes the trigger polarity of
stutter~ to negative or positive, respectively.
print The word print will cause the object to print a detailed listing of all of its
parameter settings within the Max window.
repeat repeat-chance [float] The word repeat, followed by a float, determines the percentage change of the
record buffer not being copied to the playback buffer so that the previous playback
buffer is repeated. The default is 0 (no repeat).
setbuf buffer-name [symbol] The word setbuf, followed by arguments for a buffer name, a sample offset, and a
sample-offset [int] channel, copies the specified samples to the named buffer~ object. Note: stutter~
channel-number [int] always uses its internal buffer as the playback buffer; the copied samples can be
sent to a named buffer~ object for use in some other way, if desired. The time
required to move the specified amount of memory to the buffer is n/m, there n is
the number of samples being copied and m is the fourth argument to the stutter~
object.
signal In left inlet: Signals coming into the left inlet are stored in a record buffer, where
they can be copied into a playback buffer and used as a playback source.

In middle inlet: Accepts a trigger signal, which can be specified to be positive or


negative. When the signal changes polarity in the correct direction, samples
recorded from the left inlet are copied to the playback buffer.

In right and successive inlets: A phase signal input in the range of 0-1 for each inlet
controls the output speed of the playback buffer for that inlet. The number of
phase inlets in a stutter~ object is set using the fifth argument; the default is a
single inlet. Specifying multiple phase inlets allows you to specify multiple
playback points in the sampled buffer.

Information for box attributes common to all objects

Output
signal: All outlets: The stutter~ object's outlets produce a signal from the playback buffer, the location and speed of which is
determined by the phase input for that playback outlet. The number of outlets is determined by the fifth argument to the
stutter~ object.

Examples

stutter~ captures a new slice of incoming sound into an oscillating buffer whenever it receives a trigger

See Also
Name Description
buffer~ Store audio samples
phasor~ Generate sawtooth signals
record~ Record sound into a buffer
svf~
State-variable filter with simultaneous outputs

Description
The svf~ object is an implementation of a state-variable filter algorithm described in Hal Chamberlin's book, "Musical
Applications of Microprocessors." A unique feature of this filter object is that it produces lowpass, highpass, bandpass, and
bandreject (notch) output simultaneously - all four are available as outlets.

Arguments
Name Units Type Opt Description
initial-gain float opt Sets the initial gain. The default value is 0.
center-frequency hz float opt Sets the initial center frequency for the filter. The default value is 0.
Q float opt Sets the initial Q value for the filter. The default value is 0.01.
Hz symbol opt Sets the frequency input mode to Hz (the default mode - hence this is the same as
providing no mode argument).
linear symbol opt Sets the frequency input mode to linear (0 -1).
radians symbol opt Sets the frequency input mode to radians (0 -1).

Messages
int center-frequency/Q [int] In middle and right inlets: Integer values are converted to floats and can be sent in
the two right inlets to change the center frequency and Q of the filter. By default,
the center frequency is expressed in Hz, where the allowable range is from 0 to one
quarter of the current sampling rate. If a signal is connected to one of the inlets, a
number received in that inlet is ignored. The values are sampled once every signal
vector.
float center-frequency/Q [float] In middle and right inlets: A float can be sent in the two right inlets to change the
center frequency and Q of the filter. By default, the center frequency is expressed
in Hz, where the allowable range is from 0 to one quarter of the current sampling
rate. For convenience, svf~ has two additional input modes that use the more
conventional input range, 0 - 1. (see the linear and radians messages). If a signal
is connected to one of the inlets, a number received in that inlet is ignored. The
values are sampled once every signal vector.
Hz In either inlet: Sets the frequency input mode to Hz (the default).
clear Clears the object's sample-memory in case of a blow-up.
linear In any inlet: Sets the frequency input mode to linear (0 - 1). Linear mode is simply
a scaled version of the standard Hz mode, except that values in the 0-1 range
traverse the full frequency range.
radians In any inlet: Sets the frequency input mode to radians (0 - 1). Radians mode lets
you set the center frequency directly -- while the input has the same range (0-1),
the output has a curved frequency response that is closer to the exponential pitch
scale of the human ear.
signal In left inlet: Signal to be filtered.

In middle inlet: Sets the filter center frequency in Hz.

In right inlet: Sets the bandpass filter "Q" - roughly, the sharpness of the filter -
where Q is defined as the filter bandwidth divided by the center frequency. Useful
Q values are typically between 0.01 and 500.

Information for box attributes common to all objects

Output
signal: The filtered input signal.

Examples

Four filter outputs are simultaneously available from the svf~ object

See Also
Name Description
biquad~ Two-pole, two-zero filter
comb~ Apply a comb filter effect
cross~ Third-order crossover filter
onepole~ Single-pole lowpass filter
lores~ Resonant lowpass filter
reson~ Resonant bandpass filter
State-variable filter with simultaneous outputs
Audio Filtering Audio Filtering
sync~
Synchronize MSP with an external source

Description
sync~ outputs a 0-1 ramp, like phasor~. The frequency of the ramp can be specified in beats per minute (BPM), or by sending
sync~ a tempo reference via tap tempo, MIDI beat clock, or an audio signal containing a 'click track.' Also, sync~ generates MIDI
beat clock to synchronize external devices.

Arguments
None.

Messages
bang A sequence of bang messages is used to set the tap tempo. A bang message is
interpreted as one tap. If the sync~ object receives three taps in a row with
reasonably consistent timing, it changes the tempo to match them.
int MIDI-data [int] MIDI beat clock. Integer input is interpreted as MIDI data - you can directly
connect the output of an rtin object. sync~ responds to MIDI beat clock start/stop
(int 250 and 252), and tick (248). All other values are ignored.
float beats-per-minute [float] Sets the BPM for the clock.
bpm bpm-rate [float] The word bpm, followed by a number, sets the rate of the current output ramp to
a frequency corresponding to the specified beats/minute.
midioffset output-phase [float] The word offset, followed by a floating point number in the range 0.-1.0, adjusts
the MIDI output "phase" of the current output ramp.
offset ramp-phase [float] The word offset, followed by a floating point number in the range 0.-1.0, adjusts
the "phase" of the current output ramp.
ppq number-of-ticks-per- The word ppq (parts per quarter), followed by a number, specifies the number of
quarter-note [int] ticks output for each quarter note. By default, MIDI beat clock specifies a PPQ of
24. The ppq message is useful mainly for doubling or halving the tempo for an
external device that is set to a different time signature. The ramp signal generated
by the sync~ object can be scaled for output further by using the rate~ object.
signal The sync~ object will set its tempo to match an audio click track input. The click
track should contain amplitude peaks at quarter-note intervals of the desired
tempo. Signal input will affect the tempo only if sync~ detects peak values greater
than 0.1 and within the tempo range of approximately 30-240 BPM.
start The word start causes the current output ramp to halt, and resets the ramp to 0.
The start message has the same effect as receiving the MIDI beat clock start value
(250). When the start message is received, sync~ outputs the number 250 from
the MIDI beat clock output so that any external devices will also start.
stop The word stop causes the current output ramp to halt, and to remain stationary
until a start message is received. It is equivalent to sending the MIDI beat clock
stop value (252). When the stop message is received, the sync~ object sends the
number 252 from its MIDI beat clock output. The sync~ object does not send
MIDI beat clock ticks while it is stopped.

Information for box attributes common to all objects

Output
bpm: Out middle outlet: Whenever the tempo changes, sync~ outputs the message bpm, followed by a float value that specifies
the new tempo.
click: Out middle outlet: When the sync~ object receives an audio click, it sends a click message out the middle outlet.
int: Out right outlet: sync~ generates a MIDI beat clock stream that matches its output ramp. Typically, when needed, this outlet
is connected directly to a midiout object.
midi: Out middle outlet: When the sync~ object receives a MIDI beat clock tick, it sends a midi message out the middle outlet.
signal: Left outlet: Like the phasor~-object, the sync~ object generates a sawtooth waveform that increases from 0 to 1 for each
quarter note of the current tempo. This ramp can be scaled as necessary with the rate~ object, for use with wave~ and other
objects.
tap: Out middle outlet: When the sync~ object receives a tap, it sends a tap message out the middle outlet.

Examples

See Also
Name Description
midiout Transmit raw MIDI data
phasor~ Generate sawtooth signals
rate~ Time-scale the output of a phasor~
rtin Receive MIDI real time messages
seq Sequencer for recording and playing MIDI data
transport Control a master clock
wave~ Variable size wavetable
tanh~
Signal hyperbolic tangent function

Description
Use the tanh~ object to calculate and output a signal that is the hyperbolic tangent function of each sample of the input signal.

Arguments
None.

Messages
signal Input to hyperbolic tangent function

Information for box attributes common to all objects

Output
signal: The hyperbolic tangent of the input.

Examples

Use tanh~ to generate periodic control signals

See Also
Name Description
atan~ Signal arc-tangent function
atanh~ Signal hyperbolic arc-tangent function
atan2~ Signal arc-tangent function (two variables)
tanx~ Signal tangent function
tanx~
Signal tangent function

Description
Use the tanx~ object to calculate and output a signal that is the tangent function of each sample of the input signal. The tanx~
object is a true based function - it varies from the tanh~ object, whose output is based around 1 and is intended for use as a
lookup table with the phasor~ object.

Arguments
None.

Messages
signal Input to tangent function

Information for box attributes common to all objects

Output
signal: The tangent of the input.

Examples

Generate spikes (tangents increase exponentially as the input approaches 2-pi) using tanx~

See Also
Name Description
atan~ Signal arc-tangent function
atanh~ Signal hyperbolic arc-tangent function
atan2~ Signal arc-tangent function (two variables)
tanh~ Signal hyperbolic tangent function
tapin~
Input to a delay line

Description
tapin~ receives a signal in and copies into a delay line. Using tapout~ objects, you can read from the delay line at various delay
times. You must connect the outlet of a tapin~ object to the tapout~ objects you want to use with the delay line. Note that this is
not a signal connection, since no signal travels between the objects. It is merely a way to indicate that the objects share the same
delay memory.

Arguments
Name Units Type Opt Description
maximum-delay ms number opt The maximum delay time in milliseconds. This determines the size of the delay
line memory. If the sampling rate is increased after the object has been created,
tapin~ will attempt to resize the delay line. If no argument is present, the default
maximum delay time is 100 milliseconds.

Messages
int memory-size [int] In left inlet: An int resizes the delay line memory with the new maximum delay
time specified in milliseconds (this clears the memory of the delay line, which may
produce a click in the output).
float memory-size [float] In left inlet: A float resizes the delay line memory with the new maximum delay
time specified in milliseconds (this clears the memory of the delay line, which may
produce a click in the output).
clear Clears the memory of the delay line (which may produce a click in the output).
freeze behavioral-flag (0 or nonzero) The word freeze followed by a non-zero number will cause tapin~ to freeze its
[int] buffer memory. This means the object will keep echoing out of its output what has
already been recorded into its memory at the point of freezing and no further
input will be recorded. The word freeze followed by a 0 will reset the object to its
default state of constantly recording and rerecording any given input into its
memory buffer and outputting it after the specified delay time.
signal The signal is written into a delay line that can be read by the tapout~ object.

Information for box attributes common to all objects

Output
tap: In order for the delay line to function, the outlet of tapin~ must be connected to the left inlet of tapout~. It cannot be
connected to any other object.

Examples
tapin~ creates a delay buffer from which to tap delayed signal

See Also
Name Description
delay~ Delay a signal
tapout~ Output from a delay line
MSP Tutorial 27: Delay Lines MSP Tutorial 27: Delay Lines
MSP Tutorial 28: Delay Lines with MSP Tutorial 28: Delay Lines with Feedback
Feedback
MSP Tutorial 29: Flanging MSP Tutorial 29: Flanging
tapout~
Output from a delay line

Description
The outlet of a tapin~ object must be connected to the left inlet of tapout~ in order for the delay line to function.

The tapout~ object has one or more inlets and one or more outlets. A delay time signal or number received in an inlet affects the
output signal coming out of the outlet directly below the inlet.

Arguments
Name Units Type Opt Description
initial-delay ms number opt One or more initial delay times in milliseconds, one for each delay "tap" inlet-
outlet pair desired. For example, the arguments 50 100 300 would create a
tapout~ object with three independent "taps" corresponding to three inlets and
three outlets. If a signal is connected to an inlet, the initial delay time
corresponding to that inlet-outlet pair is ignored.

Messages
int delay-time [int] If a signal is not connected to an inlet of tapout~, a fixed delay algorithm is used,
and a float or int received in the inlet sets the delay time of the signal coming out
of the corresponding outlet. This may cause clicks to appear in the output when
the delay time is changed. However, fixed delay is suitable for many applications
such as reverberation where delay times do not change dynamically, and it is
computationally less expensive than the continuous delay algorithm.
float delay-time [float] If a signal is not connected to an inlet of tapout~, a fixed delay algorithm is used,
and a float or int received in the inlet sets the delay time of the signal coming out
of the corresponding outlet. This may cause clicks to appear in the output when
the delay time is changed. However, fixed delay is suitable for many applications
such as reverberation where delay times do not change dynamically, and it is
computationally less expensive than the continuous delay algorithm.
list delay-times- In left inlet: Allows several fixed delay times to be changed at the same time. The
corresponding-to-outlets first number in the list sets the delay time for the first outlet, and so on. If any
[list] inlets corresponding to list values have signals connected to them, the values are
skipped.
tapconnect The word tapconnect will connect a tapout~ object to an available tapin~ object
remotely.
signal If a signal is connected to an inlet of tapout~, the signal coming out of the outlet
below it will use a continuous delay algorithm. Incoming signal values represent
the delay time in milliseconds. If the signal increases slowly enough, the pitch of
the output will decrease, while, if the signal decreases slowly, the pitch of the
output will increase. The continuous delay algorithm is more computationally
expensive than the fixed delay algorithm that is used when a signal is not
connected to a tapout~ inlet.

Information for box attributes common to all objects

Output
signal: Each outlet of tapout~ corresponds to an individually controlled "tap" of a delay line written by the tapin~ object. The
output signal coming out of a tapout~ outlet is the input to tapin~ delayed by the number of milliseconds specified by the
numerical or signal control received in the inlet directly above the outlet.

Examples
tapout~ sends out the signal tapin~ receives, delayed by some amount of time

See Also
Name Description
delay~ Delay a signal
tapin~ Input to a delay line
MSP Tutorial 27: Delay Lines MSP Tutorial 27: Delay Lines
MSP Tutorial 28: Delay Lines with MSP Tutorial 28: Delay Lines with Feedback
Feedback
MSP Tutorial 29: Flanging MSP Tutorial 29: Flanging
MSP Tutorial 30: Chorus MSP Tutorial 30: Chorus
techno~
Signal-driven step sequencer

Description
techno~ is a signal-based step-sequencer that facilitates sample-accurate timing of events.

Arguments
None.

Messages
amplitude sequencer-step [int] The word amplitude, followed by a number that specifies the sequencer step and
amplitude-value [float] a float that specifies an amplitude value, sets the amplitude (as an absolute factor)
of a step's output note. The amplitude is specified as an absolute factor of that
step's note -- an amplitude of 1.0 will result in the amplitude output signal having
a value of 1.0 at the very beginning of the step.
attack sequencer-step [int] The word attack, followed by a number that specifies the sequencer step and a
attack-curve-exponent float that specifies the exponent of a curve, sets the curve used to calculate the
[float] amplitude trajectory from 0.0 at the beginning of the previous step to the
amplitude value at the beginning of the current step. The values used to specify
the exponents of the curve are the same as those used for the curve message.
curve sequencer-step [int] The word curve, followed by a number that specifies the sequencer step and a
curve-exponent [float] float that specifies the exponent of a curve, sets the curve used to calculate the
trajectory of pitch from the previous step.

A value of 1.0 represents a linear slide from the previous step; a value of 0.5
represents a square root function; a value of 2.0 represents a second-order
parabolic slide; etc. The curve message lets you set and experiment with different
varieties of portamento.
decay sequencer-step [int] The word decay, followed by a number that specifies the sequencer step and a
decay-trajectory-exponent float that specifies the exponent of a curve, sets the curve used to calculate the
[float] decay trajectory from the amplitude value at the beginning of this previous step to
0.0 at the beginning of the next step. The values used to specify the exponents of
the curve are the same as those used for the curve message.
length number-of-steps [int] The word length, followed by a number, sets the number of notes in the
sequence. The default is 1.
pitch sequencer-step [int] The word pitch, followed by a number that specifies the sequencer step and a float
frequency [float] that specifies a pitch as a Hertz frequency, sets the pitch of that step's note.
pos sequencer-step [int] The word pos, followed by an integer that specifies the sequencer step and a float
start-position (step-size- that specifies a start position, positions the step to the specified position. A step
coefficient) [float] may not be placed before the previous step or after the next step. For instance, a
uniformly-spaced four step sequence will have its steps in positions 0.0, 0.25, 0.5
and 0.75, so a pos message for the third step (index 2) can only specify positions
between 0.25 and 0.75.
signal A signal is used as an input to the techno~ object to specify the step position in a
sequence. The signal is in the range 0 - 1.0 and indicates a phase value, expressed
as a fraction of the number of total steps in the sequence (set using the length
message). A phasor~ object is customarily used as input to the techno~ object.
All input signals are clipped to the range 0 - 1.0.
repeatpos step-width [list] The word repeatpos, followed by one or more floats, allows repeating settings of
non-uniform sequencer step sizes. The number of floats following the lengths
message represents one less than the size of the repeating segment of steps - this
segment size can be any even divisor of the total number of steps in the sequence.
So for instance with an eight-step sequence the length of the segment can be 2, 4,
or 8 steps. The floating point arguments, which must be strictly increasing and in
the range between 0 and 1, set the relative width of each step. For instance, one
can set uniform divisions for a sequence with an even number of steps with any of
the following messages:

repeatpos 0.5

repeatpos 0.25 0.5 0.75

repeatpos 0.125 0.25 0.375 0.5 0.625 0.75 0.875

The message repeatpos 0.66 affects a repeating segment two steps long, giving
the first step 66% of the time and the second step 34%. (This is like classic "swing"
on a drum machine.)

Information for box attributes common to all objects

Output
signal: Out left inlet: Pitch signal output for oscillator(s).

Out middle inlet: An amplitude envelope. You can multiply this signal output with the output of your oscillators.

Out right inlet: The current position in the step sequence. Each step represents a distance of 1.0 and the total output range is
from 0 to the value set by the size message.

Examples

techno~ use as a synth sequencer or to trigger individual samples, like a drum machine

See Also
Name Description
adsr~ ADSR envelope generator
cycle~ Sinusoidal oscillator
phasor~ Generate sawtooth signals
rate~ Time-scale the output of a phasor~
rect~ Antialiased rectangular (pulse) oscillator
saw~ Antialiased sawtooth oscillator
seq~ Signal-driven event sequencer
svf~ State-variable filter with simultaneous outputs
tri~ Antialiased triangular oscillator
teeth~
Comb filter with feedforward and feedback delay control

Description
The teeth~ object implements a comb filter, in which a slightly delayed version of a signal is added to itself, causing phase
cancellations and a spectrum that looks like a comb.

Arguments
Name Units Type Opt Description
feedforward-delay ms float opt Sets the initial value for the feedforward delay, in milliseconds. If a signal is
connected to this inlet, the coefficient supplied as an argument for that inlet is
ignored. If no argument is present, the delay time defaults to 10 milliseconds.
feedback-delay ms float opt Sets the initial value for the feedback delay, in milliseconds. If a signal is connected
to this inlet, the coefficient supplied as an argument for that inlet is ignored. If no
argument is present, the delay time defaults to 10 milliseconds.
gain float opt Sets the initial value for the gain. If a signal is connected to this inlet, the
coefficient supplied as an argument for that inlet is ignored. If no argument is
present, the value defaults to 0.
feedforward-gain float opt Sets the initial value for the feedforward gain. If a signal is connected to this inlet,
the coefficient supplied as an argument for that inlet is ignored. If no argument is
present, the value defaults to 0.
feedback-gain float opt Sets the initial value for the feedback gain. If a signal is connected to this inlet, the
coefficient supplied as an argument for that inlet is ignored. If no argument is
present, the value defaults to 0.

Messages
int filter-parameters [int] The filter parameters in inlets 2 to 6 may be specified by a float instead of a signal.
If a signal is also connected to the inlet, the float is ignored.
float filter-parameters [float] The filter parameters in inlets 2 to 6 may be specified by a float instead of a signal.
If a signal is also connected to the inlet, the float is ignored.
clear Clears the teeth~ object's memory of previous outputs, resetting them to 0.
signal In left inlet: Signal to be filtered. The teeth~ object is a variant of comb~-- a
comb filter that mixes the current input sample with earlier input and/or output
samples to accentuate and attenuate the input signal at regularly spaced frequency
intervals. Unlike the comb~ object, teeth~ adds feedforward and feedback, which
adds to the extremity of the effect.

In 2nd inlet: Feedforward - the delay, in milliseconds, before past samples of the
input are added to the current input.

In 3rd inlet: Feedback - the delay, in milliseconds, before past samples of the
output are added to the current input.

In 4th inlet: Gain coefficient - for scaling the amount of the input sample to be
sent to the output.

In 5th inlet: Gain coefficient - for scaling the amount of feedforward to be sent to
the output.

In right inlet: Gain coefficient - for scaling the amount of feedback to be sent to the
output.
list feedforward-delay [float] The five parameters can be provided as a list in the left inlet. The first number in
feedback-delay [float] the list is the feedforward delay, the next number is the feedback delay, the third
gain [float] number is the Gain coefficient for the input sample, the fourth number is the
feedforward-gain [float] feedforward gain coefficient, and the fifth number is the feedback gain coefficient.
feedback-gain [float] If a signal is connected to a given inlet, the coefficient supplied in the list for that
inlet is ignored.

Information for box attributes common to all objects

Output
signal: The filtered signal.

Examples

teeth~ does comb filtering on an input signal with variable feedforward and feedback delays

See Also
Name Description
allpass~ Apply an allpass filter effect
comb~ Apply a comb filter effect
delay~ Delay a signal
reson~ Resonant bandpass filter
Audio Filtering Audio Filtering
thispoly~
Control poly~ voice allocation and muting

Description
Use the thispoly~ object to control poly~ voice allocation and muting. When placed inside a patcher loaded by the poly~ object,
it sends and receives messages from the poly~ object that loads it.

Arguments
None.

Messages
bang Reports the instance number of the patch. The first instance is reported as 1.
int busy-state [int] Toggles the "busy" state for the patcher instance when the message busy 1 is
received. The object will not receive messages generated by a note or midinote
message to the left inlet of the parent poly~ object when the "busy" state is on.
mute mute-flag [int] Disables DSP processing for the loaded instance of the patcher when the message
mute 1 is received. This message can be combined with an int message which
toggles the "busy" state of the patcher to create voices in a patcher which are only
on while they play a "note".
signal Sets the "busy" state of the patcher instance. The busy state for the patcher
instance is set to 1 when the thispoly~ object receives a non-zero input signal. The
busy state is set to 0 otherwise.

Information for box attributes common to all objects

Output
int: Out left outlet: The instance number, starting at 1, reported when thispoly~ receives the bang message. If the patcher
containing thispoly~ was not loaded within a poly~ object, 0 is output.
int: Out right outlet: If the loaded instance of the patcher is muted, a 1 is output. If the instance is not muted, a 0 is output.

Examples

thispoly~ reports the instance number of its poly~ subpatcher

See Also
Name Description
in Message input for a patcher loaded by poly~ or pfft~
in~ Signal input for a patcher loaded by poly~
out Message output for a patcher loaded by poly~ or pfft~
out~ Signal output for a patcher loaded by poly~
poly~ Manage polyphony/DSP for patchers
MSP Tutorial 21: Using the poly~ MSP Tutorial 21: Using the poly~ Object
Object
thresh~
Detect signal above a set level

Description
Use the thresh~ object to detect signals which exceed a specified level.

Arguments
Name Units Type Opt Description
low/reset-threshold float The first argument specifies the reset or low threshold level. If no argument is
present, the reset level is 0.

If only one argument is present, it specifies the reset level, and the set level is 0.
high/set-threshold float The second argument specifies the set or high threshold level. If no argument is
present, the set level is 0.

Messages
float reset/set-threshold [float] In middle inlet: Sets the lower ("reset") threshold level for the input signal. When
a sample in the input signal is greater than or equal to the upper ("set") level,
thresh~ sends out a signal of 1 until a sample in the input signal is less than or
equal to this reset level.

In right inlet: Sets the upper ("set") threshold level for the input signal. When the
input is equal to or greater than this value, thresh~ sends out a signal of 1.
signal In left inlet: A signal whose level you want to detect.

Information for box attributes common to all objects

Output
signal: When a sample in the input signal is greater than or equal to the upper threshold level, the output is 1. The output
continues to be 1 until a sample in the input signal is equal to or less than the reset level. If the set level and the reset level are
the same, the output is 1 until a sample in the input signal is less than the reset level.

Examples

Detect when signal exceeds a certain level

See Also
Name Description
>~ Is greater than, comparison of two signals
change~ Report signal direction
edge~ Detect logical signal transitions
*~
Multiply two signals

Description
*~ is a signal multiplier-operator that outputs a signal which is the multiplication between two signals.

Arguments
Name Units Type Opt Description
initial-multiplier number opt Sets an initial value by which to multiply the signal coming into the left inlet. If a
signal is connected to the right inlet, the argument is ignored. If no argument is
present, and no signal is connected to the right inlet, the initial value is 0 by
default.

Messages
int input [int] In left inlet: A factor by which to multiply the signal coming into the right inlet. If
a signal is also connected to the left inlet, a float or int is ignored.

In right inlet: A factor by which to multiply the signal coming into the left inlet. If
a signal is also connected to the right inlet, a float or int is ignored.
float input [float] In left inlet: A factor by which to multiply the signal coming into the right inlet. If
a signal is also connected to the left inlet, a float or int is ignored.

In right inlet: A factor by which to multiply the signal coming into the left inlet. If
a signal is also connected to the right inlet, a float or int is ignored.
signal In left inlet: The signal is multiplied by the signal coming into the right inlet, or a
constant value received in the right inlet.

In right inlet: The signal is multiplied by the signal coming into the left inlet, or a
constant value received in the left inlet.

Information for box attributes common to all objects

Output
signal: The product of the two inputs.

Examples

Scale a signal's amplitude by a constant or changing value, or by another audio signal

See Also
Name Description
/~ Divide one signal by another
!/~ Divide input from a number
MSP Tutorial 2: Adjustable MSP Tutorial 2: Adjustable Oscillator
Oscillator
MSP Tutorial 8: Tremolo and Ring MSP Tutorial 8: Tremolo and Ring Modulation
Modulation
train~
Pulse train generator

Description
train~ generates a pulse signal whose period is specifiable in terms of milliseconds (see <~ for a method of making a pulse wave
at a specified frequency). It also sends out a bang when going from 0 to 1, so it can be used as a metronome with a floating-point
interval.

Arguments
Name Units Type Opt Description
inter-pulse- ms number opt Sets the initial value for the inter-pulse interval in milliseconds. The default is
interval 1000 ms. If a signal object is connected to this inlet, the corresponding initial
argument value is ignored.
pulse-width number opt Sets the initial value for the pulse width. The default is 0.5. If a signal object is
connected to this inlet, the corresponding initial argument value is ignored.
phase number opt Sets the initial value for the pulse phase. The default is 0. If a signal object is
connected to this inlet, the corresponding initial argument value is ignored.

Messages
int parameter-settings [int] Numbers can be used instead of signal objects to control period, pulse width, and
phase. If a signal is also connected to the inlet, float and int messages are
ignored.
float parameter-settings [float] Numbers can be used instead of signal objects to control period, pulse width, and
phase. If a signal is also connected to the inlet, float and int messages are
ignored.
signal In left inlet: Specifies the period (time interval between pulse cycles), in
milliseconds, of a pulse train sent out the left outlet.

In middle inlet: Controls the pulse width or duty cycle. The signal values represent
a fraction of the pulse interval that will be devoted to the "on" part of the pulse
(signal value of 1). A value of 0 has the smallest "on" pulse size (usually a single
sample), while a value of 1 has the largest (usually the entire interval except a
single sample). A value of 0.5 makes a pulse with half the time at 1 and half the
time at 0.

In right inlet: Sets the phase of the onset of the "on" portion of the pulse. A value
of 0 places the "on" portion at the beginning of the interval, while other values (up
to 1, which is the same as 0) delay the "on" portion by a fraction of the total inter-
pulse interval.

Information for box attributes common to all objects

Output
bang: Out right outlet: When the "on" portion of the pulse begins, a bang is sent out the right outlet. Using this outlet, you can
use train~ as a signal-synchronized metronome with an interval specifiable as a floating-point (or signal) value. However, there
is an unpredictable delay between the "on" portion of the pulse and the actual output of the bang message, which depends in
part on the current Max scheduler interval. The delay is guaranteed to be a millisecond or less if the scheduler interval is set to 1
millisecond.
signal: Out left outlet: A pulse (square) wave train having the specified interval, width, and phase.

Examples
Provide an accurate pulse for rhythmic changes in signal

See Also
Name Description
<~ Is less than, comparison of two signals
>~ Is greater than, comparison of two signals
clip~ Limit signal amplitude
phasor~ Generate sawtooth signals
trapezoid~
Trapezoidal wavetable

Description
trapezoid~ is a trapezoidal wavetable with signal inputs to change ramp up/down phase position. The default lo/hi points are 0.
and 1., but may be changed using the lo/hi messages.

Arguments
Name Units Type Opt Description
ramp-up float opt A floating-point value can be used to specify the ramp up value. The arguments 0.
0. produce a ramp waveform, and 0.5 0.5 produces a triangle waveform.
ramp-down float opt A floating-point value can be used to specify the ramp down value. The arguments
0. 0. produce a ramp waveform, and 0.5 0.5 produces a triangle waveform.

Messages
float trapezoidal-control [float] In left inlet: Any float or signal or an input signal progressing from 0 to 1 is used to
scan the trapezoid~ object's wavetable. The output of a phasor~ or some other
audio signal can be used to control trapezoid~ as an oscillator, treating the
contents of the wavetable as a repeating waveform.

In middle inlet: The ramp up portion of the trapezoidal waveform, specified as a


fraction of a cycle between 0 and 1.0. The default is .1.

In right inlet: The ramp up portion of the trapezoidal waveform, specified as a


fraction of a cycle between 0 and 1.0. The default is 0.9.
hi maximum-value [float] In left inlet: The word hi, followed by an optional number, sets the maximum
value of trapezoid~ for signal output. The default value is 1.0.
lo minimum-value [float] In left inlet: The word lo, followed by an optional number, sets the minimum
value of trapezoid~ for signal output. The default value is 0.
signal In left inlet: Any float or signal or an input signal progressing from 0 to 1 is used to
scan the trapezoid~ object's wavetable. The output of a phasor~ or some other
audio signal can be used to control trapezoid~ as an oscillator, treating the
contents of the wavetable as a repeating waveform.

In middle inlet: The ramp up portion of the trapezoidal waveform, specified as a


fraction of a cycle between 0 and 1.0. The default is .1.

In right inlet: The ramp up portion of the trapezoidal waveform, specified as a


fraction of a cycle between 0 and 1.0. The default is 0.9.

Information for box attributes common to all objects

Output
signal: A signal which corresponds to the value referenced by the trapezoid~ object's input signal. If the output of a phasor~ or
some other audio signal is used to scan the trapezoid~ object, the output will be a periodic waveform.

Examples
trapezoid~ generates a trapezoidal waveform that lets you specify the phase points at which it changes direction

See Also
Name Description
buffer~ Store audio samples
cos~ Signal cosine function (0-1 range)
phasor~ Generate sawtooth signals
wave~ Variable size wavetable
MSP Tutorial 2: Adjustable MSP Tutorial 2: Adjustable Oscillator
Oscillator
MSP Tutorial 3: Wavetable MSP Tutorial 3: Wavetable Oscillator
Oscillator
tri~
Antialiased triangular oscillator

Description
tri~ generates a triangle wave whose component frequencies are resistant to aliasing.

Arguments
Name Units Type Opt Description
initial-frequency hz number opt The first argument sets the initial frequency of the oscillator. The default is 0.
duty-cycle float opt The second argument sets the duty cycle. The default is 0.5.

Messages
int frequency [int] In left inlet: Sets the frequency of the oscillator.

In middle inlet: Sets the duty cycle of the oscillator. Signal is wrapped into the
range 0-1. A value of 0.5 will produce a triangular wave that spends equal amounts
of time sloping positively and negatively.
float frequency [float] In left inlet: Sets the frequency of the oscillator.

In middle inlet: Sets the duty cycle of the oscillator. Signal is wrapped into the
range 0-1. A value of 0.5 will produce a triangular wave that spends equal amounts
of time sloping positively and negatively.
signal In left inlet: Sets the frequency of the oscillator.

In middle inlet: Sets the duty cycle of the oscillator. Signal is wrapped into the
range 0-1. A value of 0.5 will produce a triangular wave that spends equal amounts
of time sloping positively and negatively.

In right inlet: (optional) A sync signal. When the control signal crosses from below
0.5 to above 0.5, the oscillator resets itself. A phasor~ object works well for this
purpose. The classic use is to "sweep" this control signal in a frequency range
somewhere at least three or four octaves higher than the fundamental frequency.

Information for box attributes common to all objects

Output
signal: An antialiased triangular waveform. An ideal, straight-line triangular wave generated in a computer contains aliased
frequencies that can sound irritating. tri~ produces a nice, analog-esque output waveform.

Examples

Spectral comparison of tri~ and an ideal triangular wave


See Also
Name Description
cycle~ Sinusoidal oscillator
phasor~ Generate sawtooth signals
rect~ Antialiased rectangular (pulse) oscillator
saw~ Antialiased sawtooth oscillator
techno~ Signal-driven step sequencer
triangle~ Triangle/ramp wavetable
MSP Tutorial 3: Wavetable MSP Tutorial 3: Wavetable Oscillator
Oscillator
triangle~
Triangle/ramp wavetable

Description
triangle~ is a triangle/ramp wavetable with signal input to change phase offset of the peak value. The default lo/hi points are -1.
and 1., but may be changed using the lo/hi messages.

Arguments
Name Units Type Opt Description
peak-value-phase- float opt Peak value phase offset, expressed as a fraction of a cycle, from 0 to 1.0. The
offset default is 0.5. A value of 0 produces a ramp waveform when the triangle~ object is
driven by a phasor~, and a value of 1.0 produces a sawtooth waveform.

Messages
float triangular-control [float] In left inlet: Any signal, float, or an input signal progressing from 0 to 1 is used to
scan the triangle~ object's wavetable. The output of a phasor~ or some other
audio signal can be used to control triangle~ as an oscillator, treating the contents
of the wavetable as a repeating waveform.

In right inlet: Peak value phase offset, expressed as a fraction of a cycle, from 0 to
1.0. The default is 0.5. Scanning through the triangle~ object's wavetable using
output of a phasor~ with a phase offset value of 0 produces a ramp waveform, and
a phase offset of 1.0 produces a sawtooth waveform.
signal In left inlet: Any signal, float, or an input signal progressing from 0 to 1 is used to
scan the triangle~ object's wavetable. The output of a phasor~ or some other
audio signal can be used to control triangle~ as an oscillator, treating the contents
of the wavetable as a repeating waveform.

In right inlet: Peak value phase offset, expressed as a fraction of a cycle, from 0 to
1.0. The default is 0.5. Scanning through the triangle~ object's wavetable using
output of a phasor~ with a phase offset value of 0 produces a ramp waveform, and
a phase offset of 1.0 produces a sawtooth waveform.

Attributes
Name Type g/s Description
hi float Sets the maximum value of triangle~ for signal output. The default value is 1.0
lo float Sets the minimum value of triangle~ for signal output. The default value is 1.0

Information for box attributes common to all objects

Output
signal: A signal which corresponds to the value referenced by the triangle~ object's input signal. If the output of a phasor~ or
some other audio signal is used to scan the triangle~ object, the output will be a periodic waveform.

Examples
triangle~ lets you generate ramping waveforms with different reversal points

See Also
Name Description
buffer~ Store audio samples
cos~ Signal cosine function (0-1 range)
phasor~ Generate sawtooth signals
trapezoid~ Trapezoidal wavetable
tri~ Antialiased triangular oscillator
wave~ Variable size wavetable
MSP Tutorial 2: Adjustable MSP Tutorial 2: Adjustable Oscillator
Oscillator
MSP Tutorial 3: Wavetable MSP Tutorial 3: Wavetable Oscillator
Oscillator
trunc~
Truncate fractional signal values

Description
trunc~ converts signals with values such as 1.75 to 1.0. Negative values are modified so that -1.75 becomes -1.0. This object is very
simple but computationally expensive.

Arguments
None.

Messages
signal A signal whose values will be truncated. The trunc~ object converts signals with
fractional values to the nearest lower integer value (e.g., a value of 1.75 is
truncated to 1.0, and -1.75 is truncated to -1.0). This object is simple but
computationally expensive.

Information for box attributes common to all objects

Output
signal: The truncated input signal.

Examples

trunc~ takes floating-point signals and truncated the fractional part

See Also
Name Description
clip~ Limit signal amplitude
round~ Round an input signal value
vectral~
Vector-based envelope follower

Description
Use the vectral~ object to filter frame-based signal data such as the output of the fft~ object.

Arguments
Name Units Type Opt Description
vector-size int opt The argument is the vector size for the operation. It defaults to 512, but should be
set appropriately for the size of the vectors you feed into the vectral~ object.

Messages
clear Clears object's sample memory (in case of a blow-up).
deltaclip low-limit [float] In left inlet: The word deltaclip, followed by two floats, limits the change in bins
high-limit [float] of successive vectors to the values given. This is equivalent to the time-domain
deltaclip~ object.
rampsmooth number-of- In left inlet: The word rampsmooth, followed by two ints, causes the vector to be
interpolating-frames smoothed in a linear fashion across successive frames. The arguments specify the
[list] number of frames to use to interpolate values in both directions. This is equivalent
to the time-domain filtering done by the rampsmooth~ object.
signal In left inlet: Accepts a sync signal for the output index of the vector. This is
typically in the range of 0 to n-1 where n is the size of the vector.

In middle inlet: A sync signal received in the middle inlet is used to synchronize
the input index of the vector being processed. The sync signal will typically be in
the range 0 to n-1 where n is the size of the vector. If the range of the sync signal is
different than the output index, the incoming vector will be "bin-shifted" by the
difference between the two signals.

In right inlet: Signal data to be filtered. This will usually be frequency-domain


information such as the output of an fft~ or fftin~ object.
size vector-size [int] In left inlet: The word size, followed by a number, sets the vector size for the
operation. The default is 512.
slide slide-denominator- In left inlet: The word slide, followed by two floats, causes vectral~ to do
coefficients (2 floats) logarithmic interpolation of successive vectors in a manner equivalent to the time-
[list] domain slide~ object. The two arguments determine the denominator coefficient
for the amount of the slide.

Information for box attributes common to all objects

Output
signal: A smoothed version of the signal input into the right inlet, according to the parameters given to the vectral~ object.

Examples
vectral~ performs different types of smoothing between frames of vectored data (e.g., FFT signals)

See Also
Name Description
cartopol Convert cartesian to polar coordinates
cartopol~ Signal Cartesian to Polar coordinate conversion
deltaclip~ Limit changes in signal amplitude
fft~ Fast Fourier transform
fftin~ Input for a patcher loaded by pfft~
fftinfo~ Report information about a patcher loaded by pfft~
fftout~ Output for a patcher loaded by pfft~
frameaccum~ Compute "running phase" of successive phase deviation frames
framedelta~ Compute phase deviation between successive FFT frames
ifft~ Inverse fast Fourier transform
pfft~ Spectral processing manager for patchers
poltocar Convert polar to cartesian coordinates
poltocar~ Signal Polar to Cartesian coordinate conversion
rampsmooth~ Smooth an incoming signal
slide~ Filter a signal logarithmically
MSP Tutorial 26: Frequency MSP Tutorial 26: Frequency Domain Signal Processing with pfft~
Domain Signal Processing with
pfft~
vst~
Host VST and Audio Unit plug-ins

Description
Use the vst~ object to load a real-time VST or Audio Unit plug-in and use its audio processing in MSP.

Arguments
Name Units Type Opt Description
number-of- int opt If the first or first and second arguments are numbers, they set the number of
inputs/outputs audio inputs and outputs. If there is only one number, it sets the number of
outlets. If there are two numbers, the first one sets the number of inlets and the
second sets the number of outlets.
VST-plugin- symbol opt Sets the name of a VST or Audio Unit plug-in file to load when the object is
filename created. You can load a plug-in after the object is created (or replace the one
currently in use) with the plug message.
preset-effects- symbol opt After the plug-in name, a name containing preset effects for the plug-in can be
name specified. If found, it will be loaded after the plug-in has been loaded.

Messages
int effect-program [int] In left inlet: Changes the effect program of the currently loaded plug-in. The first
program is number 1.
float effect-program [float] In left inlet: Floating point values are converted to int values and used to change
the effect program of the currently loaded plug-in. The first program is number 1.
list plugin-parameter In left inlet: Changes a parameter value in the currently loaded plug-in. The first
[symbol] list element is the parameter number (starting at 1) and the second element is the
setting [float] parameter value. The second number should be a float between 0 and 1, where 0 is
the minimum value of the parameter and 1 is the maximum.
anything plugin-parameter A symbol that names a plug-in parameter followed by a float between 0 and 1 set
[symbol] the value of the parameter.
setting [float]
bypass bypass-flag (0 or The word bypass, followed by a non-zero argument, stops any further processing
nonzero) [int] by the currently loaded plug-in and copies the object's signal input to its signal
output. bypass 0 enables processing for the plug-in.
(drag) When a plug-in file is dragged from the file browser to a vst~ object, the plug-in
will be loaded.
(mouse) Double-clicking on a vst~ object opens the plug-in's edit window.
disable mute-flag (0 or The word disable, followed by a non-zero argument, stops any further processing
nonzero) [int] by the currently loaded plug-in and outputs a zero signal. disable 0 enables
processing for the plug-in.
get parameter-data-query- The word get, followed by a number argument, reports parameter values and
index [int] plug-in information. This is output from the fourth outlet of vst~ as a list with the
said number argument as the first element and the desired information as the
second element. If the number argument is between 1 and the number of
parameters of the currently loaded plug-in (inclusive), the get message outputs
the current parameter value (a float between 0 and 1) of the numbered parameter.
If the argument is 0 nothing is output. If the argument is negative, the get
message outputs a list with the first element specifying the number argument and
the remaining elements specifying the following information:

get -1 the plug-in's number of inputs


get -2 the plug-in's number of outputs
get -3 the plug-in's number of programs (VST) or factory presets (Audio Unit)
get -4 the plug-in's number of parameters
get -5 whether the plug-in's canMono flag is set. This indicates that the plug-in
can be used in either a stereo or mono context
get -6 1 if the plug-in has its own edit window, 0 if it doesn't
get -7 1 if the plug-in is a synth plug-in, 0 if it isn't
get -8 the unique ID of the plug-in as an integer value
get -9 four integer values representing the left, top, right, and bottom
coordinates of the desired rectangle of the plug-in UI edit window
get -10 an integer value representing the initial delay of the plug-in in samples to
allow you to automatically compensate for the plugin's latency in your patch
get -11 the plug-in's number of user preset files (Audio Unit only)
getsubnames In left inlet: When using the vst~ object to host a VST shell plug-in (e.g.,
WaveShell) that is not instantiated with a specific plug-in name, the word
getsubnames causes a list of sub plug-in names to be sent out the seventh outlet
of the vst~ object.
midievent MIDI-message (2 to 4 The word midievent, followed by two to four numbers, sends a MIDI event to the
numbers) [list] plug-in. The first three number arguments are the bytes of the MIDI message. The
fourth, optional, argument is a detune parameter used for MIDI note messages.
The value ranges from -63 to 64 cents, with 0 being the default.
mix mix-mode [list] In left inlet: mix 1 turns mix mode on, in which the plug-in's output is added to
the input. mix 0 turns mix mode off. When mix mode is off, the plug-in's output is
not added to the input. Only the plug-in's output is sent to the vst~ object's signal
outlets.
params The word params causes a list of the plug-in's parameters to be sent out the
fourth-from-right outlet.
pgmnames The word pgmnames causes a list of the plug-in's current program names to be
sent out the right outlet.
plug plug-in-name [symbol] In left inlet: The word plug with no arguments opens a standard open file dialog
allowing you to choose a new VST or Audio Unit plug-in to host. The word plug
followed by a symbol argument searches for plug-in with the specified name in the
Max search path. If a new plug-in is opened and found, the old plug-in (if any) is
discarded and the new one loaded. An optional second argument to the plug
message can be used to specify a plug-in name within a shell plug-in (e.g.,
WaveShell). This can either be a symbolic plug-in name or an associated ID value
as displayed by the printids message).

When the Max application starts up, the system VST folder will be added to the
max search path. On the Macintosh this is generally /Library/Audio/Plug-
ins/VST/ and on windows this is the folder specified in the VstPluginsPath string
value under the registry key HKLM\Software\VST. On Mac OS, Audio Unit plug-
ins will be scanned and .auinfo files for Apple built-in and user-installed plug-ins
will be added to the search path.
presetnames For Audio Unit plug-ins only, the word presetnames causes a list of the plug-in's
user preset filenames to be sent out the right outlet.
open window-coordinates The word open with no arguments opens the plug-in's edit window. If the window
[list] was previously opened then the edit window location will persist. The word open
followed by two integer values specifying the left and top window coordinates
respectively will open or move the plug-in's edit window to the given coordinates.
printids In left inlet: When using the vst~ object to host a VST shell plug-in (e.g.,
WaveShell) that is not instantiated with a specific plug-in name, the word printids
causes a list of sub plug-in IDs to be displayed in the Max window.
read filename [symbol] With no arguments, read opens a standard open file dialog prompting for a file of
effect programs, either in bank or individual program format. read accepts an
optional symbol argument where it looks for a VST plug-in bank or effect program
file in the Max search path.
set effect-program-name In left inlet: The word set, followed by a symbol, changes the name of the current
[symbol] effect program to the symbol.
settitle window-title [symbol] In left inlet: The word settitle, followed by a symbol, changes the title displayed
for the name of the plug-in's edit window.
signal Input to be processed by the plug-in. If the plug-in is an instrument plug-in, the
input will be ignored.
subname plug-in-name [symbol] In left inlet: The word subname, followed by a plug-in name or plug-in ID, will
cause a shell VST plug-in (e.g., WaveShell) to be re-instantiated with the specified
name/ID.
wclose Closes the plug-in's edit window.
write file/pathname [symbol] For VST plug-ins, with no arguments, write opens a standard Save As dialog box
prompting you to choose the name and type of the effect program file (single
program or bank). write accepts an optional symbol argument that specifies a full
or partial destination pathname. An individual program file is written in this case.
For Audio Unit plug-ins, the filename argument is required, and specifies the
name of a user preset that will be written to a standard plug-in user preset
location.
writebank program-bank- With no arguments, writebank opens a standard Save As dialog box prompting
file/pathname [symbol] you to choose the name of the effect program bank file. writebank accepts an
optional symbol argument that specifies a full or partial destination pathname. For
Audio Unit plug-ins, the writebank message is the same as write and saves only
the current settings to a named file.
writepgm inividual-effect- With no arguments, writepgm opens a standard Save As dialog box prompting
program-file/pathname you to choose the name of the individual effect program file. writepgm accepts an
[symbol] optional symbol argument that specifies a full or partial destination pathname. For
Audio Unit plug-ins, the writepgm message is the same as write and saves the
current settings to a named file.

Attributes
Name Type g/s Description
genericeditor int Use a generic editor interface for a plug-in. Note that some Audio Unit plug-ins
def.:0 will not show generic interfaces.

Information for box attributes common to all objects

Output
float: Out fourth outlet: Parameter values or plug-in informational values in response to the get message.
int: Out fourth outlet: Parameter values or plug-in informational values in response to the get message.

Out fifth outlet: Raw MIDI bytes received by the plug-in (but not any MIDI messages received using the midievent message).
list: Out seventh outlet: When a VST shell plug-in (e.g., WaveShell) is instantiated without specifying a plug-in name, a list of
symbols specifying sub plug-in IDs are sent out the seventh outlet in response to the printids message.
signal: Out left outlet (and other signal outlets as defined by the number of outputs argument): Audio output from the plug-in.
The left outlet is the left channel (or channel 1).
symbol: Out third outlet: The plug-in's parameters are sent out as a series of symbols in response to the params message.
Note: Some plug-ins, especially those with their own editors, fail to name the parameters.

Out sixth outlet: A series of symbols are sent out in response to the pgmnames message. If there are no program names, the
message pgmnames: Default is output.

Out seventh outlet: When a VST shell plug-in (e.g., WaveShell) is instantiated without specifying a plug-in name, a series of
symbols specifying plug-in names are sent out the seventh outlet in response to the getsubnames message.

Out eighth outlet: An Audio Unit plug-in's user preset files are sent out as a series of symbols in response to the presetnames
message.

Examples
Process an audio signal with a plug-in

See Also
Name Description
rewire~ Host ReWire devices
wave~
Variable size wavetable

Description
wave~ reads from a portion of a buffer~ to produce a repeating waveform, given a signal input that goes between 0 and 1 (for
example, using a phasor~) to define the position in the buffer.

Arguments
Name Units Type Opt Description
buffer-name symbol Obligatory. Names the buffer~ object whose sample memory is used by wave~ for
its stored waveform. Note that if the underlying data in a buffer~ changes, the
signal output of wave~ will change, since it does not copy the sample data in a
buffer~. wave~ always uses the first channel of a multi-channel buffer~.
start-point ms number opt After the buffer~ name argument, you can type in a value for the start and end
points of the waveform as millisecond offset from the beginning of a buffer~
object's sample memory. By default, the start point is 0. If you want to set a non-
zero start point but retain the sample end as the waveform end point, use only a
single typed-in argument after the buffer~ name. The wave~ object uses the
buffer~ sampling rate to determine loop points. If a signal is connected to the
start point (middle) inlet, the initial waveform start point argument is ignored.
end-point ms number opt After the start point argument, you can type in a value for the end point of the
waveform, as a millisecond offsets from the beginning of a buffer~ object's
sample memory. By default, the end point is the end of the sample. If a signal is
connected to the end point (right) inlet, the initial waveform end point is ignored.
number-of- int opt Sets the number of output channels, which determines the number of outlets that
output-channels the wave~ object will have. The maximum number of signal outputs is 4. If the
buffer~ object being played by wave~ has more channels than the number of
outputs of wave~, the extra channels are not played. If the buffer~ object has
fewer channels, the extra wave~ signal outputs are 0.

Messages
int start/end-point [int] In middle or right inlets: Numbers can be used instead of signal objects to control
the start and end points of the waveform, provided a signal is not connected to
the inlet that receives the number. The wave~ object uses the buffer~ sampling
rate to determine loop points.
float start/end-point [float] In middle or right inlets: Numbers can be used instead of signal objects to control
the start and end points of the waveform, provided a signal is not connected to
the inlet that receives the number. The wave~ object uses the buffer~ sampling
rate to determine loop points.
(mouse) Double-clicking on the wave~ object will open a window that displays the audio
file loaded in the buffer associated with the object.
interp interpolation-mode (0 The word interp, followed by a number in the range 0-2, sets the wavetable
through 2) [int] interpolation mode. The interpolation modes are:

Value- Description

0- No interpolation. Wavetable interpolation is disabled using the interp 0


message.
1- High-quality linear interpolation (default)
2- Low-quality linear interpolation. This mode uses the interpolation method
found in MSP 1.x versions of the wave~ object. While this mode is faster than
mode 1, it cannot play buffer~ objects of arbitrary length and produces more
interpolation artifacts.
set buffer-name [symbol] The word set, followed by a symbol, sets the buffer~ used by wave~ for its stored
start-point (millisecond- waveform. The symbol can optionally be followed by two values setting new
offset) [float] waveform start and end points. If the values are not present, the default start and
end-point (millisecond- end points (the start and end of the sample) are used. If signal objects are
offset) [float] connected to the start and/or end point inlets, the start and/or end point values
are ignored.
signal In left inlet: Input signal values progressing from 0 to 1 are used to scan a
specified range of samples in a buffer~ object. The output of a phasor~ can be
used to control wave~ as an oscillator, treating the range of samples in the
buffer~ as a repeating waveform. However, note that when changing the
frequency of a phasor~ connected to the left inlet of wave~, the perceived pitch of
the signal coming out of wave~ may not correspond exactly to the frequency of
phasor~ itself if the stored waveform contains multiple or partial repetitions of a
waveform. You can invert the phasor~ to play the waveform backwards.

In middle inlet: The start of the waveform as a millisecond offset from the
beginning of a buffer~ object's sample memory.

In right inlet: The end of the waveform as a millisecond offset from the beginning
of a buffer~ object's sample memory.

Information for box attributes common to all objects

Output
signal: The portion of the buffer~ specified by the wave~ object's start and end points is scanned by signal values ranging from
0 to 1 in the wave~ object's inlet, and the corresponding sample value from the buffer~ is sent out the wave~ object's outlet. If
the signal received in wave's inlet is a repeating signal such as a sawtooth wave from a phasor~, the resulting output will be a
waveform (excerpted from the buffer~) repeating at the frequency corresponding to the repetition of the input signal.

Examples

Loop through part of a sample, treating it as a variable-size wavetable

See Also
Name Description
2d.wave~ Two-dimensional wavetable
buffer~ Store audio samples
buffir~ buffer-based FIR filter
groove~ Variable-rate looping sample playback
phasor~ Generate sawtooth signals
play~ Position-based sample playback
sync~ Synchronize MSP with an external source
MSP Tutorial 15: Variable-length MSP Tutorial 15: Variable-length Wavetable
Wavetable
waveform~
buffer~ viewer and editor

Description
Use the waveform~ object to view or edit the contents of a buffer~.

Arguments
None.

Messages
bang A bang in any inlet will cause waveform~ to dump/output the value to which it is
set specific to the inlet in which the bang is received.
int display-settings Converted to float specific to each inlet.
[int]
In left inlet: Sets the display start time in milliseconds. Changing this value will
offset and/or zoom the view, so that the requested time in the buffer~ sample
data is aligned to the left edge of the display. The default is 0 (display starts at the
beginning of the target buffer~).

In 2nd inlet: Sets the display length in milliseconds. The default is the length of
the buffer~.
In 3rd inlet: Sets the start time of the selection range in milliseconds.
In 4th inlet: Sets the end time of the selection range in milliseconds.
float display-settings In left inlet: Sets the display start time in milliseconds. Changing this value will
[float] offset and/or zoom the view, so that the requested time in the buffer~ sample
data is aligned to the left edge of the display. The default is 0 (display starts at the
beginning of the target buffer~).

In 2nd inlet: Sets the display length in milliseconds. The default is the length of
the buffer~.
In 3rd inlet: Sets the start time of the selection range in milliseconds.
In 4th inlet: Sets the end time of the selection range in milliseconds.
list start [float] In 5th inlet: The 5th inlet provides a link input, which allows any number of
length [float] waveform~ objects to share their start, length, select start, and select end values.
select-start Whenever any of these values changes, waveform~ sends them all as a list out its
[float] right outlet. If this outlet is connected to the link input of another waveform~
select-end object, it will be updated as it receives the lists.
[float]
select-start-ms To complete the circuit, the second waveform~ object's list output can be
[int] connected to the link input of the first. Then, changes in either one (via mouse
select-end-ms clicks, etc.) will be reflected in the other. This is mainly useful when the
[int] waveform~ objects are viewing different channels of the same buffer~. Any
number of waveform~ objects can be linked in this fashion, forming one long,
circular chain of links. In this case waveform~ will prevent feedback from
occurring.
crop The crop message will trim the audio data in the target buffer~ to the current
selection. It resizes the buffer~ to the selection length, copies the selected samples
into it, and displays the result at default settings. The buffer~ is erased, except for
the selected range. This is a "destructive edit," and cannot be undone.
bpm master-tempo Specifies beats per minute as the time reference unit, relative to a master tempo
[int] and number of beats per bar, both of which you can set with the bpm message.
beats-per-bar waveform~ can also calculate a tempo that fits your current selection, via the
[int] setbpm message.
(drag) Click and drag behavior for the waveform~ object varies according to the object's
mode of operation (see the setmode attribute).
buftime drawing- The word buftime, followed by a number between 20 and 60000, sets the
interval [int] minimum drawing interval in milliseconds when a waveform~ object is redrawn
due to changes in its associated buffer~ object. Setting a higher number value will
make some difference in CPU utilization. The default value is 500ms.
mode mouse- This is a legacy message - this functionality is now provided by the setmode
response-mode attribute.
(symbol) [list]
(mouse) The way that the waveform~ object responds to clicking and dragging varies
according to how the object is configured using the setmode attribute.
mouseoutput mouse-output- The word mouseoutput, followed by a symbol argument, determines when
mode (symbol) selection start and end values are sent in response to mouse activity. Only the
[list] selection start and end (outlets 3 and 4) are affected. Mouse information is always
sent from outlet 5, regardless of the mouseoutput mode. Valid symbol arguments
are, none, down, up, downup, and continuous.

none- Selection start and end values are not sent in response to mouse activity.
Sending the mouseoutput message with no argument has the same effect as the
same message with the argument none.
down- Causes the current selection start and end values to be sent (from outlets 3
and 4) only when you click inside the waveform~.
up- Causes selection start and end to be sent only when you release the mouse
button, after clicking inside the waveform~.
downup- Causes selection start and end to be sent both when you click inside the
waveform~, and when the mouse button is released.
continuous- Causes selection start and end to be sent on click, release, and
throughout the drag operation, whenever the values change.
line time [list] The word line, followed by a integer or floating point value representing a time in
milliseconds, will cause a vertical line to be superimposed on the waveform display
at the millisecond point indicated by the argument. The purpose of this is to be
able to visually indicate where the playback point of the waveform is at any given
moment. If the argument of line is a negative value, the vertical line will be
hidden.
The word line, followed by a symbol, defines the unit used to display the line. The
options are:

bpm: beats per minute


ms: milliseconds (the default)
phase: phase (range 0. - 1.0)
samples
name filename The word name, followed by a list that contains the name of a file and a channel
[symbol] number, sets waveform~ object to display the channel of that file. This is used for
channel [int] displaying multichannel audio files.
normalize maximum- The word normalize, followed by a float, will scale the sample values in the target
peak-value [list] buffer~ so that the highest peak matches the value given by the argument. This
can cause either amplification or attenuation of the audio, but in either case, every
buffer~ value is scaled, and this activity cannot be undone.
set buffer-name The word set, followed by a symbol or int which is the name of a buffer~ object,
[list] links waveform~ to the target buffer~, which is drawn with default display
values. An optional int argument sets the channel offset, for viewing multi-channel
buffer~ objects. The name of the linked buffer~ is not saved with the Max patch,
so should be stored externally if necessary.
setbpm The word setbpm, with no arguments, causes waveform~ to calculate a tempo
based on the current selection range. It automatically changes the display time
unit to bpm, as if you had sent the message unit bpm. A tempo is selected such
that the selection range constitutes a logical multiple or subdivision of the bar,
preserving the current beats per bar value, and attempting to find the closest value
to the current tempo that satisfies its criteria. When a suitable tempo is selected,
the offset parameter is adjusted so that the start time of the selection range falls
exactly on a bar line.

The result is that the selection area will be framed precisely by a compatible
tempo. One use of this technique is to quickly establish time labels and tick marks
for a section of audio. After selecting a bar as accurately as possible, sending the
setbpm message and turning on snap to label allows immediate quantization of
the selection range to metric values.

If the target buffer~ contains an audio segment that is already cropped to a logical
number of beats or bars, the best technique is to select the entire range of the
buffer~ (with messages to the select start and end inlets), followed by the setbpm
message. If the buffer~ is cropped precisely, the resulting tempo overlay should be
quite accurate, and immediately reveal the tempo along with metric information.

When a new tempo is calculated, it is sent from the rightmost outlet (the link
outlet), to update any linked waveform~ objects, and to be used in whatever
manner required by the surrounding patch.
snap snap-mode The word snap, followed by a symbol argument, Sets the snap mode of the
(symbol) [list] waveform~ selection range. snap causes the start and end points of the selection
to automatically move to specific points in the buffer~, defined by the snap mode.
Possible arguments are none, grid, and zero.

none- Disables snap to allow free selection. This is the default. The snap message
with no argument has the same effect.
grid- Specifies that the selection start and end points should snap to the vertical
grid lines, as set by the grid message. Since the spacing of the grid lines is affected
by the current time measurement unit, and by the offset value (if an offset has
been specified), snap to grid will be affected by these parameters as well.
tick- Causes the selection start and end to snap to the tick divisions specified by
the ticks message.
zero- Instead of snapping the selection to a uniform grid, this mode searches for
zero-crossings of the buffer~ data. These are defined as the points where a
positive sample follows a negative sample, or vice-versa. This can be useful to find
loop and edit points.
replacebuffercontents filename The word replacebuffercontents, followed by a symbol argument, will replace
[symbol] the current contents of the buffer with which the waveform~ object is associated
and display the new buffer contents.
undo This mode works for waveform~ selection only. It causes the selection start and
end points to revert to their immediately previous values. This is helpful when you
are making fine editing adjustments with the mouse and accidentally click in the
wrong place, or otherwise cause the selection to change unintentionally. Repeated
undo commands will toggle between the last two selection states.
unit unit-of- The word unit, followed by a symbol argument, sets the unit of time measurement
measurement used by the display. Valid symbol arguments are ms, samples, phase, and bpm.
(symbol) [list]
ms- Sets the display unit to milliseconds. This is the default.
samples- Causes time values to be shown as sample positions in the target
buffer~. The first sample is numbered 0, unless the display has been shifted by
the offset message.
phase- Causes time to be displayed according to phase within the buffer~,
normalized so that the 0 refers to the first sample, and 1 refers to the last. This
type of measurement unit is especially relevant when working with objects that use
0-1 signal sync, such as phasor~ and wave~.
bpm- Specifies beats per minute as the time reference unit, relative to a master
tempo and number of beats per bar, both of which you can set with the bpm
message. waveform~ can also calculate a tempo that fits your current selection,
via the setbpm message.

Attributes
Name Type g/s Description
attr_bpm float Specifies beats per minute as the time reference unit relative to a master tempo
def.:120. and number of beats per bar, both of which you can set with the bpm message.
waveform~ can also calculate a tempo that fits your current selection, via the
setbpm message.
beats int Toggles the display of time in beat units if the waveform~ object is set to display
def.:4 time in bpm units (set using the setunit attribute). The default is 0 (off).
bgcolor float Sets the background color in RGBA format used to paint the entire object rectangle
before the rest of the display components are drawn on top.
bordercolor float Sets the frame color used to draw the single-pixel frame around the object
rectangle and the label area in RGBA format.
buffername symbol Sets the name of the buffer~ object.
chanoffset int Specifies a given channel in a multi-channel audio file to be displayed. Channel
def.:1 numbering starts at 1, and values must be in the range 1-4.
'1' = TEXT_HERE
'2' = TEXT_HERE
'3' = TEXT_HERE
'4' = TEXT_HERE
clipdraw int When set to 1, will cause values being edited in draw mode to be clipped to the
def.:0 range of the display (as determined by the vzoom message). clipdraw 0 disables
clipping, allowing values to be scaled freely beyond the range of the window. The
default is 0, no clipping.
grid float Specifies that the selection start and end points should snap to the vertical grid
def.:1000. lines, as set by the grid message. Since the spacing of the grid lines is affected by
the current time measurement unit, and by the offset value (if an offset has been
specified), snap to grid will be affected by these parameters as well.
invert int Toggles inverting the colors used for selected and non-selected portions of the
def.:0 waveform~ object's display. The default is 0 (non-inverted).
labelbgcolor float Sets the label background color in RGBA format.
labels int Toggles the display of the numerical labels of time measurement across the top of
def.:1 the display. Any non-zero int causes the labels to be drawn. An argument of 0, or
no argument, disables them.
labeltextcolor float Sets the label text color in RGBA format.
norulerclick int Toggles clicking and dragging in the ruler area of the waveform~ display. The
def.:0 default is enabled.
offset float Causes all labels and time measurement markings to be shifted by a specified
def.:0. number of milliseconds. Snap behavior is shifted as well. offset can be removed
by sending the message offset 0., or the offset message with no argument.
outmode int Determines when selection start and end values are sent in response to mouse
def.:4 activity. Only the selection start and end (outlets 3 and 4) are affected. Mouse
information is always sent from outlet 5, regardless of the selected mode.
none: Selection start and end values are not sent in response to mouse activity.
Sending the outmode message with no argument has the same effect as the same
message with the argument none.
down: Causes the current selection start and end values to be sent (from outlets 3
and 4) only when you click inside the waveform~ object's display.
up: Causes selection start and end to be sent only when you release the mouse
button, after clicking inside the waveform~ object's display..
downup: Causes selection start and end to be sent both when you click inside the
waveform~ object's display., and when the mouse button is released.
continuous: Causes selection start and end to be sent on click, release, and
throughout the drag operation, whenever the values change.
quiet int Toggles outputting values from the waveform~ object while dragging. The default
def.:0 is 0 (send values while dragging) inverting the colors used for selected and non-
selected portions of the waveform~ object's display. The default is 0 (output data
while dragging).
selectalpha float This attribute is used to import older patches that contain waveform~ objects.
def.:0.5 Previously, the selection rectangle is painted using two legacy messages (rgb2 and
rgb7) and a "blend" transfer mode. Max 5 uses the alpha channel to set the
selection color, and will automatically apply this attribute to older version patches
containing this object. rectangle.
selectioncolor float Sets the selection rectangle color which identifies the selection range in RGBA
format.
setmode int Determines how the waveform~ object responds to mouse activity.
def.:0 'None' = Set display only mode
'Select' = Set default display mode
'Loop' = Set loop display mode
'Move' = Set move display mode
'Draw' = Set draw display mode
setunit int Sets the unit of time measurement used by the display.
def.:0 'Millisecond' = Set timing to milliseconds
'Samples' = Set timing to sample position in the buffer~
'Phase' = Set timing to phase within the buffer~
'BPM' = Set timing to beats per minute
snapto int Sets the snap mode of the waveform~ selection range. snap causes the start and
def.:0 end points of the selection to automatically move to specific points in the buffer~,
defined by the snap mode.
'Nothing' = Disable snap
'Grid' = Snap start and end point to vertical grid lines
'Zero Crossing' = TEXT_HERE
tickmarkcolor float Sets the frame color used to draw the tickmarks and measurement lines in RGBA
format (if enabled).
ticks int Specifies the number of ticks that should be drawn between each grid line. The
def.:0 default is eight. An argument of 0, or no argument, disables the tick marks.
vlabels int Toggles the drawing of vertical axis labels along the rightmost edge of the
def.:0 waveform~ display. Any non-zero number causes the labels to be drawn. An
argument of 0, or no argument, disables them.
voffset float Sets the vertical offset of the waveform~ display. A value of 0. places the x-axis in
def.:0. the middle, which is the default.
vticks int Disables or enables display of the vertical axis tick marks along the left and right
def.:1 edges of the waveform~ display. Any non-zero int causes the tick marks to be
drawn. An argument of 0, or no argument, disables them.
vzoom float Sets the vertical scaling of the waveform~ display.
def.:1.
waveformcolor float Sets the foreground color in RGBA format used to draw the buffer~ data as a
waveform graph.
zoom_orientation int Change the zoom orientation depending on mouse direction.
def.:0 'Up' = Zoom when mouse is moved up
'Down' = Zoom when mouse is moved down

Information for box attributes common to all objects

Output
float: Out 1st outlet: The display start time of the waveform in milliseconds.

Out 2nd outlet: The display length in milliseconds.

Out 3rd outlet: The start time of the selection range in milliseconds.
Out 4th outlet: The end time of the selection range in milliseconds.
list: Out 5th outlet: This is the mouse outlet, which sends information about mouse click/drag/release cycles that are initiated by
clicking within the waveform~ object. The list contains three numbers.

The first number is a float specifying the horizontal (x) position of the mouse, in 0-1 scale units relative to the waveform~ object.
x is always 0 at the left edge of the waveform~, and 1. at the right edge.

The second number in the list is the floating-point y value of the mouse, scaled to match the buffer~ values. With the default
vzoom = 1. and voffset = 0., the top of the waveform~ gives a y value of 1, and the bottom is -1.

Finally, the third number in the list is an int that indicates which portion of the mouse event is currently taking place. On mouse
down, or click, this value is 1. During the drag, it is 2, and on mouse up it is 3. These can be helpful when creating custom
responses to mouse clicks. Note that a drag (2) message is sent immediately after the mouse down (1) message, whether the
mouse has moved or not, to indicate that the drag segment has begun.

Out 6th outlet: waveform~ outputs a list containing its display start time, display length, selection start time, and selection end
time, whenever one of these values changes (by mouse activity, float input, etc.). See the link input information above for more
information.

Examples

waveform~ lets you view, select, and edit sample data from a buffer~ object

See Also
Name Description
buffer~ Store audio samples
groove~ Variable-rate looping sample playback
zerox~
Detect zero crossings

Description
zerox~ functions as a zero-crossing counter or transient detector.

Arguments
Name Units Type Opt Description
click-volume float opt Sets the output volume for the click sent out the right outlet. Volume values are in
the range 0.0-1.0. The default value is 1.0.

Messages
set output-volume (0.0 through In left inlet: The word set, followed by a floating-point number in the range 0.0-
1.0) [float] 1.0, sets the volume of the click (impulse) sent out the right outlet. The default
value is 1.0.
signal In left inlet: A signal to be analyzed.

Information for box attributes common to all objects

Output
signal: Out left outlet: A signal whose value corresponds to the number of zero-crossings per signal vector which were detected
during the period of the last signal vector.

Out right outlet: A click (impulse) whose volume is set by argument or by the set message is sent out the right outlet whenever a
zero-crossing is detected.

Examples

Use zerox~ to count zero-crossings on an input signal

See Also
Name Description
change~ Report signal direction
edge~ Detect logical signal transitions
spike~ Report intervals of zero to non-zero transitions
zigzag~
Linked list function editor

Description
Use zigzag~ to generate multisegment linear ramps. This object is similar to line~, but retains information about the ramp after it has
been output, and allows modification of the list values for the ramp.

Arguments
Name Units Type Opt Description
initial-value int or float opt Sets an initial value (y) for the zigzag~ object.

Messages
bang In left inlet: The zigzag~ object responds to a bang message according to its mode of
behavior, which is set using the mode message.

If the zigzag~ object is set to mode 0 or mode 1, a bang message will cause the
zigzag~ object to go to the start point (or end point if the direction is negative) and
begin outputting values from there.

If the zigzag~ object is set to mode 2, a bang message will cause the zigzag~ object
to jump to the next index in the list (or the previous index, if the current direction is
negative) and begin outputting values from there.
int output-rate-coefficient [int] In left inlet: Converted to float.

In right inlet: Specifies the rate at which the value and time pairs will be output. A
value of 1.0 traverses the list forward at normal speed. A playback rate of -1 traverses
the list backwards (i.e. in reverse). A value of .5 traverses the linked list at half the
normal speed (effectively doubling the delay time values).

(In left inlet: Converted to float.)


float output-rate-coefficient In left inlet: Each element in the zigzag~ object's linked list is a pair that consists of a
[number] target value (y), followed by a second number that specifies a total amount of time in
milliseconds (delta-x). In that amount of time, numbers are output regularly in a line
from the current index value to the target value. The list 0 0 3.5 500 10 1000
describes a line which begins with a value of 0 at time 0, rises to a value of 3.5 a half
second later, and rises again to a value of 10 in 1 second.

In right inlet: Specifies the rate at which the value and time pairs will be output. A
value of 1.0 traverses the list forward at normal speed. A playback rate of -1 traverses
the list backwards (i.e. in reverse). A value of .5 traverses the linked list at half the
normal speed (effectively doubling the delay time values).
list index and event-pair [list] Performs the same function as append (without the word, "append").
append value [number] The word append, followed by a list, will add new event pair(s) to the end of the
transition-time [number] current list.
bangdelta transition-time [number] In left inlet: The word bangdelta, followed by a float or int, specifies the time over
which the transition between values occurs when the zigzag~ object receives a bang.
The default is 0 (i.e., and immediate transition).
bound start-index [int] In left inlet: The word bound, followed by two numbers which specify start and end
end-index [int] indices (where 0 is the first element), sets the start and end points of the zigzag~
object's linked list.
delete index [int/list] In left inlet: The word delete, followed by an int which specifies a position (where 0 is
the first element), will delete the value and time pair associated with that index from
the list. A list can follow the delete message if you want to remove multiple event
pairs from the list. The message delete 0 will remove the current first value and time
pair from the list; the second value and time pair (i.e. the value and time pair at index
1) will now become the first values in the list.
dump In left inlet: The word dump will cause a list consisting of all currently stored value
and time pairs in the form

index value delta-x

to be sent out the zigzag~ object's 3rd outlet.


end end-index [int] In left inlet: The word end, followed by an int which specifies a position (where 0 is
the first element), sets the point at which the zigzag~ object ceases its output when
triggered by a bang.
insert index and event-pair [list] In left inlet: The word insert, followed by an int which specifies a position (where 0 is
the first element) and a list, will insert new event pair(s) before the index specified.
The message insert 0 5 500 will create a new first entry in the linked list (at the 0
index) with a value of 5 and a time of 500 milliseconds.
jump index and transition-time In left inlet: The word jump, followed by an int which specifies a position (where 0 is
[list] the first element), skips to that point in the linked list and begins outputting value and
time pairs from that point. An optional int can be used to specify the time, in
milliseconds, over which the transition to the next value will occur (the default value is
0).
jumpend transition-time [number] In left inlet: The word jumpend causes the zigzag~ object to immediately jump
forward to the last value (y)on the linked list.
jumpstart transition-time [number] In left inlet: The word jumpstart causes the zigzag~ object to immediately jump to
the first value (y)on the linked list and then output the currently selected list or
selected portion of the list.
mode response-mode [int] The word mode, followed by a number in the range 0-3, specifies the way that the
zigzag~ object responds to messages and signal values. The modes of operation are:

mode 0 is the default mode of operation. When the zigzag~ object receives a bang, it
will jump to the start point (or end point if our direction is negative) and begin
outputting values from there. The time value associated with this jump has its length
defined by the bangdelta message. The default value for bangdelta is 0. If a signal is
connected to the left inlet of the zigzag~ object in this mode, the current index of the
list is determined by the signal; any previously set speed, loopmode, start, and end
messages are ignored.

mode 1 behavior for the zigzag~ object is exactly the same as in mode 0 in terms of
the effect of a bang. In mode 1, signal inputs are handled differently. If a signal is
connected to the left inlet of the zigzag~ object in mode 1, the input signal functions
as a trigger signal; when the slope of the input signal changes from non-negative to
negative, the object will be re-triggered as though a bang were received.

mode 2 sets the zigzag~ object to jump to the next index in the list (or the previous
index, if the current direction is negative) and begin outputting values from there. The
time value associated with this jump has its length defined by the bangdelta message.
The default value for bangdelta is 0. If a signal is connected to the left inlet of the
zigzag~ object in mode 2, the input signal functions as a trigger signal; when the
slope of the input signal changes from non-negative to negative, the object will be re-
triggered as though a bang were received.
loopmode looping-enable [int] The word loopmode, followed by 1, turns on looping. loopmode 0 turns off looping.
By default, looping is off. loopmode 2 turns on looping in "pendulum" mode, in
which the value and time pairs are traversed in an alternating forward and reverse
direction. By default, looping is off
next transition-time [number] In left inlet: The word next skips to the next value and time pair in the linked list. An
optional int can be used to specify the time over which the transition to the next value
will occur (the default value is 0).
prev transition-time [number] In left inlet: The word prev skips to the previous value and time pair in the linked list.
An optional int can be used to specify the time over which the transition to the
previous value will occur (the default value is 0).
print In left inlet: The word print causes the current status and contents of the zigzag~
object to be printed out in the Max window. The output consists of the current mode,
loopmode, the start, end, and loop length of the current list, the pendulum state, and
moving value of the object, followed by a listing of each index in the linked list, along
with its y and delta-x values.
setindex index [int] In left inlet: The word setindex, followed by an int which specifies a position (where 0
value [number] is the first element) and a pair of floats, sets the target value (y) and transition time
transition-time [number] amounts (delta-x) for the specified position in the list.
signal In left inlet: The zigzag~ object responds to signal values according to its mode of
behavior, which is set using the mode message.
If the zigzag~ object is set to mode 0, the current index of the list is determined by
the input signal value; any previously set speed, loopmode, start, and end messages
will be ignored.
If a signal is connected to the left inlet of the zigzag~ object in mode 1, the input
signal functions as a trigger signal; when the slope of the input signal changes from
non-negative to negative, the object will be re-triggered as though a bang were
received.
If a signal is connected to the left inlet of the zigzag~ object in mode 2, the input
signal functions as a trigger signal; when the slope of the input signal changes from
non-negative to negative, the object will be re-triggered as though a bang were
received.

In right inlet: A signal value specifies the rate at which the value and time pairs will be
output. A value of 1.0 traverses the list forward at normal speed. A playback rate of -1
traverses the list backwards (i.e. in reverse). A signal value of .5 traverses the linked list
at half the normal speed (effectively doubling the delay time values). The value of the
input signal is sampled once per input vector. Therefore, any periodic frequency
modulation with a period which is greater than the current sample
rate/(2*vector_size) will alias.
skip number-of-skipped-indices In left inlet: The word skip, followed by a positive or negative number, will skip the
and transition-time [list] specified number of indices in the zigzag~ object's linked list. Positive number values
skip forward, and negative values skip backward. An optional integer can be used to
specify the time over which the transition to the next or previous value will occur (the
default value is 0).
speed output-rate [number] In left inlet: The word speed, followed by a positive or negative floating-point
number, specifies the rate at which the value and time pairs will be output. The
message speed 1.0 traverses the list forward at normal speed, speed -1 traverses the
list backwards, speed .5 traverses the linked list at half the normal speed (effectively
doubling the delay time values).
start start-index [number] In left inlet: The word start, followed by an int which specifies a position (where 0 is
the first element), sets the point at which the zigzag~ object begins its output when
triggered by a bang.
ramptime transition-time [number] In left inlet: The word ramptime, followed by a number, sets the ramp time, in
milliseconds, at which the output signal will arrive at the target value.

Information for box attributes common to all objects

Output
bang: Out right outlet: When looping, a bang message is sent out when the loop (re-trigger) point is reached. A bang is also sent out
when zigzag~ has finished generating all of its ramps.
list: Out 3rd outlet: In response to the dump message, a list consisting of all currently stored value and time pairs in the form

index value (y) delta-x

is output.
signal: Out 1st outlet: The current target value, or a ramp moving toward the target value according to the currently stored value and
the target time.

Out 2nd outlet: The current index.

Examples
zigzag~ can be used as a multi-purpose, editable ramp generator

See Also
Name Description
adsr~ ADSR envelope generator
curve~ Exponential ramp generator
kink~ Distort a sawtooth waveform
line~ Linear ramp generator
zplane~
Graph filter poles and zeros on the Z-plane

Description
The zplane~ object provides a way to graph filter poles and zeros in the Z-plane for display. Use the zplane~ object in
conjunction with the filtergraph~ object, or provide it with a list of biquad~ coefficients.

Arguments
None.

Messages
bang Causes the current pole and zero values to be re-output.
float biquad-filter-coefficients In 1st-5th inlets: A float in one of the first five inlets changes the current value of
[float] the corresponding biquad~ filter coefficients (a0, a1, a2, b1, and b2, respectively),
recalculates and displays the filter's pole-zero graph on the Z-plane and causes a
lists of poles and zeros be output.
(inlet1) coefficient value [float] In 2nd inlet: Sets the current value of the biquad~ filter's a1 coefficient.
(inlet2) coefficient value [float] In 3rd inlet: Sets the current value of the biquad~ filter's a2 coefficient.
(inlet3) coefficient value [float] In 4th inlet: Sets the current value of the biquad~ filter's b1 coefficient.
(inlet4) coefficient value [float] In 5th inlet: Sets the current value of the biquad~ filter's b2 coefficient.
list a0 [float] In left inlet: A list of five float values which correspond to biquad~ filter
a1 [float] coefficients sets the zplane~ object's internal values for these coefficients and
a2 [float] causes the object to visually display the poles and zeros for the filter(s) and to
b1 [float] output the pole and zero data.
b2 [float]
If more than five values are sent, they are interpreted as sets of cascaded biquad
coefficients. The zplane~ object will display a composite pole-zero graph which
shows the multiplication of a group of biquad filters in cascade. Up to 24 groups of
five float values may be cascaded.
dictionary dictionary-name [symbol] The word dictionary, followed by a symbol that references a named filterdesign
object dictionary (set via the name attribute), will cause the zplane~ object to use
the dictionary values for filter coefficients.
(mouse) You can change the filter parameters by clicking and dragging on the zplane~
objects display. Clicking and dragging on any of the poles (shown as an x in the
display) or zeros (shown as an o in the display) will modify the filter coefficients
and output the new filter coefficient values.
logscale logscale-flag [int] The word logscale, followed by a zero or one, toggles between linear (the default)
and log frequency display.
order number-of-poles/zeros The word order, followed by an even number between 2 and 24, sets the number
[int] of poles and zeros.
range visual scaling amount [float] The word range, followed by a floating point value, changes the visual scaling of
the zplane~ object's display. The default is 1.5.

Attributes
Name Type g/s Description
axiscolor float Sets the X and Y axis color of the zplane~ object in RGBA format.
bgcolor float Sets the background color of the zplane~ object in RGBA format.
bordercolor float Sets the object border color of the zplane~ object in RGBA format.in RGBA
format.
circlebordercolor float Sets the Unit Circle border color of the zplane~ object in RGBA format.
fgcolor float Sets the foreground (unit circle) color of the zplane~ object in RGBA format.
gridlinecolor float Sets the grid line color of the zplane~ object in RGBA format.
hlcolor float Sets the idle mousing highlight color of the zplane~ object in RGBA format.
pconstrain int When set to 1, poles will be constrained inside the unit circle, and thus yield a
def.:0 stable filter. An argument of zero will turn this feature off (the default).
polezerocolor float Sets the Pole and Zero color of the zplane~ object in RGBA format.
rounded int Sets the roundness, in pixels, of the zplane~ object box.
def.:8

Information for box attributes common to all objects

Output
list: Out left outlet: a list of 5 floating-point filter coefficients for the biquad~ object. Coefficients output in response to mouse
clicks and changes in the coefficient inlets.

Out second outlet: a list of "zero" location values expressed as complex numbers (real, imaginary). These correspond to the "a"
coefficients of the filter. A 2nd order (biquad) filter will have 2 zeros, a 4th order filter will have four, etc...

Out third outlet: a list of "pole" location values expressed as complex numbers (real, imaginary). These correspond to the "b"
coefficients of the filter. A 2nd order (biquad) filter will have 2 zeros, a 4th order filter will have four, etc...

Out fourth outlet: a list of floating-point values representing the overall gain of each cascaded filter.

Examples

See Also
Name Description
biquad~ Two-pole, two-zero filter
cascade~ Cascaded series of biquad filters
filtercoeff~ Signal-rate filter coefficient generator
filtergraph~ Edit a filter interactively
Audio Filtering Audio Filtering
Jitter Reference
jit.3m
Report min/mean/max values

Description
Reports the minimum, mean, and maximum values for each plane of a given input matrix as lists of size planecount , one value
for each plane. The list of minimum values are sent out the left outlet of the object, the list of mean values are sent out the middle
outlet, and the list of maximum values is sent out the right outlet.

Matrix Operator
matrix inputs:1, matrix outputs:0
Name IOProc Planelink Typelink Dimlink Plane Dim Type

Information for Jitter Matrix Operator (MOP) messages and attributes to this object

Attributes
Name Type g/s Description
max atom (get) Displays the list of maximum values (per plane) calculated from the most recent
input matrix.
mean atom (get) Displays the list of mean values (per plane) calculated from the most recent input
matrix.
min atom (get) Displays the list of minimum values (per plane) calculated from the most recent
input matrix.

Information for box attributes common to all objects

Examples

See Also
Name Description
jit.histogram Calculate matrix histogram
jit.op Apply binary or unary operators
jit.alphablend
Blend two images with an alpha channel image

Description
Accesses the alpha channel (plane 0) of the input matrix in the left inlet as a per-cell crossfade value, and crossfades between the
input matrices in the left and right inlets. In mode 0, a low value means more of the right input matrix, while a high value means
more of the left input matrix. In mode 1, a low value means more of the left input matrix, while a high value means more of the
right input matrix.

Matrix Operator
matrix inputs:2, matrix outputs:1
Name IOProc Planelink Typelink Dimlink Plane Dim Type
in2 resamp 1 1 1 1 1 char float32 float64
out n/a 1 1 1 1 1 char float32 float64

Information for Jitter Matrix Operator (MOP) messages and attributes to this object

Attributes
Name Type g/s Description
mode int Crossfade mode (default = 0 (left to right))
0 = crossfade right to left
1 = crossfade left to right
'Left-to-Right' = TEXT_HERE
'Right-to-Left' = TEXT_HERE

Information for box attributes common to all objects

Examples

See Also
Name Description
jit.op Apply binary or unary operators
jit.pack Make a multiplane matrix out of single plane matrices
jit.unpack Make multiple single plane matrices out of a multiplane matrix
jit.xfade Crossfade between 2 matrices
Tutorial 29: Using the Alpha Tutorial 29: Using the Alpha Channel
Channel
jit.altern
Color screen with threshold

Description
Overlays a color screen onto incoming matrices. The original matrix values are revealed through "gaps" in the screen.

Matrix Operator
matrix inputs:1, matrix outputs:1
Name IOProc Planelink Typelink Dimlink Plane Dim Type
out n/a 1 1 1 1 1 char long float32 float64

Information for Jitter Matrix Operator (MOP) messages and attributes to this object

Attributes
Name Type g/s Description
bgcolor float The overlaid screen color alpha red green blue (default = 0. 0. 0. 0.) All values are
in the range 0.-1.
colwidth int The width of the vertical band "gaps" in the screen. (default = 1)
ignore_zero int Alpha channel mode (default = 0 (include alpha channel))
0 = Luminance calculation includes the alpha channel
1 = Plane 0 is ignored and the luminance threshold calculation uses the RGB value
rowheight int The height of the horizontal band "gaps" in the screen. (default = 1)
thresh float The luminance threshold as an average of plane values (default = 0.) Input matrix
values above this threshold are displayed as a grid of rectangular "gaps" between
the overlaid horizontal and vertical screen stripes. Values below the threshold are
displayed using the color specified by the bgcolor attribute.
xinterval int The spacing of "gaps" in the screen along the horizontal axis. (default = 1)
yinterval int The spacing of "gaps" in the screen along the vertical axis. (default = 1)

Information for box attributes common to all objects

Examples
See Also
Name Description
jit.eclipse Create images from images
jit.hatch Perform crosshatch filtering
jit.multiplex Multiplex (interleave) two matrices into one matrix
jit.ameba
Downsample/upsample with non-obvious results

Description
Matrix Operator
matrix inputs:1, matrix outputs:1
Name IOProc Planelink Typelink Dimlink Plane Dim Type
out n/a 1 1 1 4 1 char

Information for Jitter Matrix Operator (MOP) messages and attributes to this object

Attributes
Name Type g/s Description
gain float The overall gain scaling factor (default = 1.)
mode int Color handling mode (default = 0 (wrap))
0 = wrap: Values that exceed the limits are wrapped around to the opposite limit
with a modulo operation. (256 wraps to 0, 257 wraps to 1, and -1 wraps to 255, -2
wraps to 254, etc.)
1 = clip: Values are limited not to exceed min or max. (E.g. numbers greater than
255 are set to 255, and numbers less than 0 are set to 0.)
2 = fold: Values that exceed the limits are folded back in the opposite direction.
(256 is folded back to 254, 257 is folded back to 253, and -1 is folded back to 1, -2
to 2, etc.)
x int The number of cells used for horizontal quantization (default = 1)
y int The number of cells used for vertical quantization (default = 1)

Information for box attributes common to all objects

Examples

See Also
Name Description
jit.matrix The Jitter Matrix!
jit.op Apply binary or unary operators
jit.plur Peace Love Unity Rave
jit.anim.drive
Animate a 3D transform

Description
Animates relative transforms over time with easing. The jit.anim.drive object works in conjunction with jit.anim.node and
OpenGL objects to perform this function. Double clicking the object will open a ui mapping dictionary, allowing certain user
interface actions to be mapped to animation messages.

Messages
bang Causes the animation messages to be output, if currently animating.
anim_reset Disable all animations
(mouse) Mouse events
dictionary Dictionary input to set the ui mapping
grow x [float] Scale the attached object along each axis by the amount provided. The axis
y [float] arguments are multiplied by speed.
z [float]
move x [float] Move the attached object along the axis provided, relative to the space indicated by
y [float] the objects's movemode attribute. The axis arguments are multiplied by speed.
z [float]
moveto x [float] Move the attached object to the specified position over the specified length of time
y [float] (in seconds). Easing in and out is applied to the movement based on the easefunc
z [float] attribute.
duration [float]
scaleto x [float] Scale the attached object to the specified scale value over the specified length of
y [float] time (in seconds). Easing in and out is applied to the scaling based on the easefunc
z [float] attribute.
duration [float]
springto x [float] Move the attached object to the specified position using a mass-spring simulation.
y [float]
z [float]
rotateto x [float] Rotate the attached object to the specified quaternion orientation over the
y [float] specified length of time (in seconds). Easing in and out is applied to the rotation
z [float] based on the easefunc attribute.
w [float]
duration [float]
ui_dict TEXT_HERE
ui_key key [symbol] Send the specified key. If the key is in the ui mapping dictionary, the
corresponding animation will be enabled.
ui_keyup key [symbol] Send the specified keyup. If the key is in the ui mapping dictionary, the
corresponding animation will be disabled.
ui_mouse screen-x [int] Send the mouse event. If the event is in the ui mapping dictionary, the
screen-y [int] corresponding animation will be enabled.
mouse-down [int]
update_drive TEXT_HERE
turn x [float] Rotate the attached object along each axis by the amount provided, relative to the
y [float] space indicated by the turnmode attribute. The axis arguments are multiplied by
z [float] speed.

Attributes
Name Type g/s Description
active int (get) Indicates if the object is currently animating.
automatic int Enables automatic update messages (default = 1). Requires the targetname object
to belong to a valid OpenGL context.
drawto symbol Assign to the named drawing context, allowing for updates to be received
automatically.
ease float Set both easein and easeout attributes (default = 1.).
easefunc symbol Determines how the easing is applied (default = linear).
'linear' = TEXT_HERE
'quadratic' = TEXT_HERE
'cubic' = TEXT_HERE
easein float Determines how long it will take (in seconds) for a specific animation message to
go from it's current value to the new value. (default = 1.)
easeout float Determines how long it will take (in seconds) for a specific animation message to
go from it's current value to 0. (default = 1.)
position float The current stored position in 3D space. This attribute is used for the moveto and
springto messages (default = 0 0 0).
quat float The current orientation in 3D space, stored as a quaternion value. This attribute is
used for the rotateto message (default = 0 0 0 1).
scale float The current stored scale in 3D space. This attribute is used for the scaleto
message (default = 1 1 1).
speed float The speed of animations in units per second. (default = 30.)
spring_damp float The dampening amount applied to the spring equation used in the springto
message (default = 0.1).
spring_mass float The mass amount applied to the spring equation used in the springto message
(default = 1.).
spring_stiff float The stiffness amount applied to the spring equation used in the springto message
(default = 0.2).
spring_thresh float The threshold value to determine when the spring simulation is no longer active.
Used in the springto message (default = 0.0001).
targetname symbol The name of the target object that should be either an OpenGL object, or a
jit.anim.node object.
ui_listen int Cause UI mouse and keyboard messages to be received from context window
(default = 0). Requires the targetname object to belong to a valid OpenGL context.
ui_map symbol Replace the current ui mapping with the named dictionary.
ui_priority int TEXT_HERE

Information for box attributes common to all objects

Examples
Animate a 3D transform

See Also
Name Description
jit.anim.node Perform hierarchical transformation
jit.anim.path Evaluate a path of 3D transform points
jit.gl.camera Set a rendering view
jit.anim.node
Perform hierarchical transformation

Description
The jit.anim.node object represents a transformation (position, orientation and scale) in 3D space. OpenGL objects bind to a
jit.anim.node and receive position, rotate, and scale attributes. In addition, parent-child relationships can be established in a
hierarchical transformation structure, where child jit.anim.node objects are transformed relative to their parents.

Messages
bang Output the current world transform coordinates, which is a concatenation of the
local transform with the parent transform.
anim_grow x [float] Scale the node along each axis by the amount provided.
y [float]
z [float]
anim_move x [float] Move the node along the axis provided, relative to the space indicated by
y [float] movemode.
z [float]
anim_reset Reset the local transformation attributes to their default values (position = 0 0 0,
rotatexyz = 0 0 0, and scale = 1 1 1)
anim_turn x [float] Rotate the node along each axis by the amount provided, relative to the space
y [float] indicated by turnmode.
z [float]
concat Concatenate (multiply) the current transform with the passed in 4x4 matrix. Local
transform attributes are updated after the operation.
grow x [float] See the anim_grow listing
y [float]
z [float]
localtoworld x [float] Retrieve the world-space position from passed in local coordinates. The local
y [float] coordinates are relative to the current world-space transform.
z [float]
localtoworld_quat x [float] Retrieve the world-space quaternion from passed in local quaternion. The
y [float] returned quaternion is the product of to the current world-space quaternion and
z [float] the local quaternion.
w [float]
move x [float] See the anim_move listing
y [float]
z [float]
reset See the anim_reset listing
update_node See the bang listing
turn x [float] See the anim_turn listing
y [float]
z [float]
worldtolocal x [float] Retrieve the local-space position from passed in world coordinates. The local
y [float] coordinates are relative to the current world-space transform.
z [float]
worldtolocal_quat x [float] Retrieve the local quaternion from passed in world quaternion. The returned
y [float] quaternion is the product of to the current inverse world-space quaternion and the
z [float] world quaternion.
w [float]

Attributes
Name Type g/s Description
anchor float Adjust the node anchor (pivot) position (default = 0 0 0). This is the position
around which the node will rotate.
anim symbol Parent anim_node name
animmode symbol Set both turnmode and movemode attributes (default = parent).
'local' = transform relative to local axis
'parent' = transform relative to parent axis
'world' = transform relative to world axis
automatic int Enable automatic updates from draw context (default = 1).
direction float One way to set the orientation. The node will orient so that it's local Z axis will
align with the axis provided. (default = 0 0 1)
inherit_position int Enable inheriting of position values from the parent node (default = 1).
inherit_rotate int Enable inheriting of rotation values from the parent node (default = 1).
inherit_scale int Enable inheriting of scale values from the parent node (default = 1).
invtransform float (get) Retrieve the inverse world transform
locklook int Force the node to remain pointed at the lookat value, ignoring orientation
messages and attributes (default = 0).
lockplane int Cause translation values of the specified plane to be set to zero for move message
(default = 0).
'none' = TEXT_HERE
'x-plane' = TEXT_HERE
'y-plane' = TEXT_HERE
'z-plane' = TEXT_HERE
lookat float One way to set the orientation. The node will orient so that it's local Z points to the
3D position provided. (default = 0 0 0)
movemode symbol Determines which space the move message will affect the position of this node
(default = parent).
'local' = move relative to local axis
'parent' = Move relative to parent axis
'world' = Move relative to world axis
name symbol The instance name. Ob3ds can set their anim attribute to this value to bind to this
node.
parentpos float Set by the node named by the parent attribute. Specifies a position in 3D space
that will be concatenated with the local position to derive the world position.
(default = 0 0 0)
parentquat float Set by the node named by the parent attribute. Specifies a quaternion orientation
that will be concatenated with the local orientation to derive the world orientation.
(default = 0 0 0 1)
parentrot float Set by the node named by the parent attribute. Specifies an angle-axis orientation
that will be concatenated with the local orientation to derive the world orientation.
(default = 0 0 0 1)
parentscale float Set by the node named by the parent attribute. Specifies a scale value that will be
concatenated with the local scale to derive the world scale. (default = 1 1 1)
position float Specifies a position in 3D space. This position is relative to the position provided
by the parent node. (default = 0 0 0)
quat float Specifies a quaternion orientation in 3D space. This orientation is relative to the
orientation provided by the parent node. (default = 0 0 0 1)
rotate float Specifies an angle-axis orientation in 3D space. This orientation is relative to the
orientation provided by the parent node. (default = 0 0 0 1)
rotatexyz float Specifies an Euler orientation in 3D space. This orientation is relative to the
orientation provided by the parent node. (default = 0 0 0)
scale float The local 3D scaling factor in the form x y z (default = 1. 1. 1.)
transform float Get and set the full local 4x4 matrix transformation.
tripod int Force the node to orient itself as if mounted on a tripod. Y-axis turn values are
applied in world-space regardless of turnmode (default = 0).
turnmode symbol Determines which space the turn message will affect the orientation of this node
(default = parent).
'local' = Rotate relative to local axis
'parent' = Rotate relative to parent axis
'world' = Rotate relative to world axis
worlddir float (get) Retrieve the worldspace direction vector.
worldpos float (get) A position in 3D space that is derived from the local position and parent position.
(default = 0 0 0)
worldquat float (get) An orientation in 3D space that is derived from the local orientation and the
parent orientation. (default = 0 0 0 1)
worldrot float (get) An orientation in 3D space that is derived from the local orientation and the
parent orientation. (default = 0 0 0 1)
worldscale float (get) A scaling value in 3D space that is derived from the local scale and the parent
scale. (default = 1 1 1)
worldtransform float (get) The full world transformation

Information for box attributes common to all objects

Examples

Perform hierarchical transformation

See Also
Name Description
jit.anim.drive Animate a 3D transform
jit.anim.path Evaluate a path of 3D transform points
jit.gl.camera Set a rendering view
jit.anim.path
Evaluate a path of 3D transform points

Description
Takes a series of 3D transform points and interpolates between them. See the jit.path object for more information on this
interpolation. Each point stores 11 values: a time value, 3 position values, 3 scale values and 4 quaternion rotation values.

Messages
bang Cause the animation to update, if currently active, and the transform messages to
output.
addquat x [float] Add quaternion orientation values to the last point in the path.
y [float]
z [float]
w [float]
addrotate angle [float] Add angle-axis orientation values to the last point in the path. The values are
x [float] converted to a quaternion before adding.
y [float]
z [float]
addrotatexyz x [float] Add euler orientation values to the last point in the path. The values are converted
y [float] to a quaternion before adding.
z [float]
addscale x [float] Add scale values to the last point in the path.
y [float]
z [float]
append time [float] Append point values to the end of the path. If necessary, the path will be resorted
x [float] based on the time value prior to evaluation.
y [float]
z [float]
scale-x [float]
scale-y [float]
scale-z [float]
quat-x [float]
quat-y [float]
quat-z [float]
quat-w [float]
calchandles Calculate the path handles of each point in the path using the Catmull-Rom
method. This will overwrite any previously stored handles.
clear Remove all points from the path
closepath Close the path by adding a point to the end equal to the first point.
eval parameter [float] Evaluate the path using parameter , (between 0. and 1.) and output the
interpolated values.
evallength length-parameter [float] Evaluate the path using the length-parameter (between 0 and pathlength) and
output the interpolated values.
evaltime time [float] Evaluate the path using time (between 0 and duration) and output the
interpolated values.
delete index [int] Delete the point at index .
edit index [int] Edit the point at index
time [float]
x [float]
y [float]
z [float]
scale-x [float]
scale-y [float]
scale-z [float]
quat-x [float]
quat-y [float]
quat-z [float]
quat-w [float]
edithandle index [int] Edit the point handle at index .
time [float]
x [float]
y [float]
z [float]
scale-x [float]
scale-y [float]
scale-z [float]
quat-x [float]
quat-y [float]
quat-z [float]
quat-w [float]
gethandle index [int] Get handle values at index and output through the right (dumpout) outlet.
getpoint index [int] Get point values at index and output through the right (dumpout) outlet.
insert index [int] Insert a new point at index
time [float]
x [float]
y [float]
z [float]
scale-x [float]
scale-y [float]
scale-z [float]
quat-x [float]
quat-y [float]
quat-z [float]
quat-w [float]
next Advance the path animation to the next point.
prev Rewind the path animation to the previous point
setquat index [int] Set quaternion orientation values at index
x [float]
y [float]
z [float]
w [float]
setrotate index [int] Set angle-axis orientation orientation values at index
angle [float]
x [float]
y [float]
z [float]
setrotatexyz index [int] Set euler orientation orientation values at index
x [float]
y [float]
z [float]
settime index [int] Set time at index . If necessary, the path will be resorted prior to evaluation.
setscale index [int] Set scale values at index
x [float]
y [float]
z [float]
sorttime Sort path based on time values
start Start path animation
stop Stop path animation

Attributes
Name Type g/s Description
autohandles int Enable the calculation of handle values every time the path is edited (default = 1).
automatic int Enable automatic animation notifications from the attached render context
(default = 1).
closed int (get) Indicates the path is closed (first and last points are equal).
drawpath symbol Name of a jit.gl.path object used to draw this path.
drawto symbol Assign to the named drawing context, allowing for updates to be received
automatically.
duration float (get) Path duration in seconds (default = 0.)
endreport int Enable animation end reporting (default = 0). The symbol endnotify is sent out
the dumpout when the animation ends. Only valid if loop = 0.
evalquat int Output evaluated quaternion values (default = 0). Adding orientation values to the
path enables.
evalscale int Output evaluated scale values (default = 0). Adding scale values to the path
enables.
interpmode symbol Path interpolation method (default = linear).
'linear' = Linear interpolation
'spline' = Hermite interpolation
length float (get) Path length (default = 0.)
loop int Path animation loop method (default = 1).
'off' = TEXT_HERE
'on' = TEXT_HERE
'palindrome' = TEXT_HERE
loopreport int Enable animation loop reporting (default = 0). The symbol loopnotify is sent out
the dumpout when the animation loops. Only valid if loop is not 0.
play int Enable path animation (default = 0).
pointcount int (get) Number of path points (default = 0).
position float (get) Current path position (default = 0. 0. 0.).
quat float (get) Current path quaternion orientation (default = 0. 0. 0. 1.)
rate float Animation rate value (default = 1.)
scale float (get) Current path scale value (default = 1. 1. 1.).
shortestrot int Use the shortest path between rotations (default = 1).
targetname symbol The name of the target object that should be either an OpenGL object, or a
jit.anim.node object.
time float Current path time value (default = 0.)
timemode symbol Determine how time values added to the path (default = relative).
'absolute' = Time value is set to argument
'relative' = Time value is set to argument plus previous time value
ui_priority int TEXT_HERE

Information for box attributes common to all objects

Examples
Evaluate a path of 3D transform points

See Also
Name Description
jit.anim.drive Animate a 3D transform
Evaluate a path of 3D transform points
jit.path Evaluates a series of N-dim points as a path
jit.gl.path Generate and render a path in OpenGL
jit.argb2ayuv
Convert ARGB to AYUV

Description
Converts 4-plane char matrix a 4-plane char ARGB (alpha, red, green, blue) matrix into a 4-plane AYUV (alpha, luminance,
signed chroma blue, signed chroma red) matrix. Unlike UYVY data, AYUV data has an alpha channel and full resolution chroma
data.

Matrix Operator
matrix inputs:1, matrix outputs:1
Name IOProc Planelink Typelink Dimlink Plane Dim Type
out n/a 1 1 0 4 1 char

Information for Jitter Matrix Operator (MOP) messages and attributes to this object

Information for box attributes common to all objects

Examples

See Also
Name Description
jit.argb2uyvy Convert ARGB to UYVY
jit.ayuv2argb Convert AYUV to ARGB
jit.colorspace Convert between colorspaces
jit.rgb2luma Converts RGB to monochrome (luminance)
jit.traffic Multiply the planar vector by a matrix
jit.argb2grgb
Convert ARGB to GRGB

Description
Converts a 4-plane char ARGB (alpha, red, green, blue) matrix into a 4-plane char GRGB (green left, red, green right, blue)
matrix. Alpha channel is lost and horizontal dimension is halved to support this half red and blue chroma, macro pixel output
format. The GRGB format is typically useful for conserving memory and/or bandwidth for continuous tone images with less
expense than colorspace conversion.

Matrix Operator
matrix inputs:1, matrix outputs:1
Name IOProc Planelink Typelink Dimlink Plane Dim Type
out n/a 1 1 0 4 1 char

Information for Jitter Matrix Operator (MOP) messages and attributes to this object

Information for box attributes common to all objects

Examples

See Also
Name Description
jit.argb2uyvy Convert ARGB to UYVY
jit.grgb2argb Convert GRGB to ARGB
jit.colorspace Convert between colorspaces
jit.rgb2luma Converts RGB to monochrome (luminance)
jit.traffic Multiply the planar vector by a matrix
jit.argb2uyvy
Convert ARGB to UYVY

Description
Converts a 4-plane char ARGB (alpha, red, green, blue) matrix into a 4-plane char UYVY (signed chroma blue, luminance left,
signed chroma red, luminance right) matrix. Alpha channel is lost and horizontal dimension is halved to support this half chroma,
macro pixel output format. The UYVY format is typically useful for efficiently transferring chroma reduced codecs to the GPU
without the expense of colorspace conversion, or bandwidth requirements of a full chroma format.

Matrix Operator
matrix inputs:1, matrix outputs:1
Name IOProc Planelink Typelink Dimlink Plane Dim Type
out n/a 1 1 0 4 1 char

Information for Jitter Matrix Operator (MOP) messages and attributes to this object

Information for box attributes common to all objects

Examples

See Also
Name Description
jit.argb2ayuv Convert ARGB to AYUV
jit.colorspace Convert between colorspaces
jit.rgb2luma Converts RGB to monochrome (luminance)
jit.traffic Multiply the planar vector by a matrix
jit.uyvy2argb Converts UYVY to ARGB
jit.avc
Control a FireWire VTR

Description
Communicates with FireWire VTR devices, such as digital cameras and DV decks, using the 1394 AV/C protocol. Use it to control
the transport of these devices with messages.

Arguments
None.

Messages
close Closes the AV/C connection. The connection is closed automatically if the object is
deleted, or the patch containing the object is closed.
custom sequence [list] Sends a custom string of data to the DV device. Messages are usually sent as a
sequence of hexadecimal numbers. Accepted messages are documented by the
1394 Trade Association . The relevant specification is the "AV/C Tape
Recorder/Player Subunit".
getdevice Sends the name of the currently active device out the right outlet of the object in
the form device active-device .
gettime Sends the name of the currently active device out the right outlet of the object in
the form time DVdevicemedia-time .
fastwind Fast rewinds the transport.
ff Fast forwards the transport.
gettransport The gettransport message will report the precise state of the transport of the VTR
device to which it is connected out the right outlet of the jit.avc object.
open Opens an AV/C connection to a compatible device if one can be found.
pause Pauses the transport playback.
play command [symbol] Sets playback at normal speed. The following optional arguments are permitted:
pause: Pause in playback.
reverse: Playback at normal speed in reverse.
revpause: Pause in reverse playback.
nextframe: Playback the next sequential frame or field.
prevframe: Playback the previous sequential frame or field.
sf: Playback at the slowest forward special effect speed (sf = slowest, sf6 = slow,
sf1 = fastest)
sf6: Playback at slow forward special effect speed
sf5: Playback at slow forward special effect speed
sf4: Playback at slow forward special effect speed
sf3: Playback at slow forward special effect speed
sf2: Playback at slow forward special effect speed
sf1: Playback at fastest slow forward special effect speed
sr: Playback at the slowest reverse special effect speed (sr = slowest, sr6 = slow,
sr1 = fastest)
sr6: Playback at slow reverse special effect speed
sr5: Playback at slow reverse special effect speed
sr4: Playback at slow reverse special effect speed
sr3: Playback at slow reverse special effect speed
sr2: Playback at slow reverse special effect speed
sr1: Playback at fastest slow reverse special effect speed
ff: Playback at the fastest fast forward special effect speed (ff = fastest, ff6 = fast,
ff1 = slowest)
ff6: Playback at fast forward special effect speed
ff5: Playback at fast forward special effect speed
ff4: Playback at fast forward special effect speed
ff3: Playback at fast forward special effect speed
ff2: Playback at fast forward special effect speed
ff1: Playback at slowest fast forward special effect speed
fr: Playback at the fastest fast reverse special effect speed. (fr = fastest, fr6 = fast,
fr1 = slowest)
fr6: Playback at fast reverse special effect speed
fr5: Playback at fast reverse special effect speed
fr4: Playback at fast reverse special effect speed
fr3: Playback at fast reverse special effect speed
fr2: Playback at fast reverse special effect speed
fr1: Playback at slowest fast reverse special effect speed
record command [symbol] Sets the DV device to record. The following optional arguments are permitted:
recpause: Pause while recording all signal(s)
insertvideo: Replace the video signal with a new signal, but leave any other
signals on the medium intact
insertaudio: Replace the audio signal with a new signal, but leave any other
signals on the medium intact
insertav: Replace the audio and video signals with new signals, but leave any
other signals on the medium intact
insertsubcode: Replace the subcode signal with a new signal, but leave any other
signals on the medium intact
insertvideopause: Pause recording signals, and set the recording mode record
insertvideo
insertaudiopause: Pause recording signals, and set the recording mode record
insertaudio
insertavpause: Pause recording signals, and establish the recording mode record
insertav
insertsubcodepause: Pause recording signals, and set the recording mode
record insertsubcode
recpause Pauses while recording all signal(s).
rewind Rewinds the transport.
stop Halts the transport.
time Causes the attached DV device to seek for the specified time on any loaded media.
Time is specified by four integer arguments that specify hours, minutes, seconds
and frames. Many devices do not support this function.

Information for box attributes common to all objects

Examples
See Also
Name Description
jit.qt.grab Digitize video from an external source
jit.qt.videoout Output video to QuickTime video output component
Tutorial 23: Controlling Your Tutorial 23: Controlling Your FireWire Camera
FireWire Camera
jit.avg4
Average four points

Description
Replaces the values in each cell of an incoming matrix with average values derived from four cells at a specified distance from the
original.

Matrix Operator
matrix inputs:1, matrix outputs:1
Name IOProc Planelink Typelink Dimlink Plane Dim Type
out n/a 1 1 1 1 1 char long float32 float64

Information for Jitter Matrix Operator (MOP) messages and attributes to this object

Attributes
Name Type g/s Description
mode int Boundary handling mode (default = 0 (wrap))
0 = wrap: Values that exceed the limits are wrapped around to the opposite limit
with a modulo operation. (256 wraps to 0, 257 wraps to 1, and -1 wraps to 255, -2
wraps to 254, etc.)
1 = clip: Values are limited not to exceed min or max. (e.g. numbers greater than
255 are set to 255, and numbers less than 0 are set to 0.)
2 = fold: Values that exceed the limits are folded back in the opposite direction.
(256 is folded back to 254, 257 is folded back to 253, and -1 is folded back to 1, -2
to 2, etc.)

'Clip' = TEXT_HERE
'Fold' = TEXT_HERE
'Wrap' = TEXT_HERE
x int The horizontal distance from each incoming cell to the source cells used for
averaging (default = 0)
y int The vertical distance from each incoming cell to the source cells used for averaging
(default = 0)

Information for box attributes common to all objects

Examples
See Also
Name Description
jit.convolve Convolve two matrices
jit.fastblur Blur/sharpen using optimized algorithm
jit.op Apply binary or unary operators
jit.axis2quat
Convert angle-axis to quaternion

Description
Convert an angle-axis representation of an orientation to a quaternion.

Messages
bang Output the resulting quaternion conversion.
list angle [float] A four element list of floating point numbers interpreted as an angle in degrees
x [float] and an axis, is converted to a quaternion and output.
y [float]
z [float]

Attributes
Name Type g/s Description
angleaxis float The angle-axis to be converted. (default = 0 0 0 1)
normalize int Normalize the quaternion before outputting (default = 0).
quat float (get) The resulting quaternion after the conversion.

Information for box attributes common to all objects

Examples

See Also
Name Description
jit.quat Quaternion multiplication
jit.quat2axis Quaternion to angle-axis conversion
jit.quat2euler Quaternion to Euler conversion
jit.euler2quat Convert Euler angles to quaternion
jit.anim.node Perform hierarchical transformation
jit.ayuv2argb
Convert AYUV to ARGB

Description
Converts 4-plane char AYUV (alpha, luminance, signed chroma blue, signed chroma red) matrix into a 4-plane char ARGB (alpha,
red, green, blue) matrix. Unlike UYVY data, AYUV data has an alpha channel and full resolution chroma data.

Matrix Operator
matrix inputs:1, matrix outputs:1
Name IOProc Planelink Typelink Dimlink Plane Dim Type
out n/a 1 1 0 4 1 char

Information for Jitter Matrix Operator (MOP) messages and attributes to this object

Information for box attributes common to all objects

Examples

See Also
Name Description
jit.argb2ayuv Convert ARGB to AYUV
jit.ayuv2uyvy Convert AYUV to UYVY
jit.ayuv2luma Convert AYUV to monochrome (luminance)
jit.colorspace Convert between colorspaces
jit.traffic Multiply the planar vector by a matrix
jit.ayuv2luma
Convert AYUV to monochrome (luminance)

Description
Converts 4-plane char AYUV (alpha, luminance, signed chroma blue, signed chroma red) matrix into into a 1-plane char
monochrome matrix containing the luminosity of the original matrix.

Matrix Operator
matrix inputs:1, matrix outputs:1
Name IOProc Planelink Typelink Dimlink Plane Dim Type
out n/a 0 1 0 1 1 char

Information for Jitter Matrix Operator (MOP) messages and attributes to this object

Information for box attributes common to all objects

Examples

See Also
Name Description
jit.ayuv2uyvy Convert AYUV to UYVY
jit.luma2ayuv Converts monochrome (luminance) to AYUV
jit.colorspace Convert between colorspaces
jit.traffic Multiply the planar vector by a matrix
jit.ayuv2uyvy
Convert AYUV to UYVY

Description
Converts a 4-plane char AYUV (alpha, luminance, signed chroma blue, signed chroma red) matrix into a 4-plane char UYVY
(signed chroma blue, luminance left, signed chroma red, luminance right) matrix. Alpha channel is lost and the horizontal
dimension is halved to account for this half chroma, macro pixel out format.

Matrix Operator
matrix inputs:1, matrix outputs:1
Name IOProc Planelink Typelink Dimlink Plane Dim Type
out n/a 1 1 0 4 1 char

Information for Jitter Matrix Operator (MOP) messages and attributes to this object

Information for box attributes common to all objects

Examples

See Also
Name Description
jit.ayuv2argb Convert AYUV to ARGB
jit.ayuv2luma Convert AYUV to monochrome (luminance)
Convert AYUV to UYVY
jit.colorspace Convert between colorspaces
jit.traffic Multiply the planar vector by a matrix
jit.bfg
Evaluate a procedural basis function graph

Description
Evaluates and exposes a library of procedural basis functions. Each of these basis functions can be evaluated in any number of
dimensions, across any coordinate, without any need of referencing existing calculations. In addition, since they all share a
common interface, basis functions can be combined together and evaluated in a function graph by cross-referencing several
jit.bfg objects.

Matrix Operator
matrix inputs:1, matrix outputs:1
Name IOProc Planelink Typelink Dimlink Plane Dim Type
out n/a 1 1 1 1 1 char long float32 float64

Information for Jitter Matrix Operator (MOP) messages and attributes to this object

Messages
setattr The word setattr, followed by the name of an attribute and value or list of values,
forwards attribute messages on to internal objects (e.g. setattr basis abs 0 would
set the basis function object's abs attribute to zero.

Attributes
Name Type g/s Description
align float The fractional alignment for offsetting each plane. (default = 10)
autocenter int Flag for enabling or disabling automatically placing the origin at the center of the
output matrix. (default = 0)
basis symbol The name of the basis function to use for the evaluation. (default = none)
Supported basis functions are:
Distance Functions
chebychev (Absolute maximum difference between two points)
euclidean (True straight line distance in Euclidean space)
euclidean.squared (Squared Euclidean distance)
manhattan (Rectilinear distance measured along axes at right angles)
manhattan.radial (Manhattan distance with radius fall-off control)
minkovsky (Exponentially controlled distance)
Filter Functions
box (Sums all samples in the filter area with equal weight)
gaussian (Weights samples in the filter area using a bell curve)
lanczossinc (Weights samples using a steep windowed sinc curve)
mitchell (Weights samples using a controllable cubic polynomial)
disk (Sums all samples inside the filter's radius with equal weight)
sinc (Weights samples using an un-windowed sinc curve)
catmullrom (Weights samples using a Catmull-Rom cubic polynomial)
bessel (Weights samples with a linear phase response)
triangle (Weights samples in the filter area using a pyramid)
Transfer Functions
step (Always 0 if value is less than threshold, otherwise always 1)
smoothstep (Step function with cubic smoothing at boundaries)
bias (Polynomial similar to gamma but remapped to unit interval)
cubic (Generic 3rd order polynomial with controllable coefficients)
saw (Periodic triangle pulse train)
quintic (Generic 5th order polynomial with controllable coefficients)
gain (S-Shaped polynomial evaluated inside unit interval)
pulse (Periodic step function)
smoothpulse (Periodic step function with cubic smoothing at boundaries)
sine (Periodic sinusoidal curve)
linear (Linear function across unit interval)
solarize (Scales given value if threshold is exceeded)
Noise Functions
cellnoise (Coherent blocky noise)
checker (Periodic checker squares)
value.cubicspline (Polynomial smoothed pseudo-random values)
value.convolution (Convolution filtered pseudo-random values))
sparse.convolution (Convolution filtered pseudo-random feature points)
gradient (Directionally weighted polynomially interpolated values)
simplex (Simplex weighted pseudo-random values)
voronoi (Distance weighted pseudo-random feature points)
distorted (Domain distorted combinational noise)
Fractal Functions
mono (Additive fractal with global simularity across scales)
multi (Multiplicative fractal with varying simularity across scales)
multi.hybrid (A hybrid additive and multiplicative fractal)
multi.hetero (Heterogenous multiplicative fractal)
multi.ridged (Multiplicative fractal with sharp ridges)
turbulence (Additive mono-fractal with sharp ridges)

'distance.euclidean' = TEXT_HERE
'distance.euclidean.squared' = TEXT_HERE
'distance.manhattan' = TEXT_HERE
'distance.manhattan.radial' = TEXT_HERE
'distance.chebychev' = TEXT_HERE
'distance.minkovsky' = TEXT_HERE
'filter.bessel' = TEXT_HERE
'filter.box' = TEXT_HERE
'filter.catmullrom' = TEXT_HERE
'filter.disk' = TEXT_HERE
'filter.gaussian' = TEXT_HERE
'filter.lanczossinc' = TEXT_HERE
'filter.mitchell' = TEXT_HERE
'filter.sinc' = TEXT_HERE
'filter.triangle' = TEXT_HERE
'transfer.step' = TEXT_HERE
'transfer.smoothstep' = TEXT_HERE
'transfer.bias' = TEXT_HERE
'transfer.cubic' = TEXT_HERE
'transfer.saw' = TEXT_HERE
'transfer.quintic' = TEXT_HERE
'transfer.gain' = TEXT_HERE
'transfer.pulse' = TEXT_HERE
'transfer.smoothpulse' = TEXT_HERE
'transfer.sine' = TEXT_HERE
'transfer.linear' = TEXT_HERE
'transfer.solarize' = TEXT_HERE
'noise.cell' = TEXT_HERE
'noise.checker' = TEXT_HERE
'noise.distorted' = TEXT_HERE
'noise.gradient' = TEXT_HERE
'noise.simplex' = TEXT_HERE
'noise.voronoi' = TEXT_HERE
'noise.value.cubicspline' = TEXT_HERE
'noise.value.convolution' = TEXT_HERE
'noise.sparse.convolution' = TEXT_HERE
'fractal.mono' = TEXT_HERE
'fractal.hetero' = TEXT_HERE
'fractal.multi' = TEXT_HERE
'fractal.multi.hybrid' = TEXT_HERE
'fractal.multi.ridged' = TEXT_HERE
'fractal.turbulence' = TEXT_HERE
classname symbol The name of the basis function class (eg cellnoise) (default = none)
offset float The dimensional offsets to use for generating the spatial grid coordinates (only
valid when an input matrix is not attached). (default = 0)
origin float The dimensional origin to use for generating the spatial grid coordinates (only
valid when an input matrix is not attached). (default = 0)
precision symbol Internal precision for to use for evaluation, independent of matrix datatype.
(default = float32)
'float32' = TEXT_HERE
'float64' = TEXT_HERE
'fixed' = TEXT_HERE
'float' = TEXT_HERE
'double' = TEXT_HERE
rotation float The rotation angles to use for generating the spatial grid coordinates (only valid
when an input matrix is not attached). (default = 0)
scale float The dimensional scale factors to use for generating the spatial grid coordinates
(only valid when an input matrix is not attached). (default = 0)
seed int The seed value to use for initializing the pseudo-random number generator for
alignment. The same seed will result in the same output (default = -1138).
weight float The weight factors for scaling the output values. (default = 1)

Information for box attributes common to all objects

Examples

See Also
Name Description
jit.gencoord Evaluate a procedural basis function graph
jit.matrix The Jitter Matrix!
jit.normalize Normalizes a matrix.
Tutorial 50: Procedural Texturing Tutorial 50: Procedural Texturing & Modeling
& Modeling
jit.brass
Emboss image

Description
Provides a quick and dirty embossing effect on an 4-plane char input matrix. You can specify the amount and direction of the
emboss effect and apply an overall tint to the output matrix.

Matrix Operator
matrix inputs:1, matrix outputs:1
Name IOProc Planelink Typelink Dimlink Plane Dim Type
out n/a 1 1 1 4 1 char

Information for Jitter Matrix Operator (MOP) messages and attributes to this object

Attributes
Name Type g/s Description
atint float The amount of tinting to apply to the alpha channel (plane 0) (default = 0.)
btint float The amount of tinting to apply to the blue channel (plane 3) (default = 0.)
gtint float The amount of tinting to apply to the green channel (plane 2) (default = 0.)
mask int The overall embossing mask (default = 0 0 0 0)
The numbers in the list control the embossing amount for the four axes around
each cell in the form upperleft-to-lowerright top-to-bottom upperright-to-
lowerleft across-the-middle . Negative values will invert the direction of the effect.
rtint float The amount of tinting to apply to the red channel (plane 1) (default = 0.)

Information for box attributes common to all objects

Examples

See Also
Name Description
jit.convolve Convolve two matrices
jit.op Apply binary or unary operators
jit.qt.effect QuickTime Effects for Jitter matrices
jit.brcosa
Adjust image brightness/contrast/saturation

Description
Permits you to simultaneously adjust an image's brightness, contrast and saturation. This is useful for achieving a variety of color
effects.

Matrix Operator
matrix inputs:1, matrix outputs:1
Name IOProc Planelink Typelink Dimlink Plane Dim Type
out n/a 1 1 1 4 1 char

Information for Jitter Matrix Operator (MOP) messages and attributes to this object

Attributes
Name Type g/s Description
brightness float Brightness (default = 1.) Values below 1. (to 0.) reduce brightness, while values
above 1. increase it. 1. represents no change.
contrast float Contrast (default = 1.) Values below 1. (to 0.) decrease contrast, bringing the image
closer to grey (which represents the average luminance of the image frame).
Values above 1.0 increase contrast. 1.0 represents no change. Negative values
affect a color inversion, but with similar results.
saturation float Saturation (default = 1.) Values below 1. (to 0.) decrease saturation, bringing the
image closer to greyscale. Values above 1. increase saturation. 1. represents no
change. Negative values affect a color inversion, but with similar results.

Information for box attributes common to all objects

Examples

See Also
Name Description
jit.op Apply binary or unary operators
jit.scalebias Multiply and add
jit.traffic Multiply the planar vector by a matrix
jit.qt.effect QuickTime Effects for Jitter matrices
Tutorial 7: Image Level Tutorial 7: Image Level Adjustment
Adjustment
Tutorial 45: Introduction to using Tutorial 45: Introduction to using Jitter within JavaScript
Jitter within JavaScript
jit.broadcast
Broadcast video using RTSP

Description
The jit.broadcast object is an RTSP server. It takes a 4 char matrix as input, compresses the data and streams it over a network
(local or internet) using the RTSP streaming standard.

Matrix Operator
matrix inputs:1, matrix outputs:1
Name IOProc Planelink Typelink Dimlink Plane Dim Type
out n/a 1 1 1 4 1 char

Information for Jitter Matrix Operator (MOP) messages and attributes to this object

Messages
start Starts the broadcast server and reports the success or failure of the start operation
from the right outlet of the jit.broadcast object. In the event of success, the
message will be in the format start 1 URL . The URL argument is the RTSP URL
which client computers will use to access the stream.
Note that, if your computer is behind a router, the IP address reported may not
permit access to the stream by client machines outside of your local network. In
that instance, you will need to substitute your network's WAN address (the IP
address of the router, as seen by the outside world) for the IP address portion of
the URL , before non-local clients can receive your broadcast. The vport will also
need to be unblocked, if a firewall is active, and the port mapped to your computer
behind the router.
stop Stops the broadcast server.

Attributes
Name Type g/s Description
codec symbol The video codec for streaming (default = mpeg4)
The available codec types are jpeg, mjpega, mjpegb, h263 and mpeg4.
datarate int Sets the data rate in frames/second.
dstrect int The rectangular portion of the streaming image to be drawn to, when an incoming
matrix is received. (default = 0 0 (image width) (image height))
The proportions of the rectangle are expressed in the form left top right bottom .
All values are relative to the top left corner of the viewing area of the streamed
image.
interp int Interpolation flag (default = 0)
ip symbol Video IP address (default = variable)
In multicast mode (the default. See unicast, below), this IP address is
automatically assigned, and read-only, and refers to the special multicast address
client computers access to reach your broadcast.
In unicast mode, this IP address should be set to the IP address of the single client
computer.
kframe int Keyframe rate (default = 50)
If set, the jit.broadcast object will attempt to configure the video compressor to
use the specified keyframe rate. Keyframes (temporal compression) are not
available to all codecs.
mode int Streaming source mode (default = 0)
0 = matrix input
1 = Hinted Movie input (uses the movie attribute to choose a pre-hinted source
movie)
movie symbol Source movie for mode 1 (default = "")
If no movie is specified when setting this attribute, a File dialog will be presented.
Movies must be hinted, to be used with the jit.broadcast object. See Tutorial 51:
Broadcasting for more information.
port_v int Video broadcast port number (default = 8554)
The network port to be used by the video portion of the broadcast stream.
preview int Matrix preview flag (default = 0)
If set, an incoming matrix will be copied to the object's output matrix (with
srcrect, interp or dstrect transformations) when the jit.broadcast object is
streaming. Otherwise, the matrix is simply passed through the object. Only
functional in mode 0.
size int The dimensions of the broadcast (default = 160 120)
spatialquality symbol Codec spatial compression quality (default = 2 (normal))
0 or min = minimum
1 or low = low
2 or normal = normal
3 or high = high
4 or max = maximum
5 or lossless = lossless

Note that minimum quality is, in many cases, the codec's default quality. Use
"low" quality for consistent results.
srcrect int The rectangular section of the incoming matrix to compress and stream (default =
0 0 (movie width) (movie height))
streamname symbol Name of the broadcast stream, as displayed in the stream's URL (default =
"jitStream")
temporalquality symbol Codec temporal compression quality (default = 2 (normal))
0 or min = minimum
1 or low = low
2 or normal = normal
3 or high = high
4 or max = maximum
5 or lossless = lossless

Note that minimum quality is, in many cases, the codec's default quality. Use
"low" quality for consistent results.
ttl int Packet time to live (default = 255)
unicast int Unicast broadcast flag (default = 0)
If set, the jit.broadcast object will broadcast in unicast mode. In this mode, the ip
refers to a single client computer, which will be able to receive your broadcast. In
multicast mode (the default), as many clients as your system's bandwidth can
support will be able to access the stream.
usedstrect int Destination rect flag (default = 0)
When the flag is set, the dstrect attributes are used when compressing an input
matrix for streaming.
usesrcrect int Source rect flag (default = 0)
When the flag is set, the srcrect attributes are used when compressing an input
matrix for streaming. The proportions of the rectangle are expressed in the form
left top right bottom . All values are relative to the top left corner of the viewing
area of the incoming matrix.
vcodec symbol The video codec for streaming (default = h263)
Synonym for codec, above.
vip symbol Video IP address (default = variable)
Synonym for ip, above.
vport int Video broadcast port number (default = 8554)
Synonym for port_v, above.

Information for box attributes common to all objects

Examples

See Also
Name Description
jit.net.recv Receive matrices from a jit.net.send object via TCP/IP
jit.net.send Send matrices to a jit.net.recv object via TCP/IP
jit.qt.broadcast Broadcast video using RTSP (Macintosh only)
Tutorial 53: Jitter Networking Tutorial 53: Jitter Networking (part 2)
(part 2)
jit.bsort
Bubble sort

Description
Performs a bubble sort on an incoming matrix, sorting the cells in ascending order.

Matrix Operator
matrix inputs:1, matrix outputs:1
Name IOProc Planelink Typelink Dimlink Plane Dim Type
out n/a 1 1 1 1 1 char long float32 float64

Information for Jitter Matrix Operator (MOP) messages and attributes to this object

Attributes
Name Type g/s Description
dimmode int Sorts along the dimension specified the integer (0 or 1)
maxiter int The maximum number of search iterations (default = -1). A value of -1 sets the
search iterations based on the matrix size.
planemode int Sorts cells based on the values contained in the plane specified by the planemode
0-(planecount-1)
summode int Summing flag (default = 0) When the flag is set, sorting is based on the sum of the
planes.

Information for box attributes common to all objects

Examples

See Also
Name Description
jit.3m Report min/mean/max values
jit.histogram Calculate matrix histogram
jit.buffer~
Access an MSP buffer~ in matrix form

Description
Represents audio in a float32 matrix with time across dim[0]. Multi-channel audio uses a separate plane for each channel. The
object arguments are the same as those for the buffer~ object. jit.buffer~ responds to all the same messages as buffer~.

Arguments
Name Units Type Opt Description
buffer_name The name of the buffer~ to access
filename Optional filename to read
length Optional length in milliseconds
channels Optional number of channels (default=1)

Messages
anything Any message not specifically handled by the jit.buffer~ object will be passed along
to its child buffer~ object.
(mouse) Double-clicking on a jit.buffer~ object opens a display window where you can
view its contents.
getframes Outputs the number of frames.
getlength Outputs the length of the buffer~ in milliseconds.
output float32 matrix containing the range of the buffer~ specified by the outputstart,
outputlength, outputfirst and outputlast attributes will be output out the left
outlet.
viz Outputs a visualization matrix from the second outlet. In opaque mode the matrix
will be of type char and in statistical mode the matrix will be of type float32. In
both modes each channel of audio results is mapped to a separate plane of the
matrix.

Attributes
Name Type g/s Description
outputstart float The position in milliseconds to start collecting data from the buffer~ for an output
matrix
outputlength float The length in milliseconds of the output matrix collected from the buffer~
outputfirst int Frame at which to start collecting data from the buffer~ for an output matrix
outputlast int Frame at which to finish collecting data from the buffer~ for an output matrix
inputstart float An input matrix will be written to the buffer~ starting at this position in
milliseconds
inputfirst int An input matrix will be written to the buffer~ starting at this frame
vizwidth int The width of the visualization output matrix (default=320)
vizheight int The height of the visualization output matrix (default=160)
vizchecktime int How often in milliseconds the visualization engine should check the status of the
buffer~ and re-render the cache if necessary (default=250)
vizmode int A value of 1 turns on opaque rendering mode. A value of 2 turns on statistical
rendering mode, which has greater detail but is more expensive to render. A value
of 0 turns off visualization and all background processing of cached speedup data.
(default=0)
vizstart float The position in milliseconds to start the render of the visualization output matrix
vizlength float The length in milliseconds to render for the visualization output matrix
vizfirst int Frame at which to start render of the visualization output matrix
vizlast int Frame at which to end render of the visualization output matrix
vizmemoryratio float Specifies the size of the data cache used to speed up rendering of the visualization
matrix as a fraction of the data size of the buffer~ (default=0.5)

Information for box attributes common to all objects

Examples

See Also
Name Description
jit.catch~ Transform signal data into matrices
jit.graph Perform floating-point data visualization
jit.peek~ Read matrix data as an audio signal
jit.poke~ Write an audio signal into a matrix
jit.release~ Transforms matrix data into signals
peek~ Read and write sample values
poke~ Write sample values to a buffer by index
Tutorial 48: Frames of MSP Tutorial 48: Frames of MSP signals
signals
jit.catch~
Transform signal data into matrices

Description
Transforms MSP signals into a stream of jitter matrices.

Arguments
Name Units Type Opt Description
channels The number of input signals. An inlet will be created for each channel and the
output matrices will contain the data for each channel on a separate plane.

Messages
bang Receiving a bang may trigger a matrix to be output, depending on the mode and
the amount of signal data that has been received since the last bang.
bufsize The word bufsize, followed by a floating-point number, sets the size of the buffer
to be sampled.
signal Signal data received in any inlet of a jit.catch~ object will be converted to a stream
of Jitter matrices and sent out the object's outlet.

Attributes
Name Type g/s Description
mode int Four different modes are possible: in mode 0, all data since the last output is
output in a one-dimensional matrix. In mode 1 the amount of buffered data that
fits into a multiple of the framesize is output in two dimensions; data not output
will be saved for the next time. In these first two modes, every sample collected
should be output once and only once. In mode 2 a framesize of the most recent
data is output. Mode 3 causes jit.catch~ to behave like an oscilloscope, triggering
on channel trigchan when the signal crosses triglevel in the direction trigdir. If
the threshold has not been passed for the duration of the entire internal data
buffer (100 ms), jit.catch~ reverts temporarily to mode 2 behavior and outputs the
most recent data until the threshold is crossed again.
framesize int In some modes, the width of the output matrix. (default=320)
trigthresh float The signal level at which to trigger a redraw in mode 3 (default=0.0)
trigdir int The direction to use to identify crosses in the trigger point: 0 is upwards, and 1 is
downwards. (default=0)
trigchan int In mode 3, the channel to use for trigger points (default=0)
downsample int A downsampling factor (default=1). If downsampling value is set to n, each group
of n successive samples are averaged.

Information for box attributes common to all objects

Examples
See Also
Name Description
jit.buffer~ Access an MSP buffer~ in matrix form
jit.graph Perform floating-point data visualization
jit.gl.graph Graph floats into 3D space
jit.peek~ Read matrix data as an audio signal
jit.poke~ Write an audio signal into a matrix
jit.release~ Transforms matrix data into signals
peek~ Read and write sample values
poke~ Write sample values to a buffer by index
Tutorial 48: Frames of MSP Tutorial 48: Frames of MSP signals
signals
jit.change
Only pass different frames

Description
Calculates the number of cells in which the current matrix differs from the previously received matrix, and based on this
difference either passes the matrix or not.

Matrix Operator
matrix inputs:1, matrix outputs:1
Name IOProc Planelink Typelink Dimlink Plane Dim Type
out n/a 1 1 1 1 1 char long float32 float64

Information for Jitter Matrix Operator (MOP) messages and attributes to this object

Attributes
Name Type g/s Description
report int Report whether a matrix was passed (default = 0)
0 = do not report whether a matrix was passed
1 = report whether a matrix was passed

With report set to on (1), jit.change will behave a bit like Max's == object. If
jit.change determines that the matrix input has not changed (within the
parameters set with the mode and thresh attributes), it will send the message
report 1 from its rightmost outlet. If the matrix input has changed, jit.change will
send the message report 0.

mode int Mode of operation (default = 0 (more differing cells))


0 = pass new frames having MORE differing cells than the number specified by
the thresh value
1 = pass new frames having FEWER differing cells than the number specified by
the thresh value
'More-Than-Threshold' = TEXT_HERE
'Less-Than-Threshold' = TEXT_HERE
thresh int The difference threshold (default = 0)

The threshold specifies the number to cells above or below which a new "changed"
frame will be output. This object uses cells not planes; if you have a 4-plane matrix
and a threshold value of 3, one matrix cell with a different values from the
previously passed frame will NOT trigger a new frame -- If you have a single matrix
cell with 4 values (one per plane) which are different from the previously passed
frame, it will not trigger a new frame.

With the mode set to 0, a threshold of 0 means that even 1 different matrix cell
between 2 frames will cause that frame to be output. Higher values refer explicitly
to the matrix cell count required to cause output (5000 means it will take 5000
different matrix cells to cause the matrix to be output). Setting a negative
threshold will pass all frames.

Information for box attributes common to all objects

Examples
See Also
Name Description
jit.op Apply binary or unary operators
jit.charmap
Map 256-point input to output

Description
Creates a 256-point input to output map. Input values are replaced by the corresponding output value.

Matrix Operator
matrix inputs:2, matrix outputs:1
Name IOProc Planelink Typelink Dimlink Plane Dim Type
in2 resamp 1 1 0 1 1 char
out n/a 1 1 1 1 1 char

Information for Jitter Matrix Operator (MOP) messages and attributes to this object

Information for box attributes common to all objects

Examples

See Also
Name Description
jit.map Map input range to output range
jit.op Apply binary or unary operators
jit.scalebias Multiply and add
Tutorial 12: Color Lookup Tables Tutorial 12: Color Lookup Tables
Tutorial 49: Colorspaces Tutorial 49: Colorspaces
jit.chromakey
Key images based on chromatic distance

Description
Produces an chromakey effect based on a reference color. Tolerance and fade settings allow for control over the resulting
combined image. An alternate mode outputs a matrix with the keying values, which can be used by other Jitter objects.

Matrix Operator
matrix inputs:2, matrix outputs:1
Name IOProc Planelink Typelink Dimlink Plane Dim Type
in2 resamp 1 1 1 1 1 char long float32 float64
out n/a 1 1 1 1 1 char long float32 float64

Information for Jitter Matrix Operator (MOP) messages and attributes to this object

Attributes
Name Type g/s Description
alphaignore int Ignore alpha channel flag (default = 1)
0 = use alpha channel (plane 0) when calculating chromatic distance
1 = (plane 0) when calculating chromatic distance
color float The reference color to be used for keying (default = all 0.)
fade float The amount of fade (default = 0.)
maxkey float The maximum keying value (default = 1.)
minkey float Minimum keying value
mode int Output mode (default = 0)
0 = perform keying and output matrix
1 = output the key map for use elsewhere
2 = alpha contains key map, other planes are from left input
'Composite' = TEXT_HERE
'Key Map in All Channels' = TEXT_HERE
'Key Map in Alpha' = TEXT_HERE
tol float The tolerated distance -- the range of variance from which an input cell's absolute
value can diverge when calculating keying (default = 0.)

Information for box attributes common to all objects

Examples
See Also
Name Description
jit.alphablend Blend two images with an alpha channel image
jit.keyscreen Choke chromakey from 3 sources
jit.lumakey Key based on distance from a luminance value
jit.op Apply binary or unary operators
Tutorial 10: Chromakeying Tutorial 10: Chromakeying
jit.clip
Limit data to a range

Description
Limits matrix values to a range specified the object's min and max attributes.

Matrix Operator
matrix inputs:1, matrix outputs:1
Name IOProc Planelink Typelink Dimlink Plane Dim Type
out n/a 1 1 1 1 1 char long float32 float64

Information for Jitter Matrix Operator (MOP) messages and attributes to this object

Attributes
Name Type g/s Description
max float The maximum value above which clipping occurs (default = 1.)
min float The minimum value below which clipping occurs (default = 0.)

Information for box attributes common to all objects

Examples

See Also
Name Description
jit.3m Report min/mean/max values
jit.op Apply binary or unary operators
jit.coerce
Coerce a matrix into different types/planecount

Description
Coerces a matrix into different types/planecount without copying data (sometimes called "header munging"). This may be useful
for treating integers as floating point data and vice versa, or treating a four-plane char matrix as a single plane long matrix.

Matrix Operator
matrix inputs:1, matrix outputs:1
Name IOProc Planelink Typelink Dimlink Plane Dim Type
out n/a 0 0 0 1 1 char long float32 float64

Information for Jitter Matrix Operator (MOP) messages and attributes to this object

Attributes
Name Type g/s Description

Information for box attributes common to all objects

Examples

See Also
Name Description
jit.matrix The Jitter Matrix!
jit.pack Make a multiplane matrix out of single plane matrices
jit.unpack Make multiple single plane matrices out of a multiplane matrix
jit.submatrix Reference a sub-region of a matrix
jit.colorspace
Convert between colorspaces

Description
Converts a 4-plane char matrix between two different colorspaces. Output matrices are always 4-plane char, even if the colorspace
is normally described in a different format. The alpha channel (plane 0) remains untouched in all conversions except for the
KCMY colorspace.

Matrix Operator
matrix inputs:1, matrix outputs:1
Name IOProc Planelink Typelink Dimlink Plane Dim Type
out n/a 1 1 1 4 1 char

Information for Jitter Matrix Operator (MOP) messages and attributes to this object

Attributes
Name Type g/s Description
input symbol The name of the colorspace to convert from (default = RGB)
'RGB' = TEXT_HERE
'RetinalCone' = TEXT_HERE
'XYZ' = TEXT_HERE
'UVW' = TEXT_HERE
'uvY' = TEXT_HERE
'xyY' = TEXT_HERE
'U*V*W*' = TEXT_HERE
'S0W*' = TEXT_HERE
'L*HoC*' = TEXT_HERE
'YIQ' = TEXT_HERE
'YUV' = TEXT_HERE
'RGBcie' = TEXT_HERE
'RGBsmpte' = TEXT_HERE
'HSV' = TEXT_HERE
'HLS' = TEXT_HERE
'IHS' = TEXT_HERE
'L*a*b*' = TEXT_HERE
'L*u*v*' = TEXT_HERE
'CMY' = TEXT_HERE
'CMYK' = TEXT_HERE
'KCMY' = TEXT_HERE
'I1I2I3' = TEXT_HERE
output symbol The name of the colorspace to convert to (default = RGB)
The options are the same as for the input attribute.
'RGB' = TEXT_HERE
'RetinalCone' = TEXT_HERE
'XYZ' = TEXT_HERE
'UVW' = TEXT_HERE
'uvY' = TEXT_HERE
'xyY' = TEXT_HERE
'U*V*W*' = TEXT_HERE
'S0W*' = TEXT_HERE
'L*HoC*' = TEXT_HERE
'YIQ' = TEXT_HERE
'YUV' = TEXT_HERE
'RGBcie' = TEXT_HERE
'RGBsmpte' = TEXT_HERE
'HSV' = TEXT_HERE
'HLS' = TEXT_HERE
'IHS' = TEXT_HERE
'L*a*b*' = TEXT_HERE
'L*u*v*' = TEXT_HERE
'CMY' = TEXT_HERE
'CMYK' = TEXT_HERE
'KCMY' = TEXT_HERE
'I1I2I3' = TEXT_HERE

Information for box attributes common to all objects

Examples

See Also
Name Description
jit.rgb2luma Converts RGB to monochrome (luminance)
jit.hsl2rgb Convert HSL to RGB
jit.traffic Multiply the planar vector by a matrix
jit.rgb2hsl Convert HSL to RGB
jit.concat
Concatenate two matrices

Description
Accepts two matrices as input, and sends a single concatenated matrix out.

Matrix Operator
matrix inputs:2, matrix outputs:1
Name IOProc Planelink Typelink Dimlink Plane Dim Type
in2 adapt 0 0 0 1 1 char long float32 float64
out n/a 0 0 0 1 1 char long float32 float64

Information for Jitter Matrix Operator (MOP) messages and attributes to this object

Attributes
Name Type g/s Description
autoclear int Matrix clear following output flag (default = 1)
concatdim int The dimension across which concatenation occurs (default = 0)
mode int Concatenation order flag (default = 0)
0 = append the matrix entering the right inlet to the matrix entering the left inlet
1 = append the matrix entering the left inlet to the matrix entering the right inlet
'Append Right to Left' = TEXT_HERE
'Append Left to Right' = TEXT_HERE
truncate int Matrix truncation flag (default = 1) When the flag is set, the right input's
dimensions are truncated to the left input's dimensions if the right dimensions are
greater than the left for all dimensions except the concatenation dimension.

Information for box attributes common to all objects

Examples
See Also
Name Description
jit.demultiplex Demultiplex (deinterleave) one matrix into two
jit.glue Glue many matrices into one
jit.matrix The Jitter Matrix!
jit.multiplex Multiplex (interleave) two matrices into one matrix
jit.scissors Cut up a matrix into evenly spaced sub matrices
jit.split Split a matrix into two matrices
jit.convolve
Convolve two matrices

Description
Convolves a matrix with another matrix (convolution kernel). This may be used for typical image processing tasks like blurring,
sharpening, and edge detection. By default, the convolution kernel is a 3 by 3 float32 matrix

Matrix Operator
matrix inputs:2, matrix outputs:1
Name IOProc Planelink Typelink Dimlink Plane Dim Type
in2 adapt 0 0 0 1 1 float32
out n/a 1 1 1 1 1 char long float32 float64

Information for Jitter Matrix Operator (MOP) messages and attributes to this object

Attributes
Name Type g/s Description
boundmode int Boundary case handling mode (default = 0 (clip))
0 = clip: cells which lie outside the domain of the input data will clip to the nearest
cell within the domain of the input data (e.g. a convolution which would need to
use cell (0,-1) would instead use cell (0,0)).
1 = wrap: cells which lie outside the domain of the input data will wrap via
modulus arithmetic within the domain of the input data (e.g. a convolution on a
320 by 240 matrix which would need to use cell (0,-1) would instead use cell
(0,239)).
2 = ignore: cells which lie outside the domain of the input data will not be used in
calculating the convolution.
origin int The origin of the convolution kernel (default = 1 1)

Information for box attributes common to all objects

Examples
See Also
Name Description
jit.fastblur Blur/sharpen using optimized algorithm
jit.op Apply binary or unary operators
jit.conway
Play Conway's game of life

Description
Performs Conway's Game of Life (a cellular automata function) on incoming 1- or 4-plane character matrices.

Matrix Operator
matrix inputs:1, matrix outputs:1
Name IOProc Planelink Typelink Dimlink Plane Dim Type
out n/a 1 1 1 1 1 char

Information for Jitter Matrix Operator (MOP) messages and attributes to this object

Attributes
Name Type g/s Description
birthmark int Defines whether newborn cells are set to 255 (off) or to the average of the
contributing neighbor cells (on) (default = 0).
deathmask int A mask setting whether a given number of live (non-0) neighbors will make a dead
(0) cell come to life (default = 0 0 0 1 0 0 0 0 0). The first element in the list is the
mask value for 0 live neighbors.
lifemask int A mask setting whether a given number of live (non-0) neighbors will keep a live
(non-0) cell alive (default = 0 0 1 1 0 0 0 0 0). The first element in the list is the
mask value for 0 live neighbors.
neighborhood int A mask for which neighbors around a cell are tallied to determine whether the cell
changes state (default = 1 1 1 1 1 1 1 1). Ordering is upper-left, upper, upper-right,
left, right, lower-left, lower, lower-right.

Information for box attributes common to all objects

Examples
See Also
Name Description
jit.linden Lindenmayer string expansion (L-systems)
Tutorial 17: Feedback Using Tutorial 17: Feedback Using Named Matrices
Named Matrices
jit.cycle
Cycle messages through outputs

Description
Route messages, unchanged, through the object's outlets sequentially. Lists remain intact, unlike the Max cycle object. The
jit.cycle object takes a single integer argument, which sets the number of outlets.

Arguments
None.

Messages
bang Any bang message sent to the jit.cycle object is sent out the next outlet in
sequence.
int Any int sent to the jit.cycle object is sent out the next outlet in sequence.
float Any float sent to the jit.cycle object is sent out the next outlet in sequence.
list Any list sent to the jit.cycle object is sent out the next outlet in sequence.
anything Any message sent to the jit.cycle object is sent out the next outlet in sequence.
reset Causes the index to jump to either the lo or hi value, depending on the current
cycle mode setting (mode).

Attributes
Name Type g/s Description
mode int Cycle mode (default = 0 (left to right))
0 = left to right (from lo to hi)
1 = right to left (from hi to lo)
2 = pendulum mode, starting from lo, passing sequentially to hi, and then back to
lo
index int The current outlet
hi int Outlet high limit (default = rightmost outlet) Outlets with indices higher than the
value of the hi attribute are ignored during routing. Outlet indices begin
numbering at 0.
lo int Outlet low limit (default = 0 (leftmost outlet)) Outlets with indices lower than the
value of the lo attribute are ignored during routing. Outlet indices begin
numbering at 0.

Information for box attributes common to all objects

Examples
See Also
Name Description
cycle Round-robin messages to outlets
jit.reverse Reverse output with respect to input
router Route messages to multiple locations
jit.demultiplex
Demultiplex (deinterleave) one matrix into two

Description
Accepts a single matrix as input, and derives two output matrices from it by demultiplexing across a specified dimension.

Matrix Operator
matrix inputs:1, matrix outputs:2
Name IOProc Planelink Typelink Dimlink Plane Dim Type
out n/a 0 0 0 1 1 char long float32 float64
out2 n/a 0 0 0 1 1 char long float32 float64

Information for Jitter Matrix Operator (MOP) messages and attributes to this object

Attributes
Name Type g/s Description
autoclear int Matrix clear following output flag (default = 1)
demultiplexdim int The dimension across which demultiplexing occurs (default = 0)
'0' = TEXT_HERE
'1' = TEXT_HERE
'2' = TEXT_HERE
'3' = TEXT_HERE
'4' = TEXT_HERE
'5' = TEXT_HERE
'6' = TEXT_HERE
'7' = TEXT_HERE
'8' = TEXT_HERE
'9' = TEXT_HERE
'10' = TEXT_HERE
'11' = TEXT_HERE
'12' = TEXT_HERE
'13' = TEXT_HERE
'14' = TEXT_HERE
'15' = TEXT_HERE
'16' = TEXT_HERE
'17' = TEXT_HERE
'18' = TEXT_HERE
'19' = TEXT_HERE
'20' = TEXT_HERE
'21' = TEXT_HERE
'22' = TEXT_HERE
'23' = TEXT_HERE
'24' = TEXT_HERE
'25' = TEXT_HERE
'26' = TEXT_HERE
'27' = TEXT_HERE
'28' = TEXT_HERE
'29' = TEXT_HERE
'30' = TEXT_HERE
'31' = TEXT_HERE
scan_a int The number of scanlines across the input matrix sampled into the first output
matrix (default = 1)
To perform a standard deinterleave of NTSC video, scan_a and scan_b would
both be set to 1.
scan_b int The number of scanlines across the input matrix sampled into the second output
matrix (default = 1)
To perform a standard deinterleave of NTSC video, scan_a and scan_b would
both be set to 1.

Information for box attributes common to all objects

Examples

See Also
Name Description
jit.concat Concatenate two matrices
jit.glue Glue many matrices into one
jit.matrix The Jitter Matrix!
jit.multiplex Multiplex (interleave) two matrices into one matrix
jit.scissors Cut up a matrix into evenly spaced sub matrices
jit.split Split a matrix into two matrices
jit.desktop
Copy the display into a matrix

Description
Grabs the contents of the computer display, taking a screen shot of whatever lies at the specified screen coordinates and placing
that data into a Jitter matrix.

Matrix Operator
matrix inputs:0, matrix outputs:1
Name IOProc Planelink Typelink Dimlink Plane Dim Type
out n/a 1 1 1 4 2 char

Information for Jitter Matrix Operator (MOP) messages and attributes to this object

Attributes
Name Type g/s Description
rect int Coordinates of the computer display to copy into a Jitter matrix. The display area
is specified by four ints corresponding to the x and y pixel offsets from the upper
left of the computer screen followed by the horizontal and vertical size of the
matrix (default = 0 0 320 240)

Information for box attributes common to all objects

Examples

See Also
Name Description
jit.displays Set and query monitor attributes
jit.dimmap
Remap and/or invert matrix dimensions

Description
Provides remapping and/or inversion of matrix dimensions. Similar to the jit.transpose object, however any dimension may be
mapped to any other dimension as well as inverted. Note that the input to output map may not contain any duplicates.
Redundant dimensions of size 1 may be inserted by using a map value of -1 at the corresponding dimension index.

Matrix Operator
matrix inputs:1, matrix outputs:1
Name IOProc Planelink Typelink Dimlink Plane Dim Type
out n/a 0 0 0 1 1 char long float32 float64

Information for Jitter Matrix Operator (MOP) messages and attributes to this object

Attributes
Name Type g/s Description
invert int Invert dimension flag array (default = all zero)
map int Input to output dimension map (default = 0 1 2 ... 31)

Information for box attributes common to all objects

Examples

See Also
Name Description
jit.matrix The Jitter Matrix!
jit.transpose Calculate the transpose of a matrix
jit.dimop
Downsample using operators across dimensions

Description
Applies an operator to elements within a subregion, across one or more dimensions, downsampling the input matrix in the
process.

Matrix Operator
matrix inputs:1, matrix outputs:1
Name IOProc Planelink Typelink Dimlink Plane Dim Type
out n/a 0 0 0 1 1 char long float32 float64

Information for Jitter Matrix Operator (MOP) messages and attributes to this object

Attributes
Name Type g/s Description
op symbol The operator to be used in the downsampling process (default = avg).
'avg' = TEXT_HERE
'+' = TEXT_HERE
'*' = TEXT_HERE
'min' = TEXT_HERE
'max' = TEXT_HERE
step int Step size across each dimension (default = 1). A step size of -1 will span the entire
dimension.

Information for box attributes common to all objects

Examples

See Also
Name Description
jit.op Apply binary or unary operators
jit.planeop Operator across planes
jit.expr Evaluate an expression to fill a matrix
jit.displays
Set and query monitor attributes

Description
Senses additional display hardware attached to your computer and allows you to use standard Jitter get* and set* messages to
enumerate the number and coordinates of any and all monitors. The object remembers the original state of your system's display
settings when the object is instantiated, which can be easily recalled, and you can also use the object to enable display mirroring.
Typically, the jit.displays object is saved as a portion of a performance patch setup to automatically determine the exact position
of your attached hardware and move your output window as needed.

Arguments
None.

Messages
bang Equivalent to the count message. Sends a count of the attached displays out the
object's outlet in the form count number-of-displays .
coords display-index Sends the display screen coordinates for the display whose index is specified out
[int] the object's right outlet as a list in the form coords display-index left top bottom
right . Displays are counted from 0 (0 is the primary display).
count Sends a count of the attached displays out the object's outlet in the form count
number-of-displays .
currentstate display-index Sends the current state of the display out the object's outlet as a list in the form
[int] currentstate display-index width height color-bit-depth refresh-rate . Note that
LCD displays report a refresh rate of 0.
gammatable2matrix display-index Copies the gamma table for the display specified by display-index to the matrix
[int] named matrix-name.
matrix-name
[symbol]
getmode display-index Sends available display modes for display specified by display-index out the right
[int] outlet as a sequence of lists, one display per line. Each display is described by a list
in the form mode display-index mode-index width height color-bit-depth
refresh-rate . Note: LCD displays have a refresh rate of 0.
manual display-index Macintosh only
[int] Sets the display to a configuration which provides the closest match for the ideal
width [int] configuration specified by the arguments.
height [int]
bit-depth [int]
matrix2gammatable matrix-name Copies the Jitter matrix named matrix-name to the gamma table for the display
[symbol] specified by display-index. On Windows, gamma tables with negative slope are
display-index not permitted, and will result in an error message.
[int]
mirror src-display-index Macintosh only
[int] Enables video mirroring of the display whose number is specified by src-display-
dst-display- index to the display whose number is specified by dst-display-index.
index [int]
move display-index Changes the logical screen location of the display whose number is specified by
[int] src-display-index. Two additional arguments specify the new screen location. If
newxtop [int] a location is chosen which overlaps with the location of another display, a new
newytop [int] non-overlapping location will be automatically assigned. The final position of the
display after a move can be verified using the coords message.
reset Return displays to their snapshot state (see the snapshot method). Note that reset
does not have any affect on video mirroring settings, which must be maintained
manually.
resetgamma Return display gamma settings to their system default state.
setmode display-index Change the display mode. The two arguments specify the display index, and the
[int] mode index (derived from the getmode message).
mode-index [int]
snapshot Saves the current display mode (on all active displays) for use with the reset and
resetmode messages. A snapshot is automatically taken when the object is
instantiated.
unmirror display-index Macintosh only
[int] Disables video mirroring on the specified display.

Attributes
Name Type g/s Description
resetmode int Macintosh only
Display mode flag (default = 1)
Enables or disables reset when the object is freed The jit.displays object
remembers the original state of your system's display settings when the object is
instantiated (display settings can also be saved using the snapshot message. A
resetmode 1 will cause the original display settings to be restored when the patch
is closed or the object is otherwise freed.
gamma float (set) Monitor gamma settings (Macintosh default = 0 1.8 1.8 1.8) (Windows default = 0
2.2 2.2 2.2)
The first argument specifies the device. The latter three arguments are used as
coefficients in the generation of power-curve gamma tables for the red, green and
blue channels. 1.8 represents standard Macintosh gamma, while 2.2 represents
standard Windows gamma.

Information for box attributes common to all objects

Examples

See Also
Name Description
jit.desktop Copy the display into a matrix
Tutorial 38: Basic Performance Tutorial 38: Basic Performance Setup
Setup
jit.dx.grab
Digitize video using DirectX (Windows)

Description
Digitizes video from any DirectX-compatible video digitizer, and decompresses the signal into a Jitter matrix. It also offers a grab-
to-disk mode. Although numerous parameters for control are offered, not all features are supported by all digitizers.

Matrix Operator
matrix inputs:1, matrix outputs:1
Name IOProc Planelink Typelink Dimlink Plane Dim Type
out n/a 1 1 1 4 1 char

Information for Jitter Matrix Operator (MOP) messages and attributes to this object

Messages
settings Opens the standard video digitizer settings dialog box.
snd_settings Opens the standard sound digitizer settings dialog box.
stop Stops grabbing to disk.
defaults Restores digitizer image control defaults.
exportimage filename [symbol] Export the current frame as an image file with the name specified by the first
file-type [symbol] argument. The second argument sets the file type (default = png). Available file
use-dialog [int] types are png, bmp, jpeg, macpaint, photoshop, pict, qtimage, sgi, tga and
tiff. An optional use-dialog argument of 1 will open a File dialog to allow you to
enter the image file settings.
You can use the Max Preferences to specify a default image resolution.
open Opens a sequence grab component. A component must be explicitly opened before
the jit.dx.grab object will began digitizing.
close Closes an open sequence grab component. The component is automatically closed
when the object is freed.
write filename [symbol]
FPS [float] Starts grabbing to disk. If no filename argument is supplied, a file dialog box will
open.

The default FPS is 30. frames/sec.

getvdevlist Reports the list of available video digitizers from the object's right outlet, preceded
by the word vdevlist.
getinputlist Reports the list of available inputs to the video digitizer from the object's right
outlet, preceded by the word inputlist. Note that the digitizer must be open in
order for this method to function.
getsnddevlist Reports the list of available sound digitizers from the object's right outlet,
preceded by the word snddevlist.
getsndinputlist Reports the list of available inputs for the current sound digitizer from the object's
right outlet, preceded by the word sndinputlist. Note that the digitizer must be
open in order for this method to function.
getformatlist Reports the list of available digitizer formats from the object's right outlet,
preceded by the word formatlist. Note that the digitizer must be open in order
for this method to function.

Attributes
Name Type g/s Description
backlight float The video digitizer backlight compensation setting (default = digitizer-specific)
0 = off
1 = on
bitrate int The sound digitizer bit depth (default = digitizer-specific)
8 = digitize sound at 8-bit resolution
16 = digitize sound at 16-bit resolution
brightness float The video digitizer brightness level (default = digitizer-specific)
channels int The sound channel selection (default = digitizer-specific)
1 = digitize sound in mono
2 = digitize sound in stereo
colorenable float The video digitizer colorenable setting (default = digitizer-specific)
0 = off
1 = on
colormode symbol The output matrix's color encoding (default = argb)
argb = ARGB (alpha, red, green, blue) colormode
uyvy = UYVY (YUV 4:2:2 packed) colormode
'argb' = TEXT_HERE
'uyvy' = TEXT_HERE
contrast float The video digitizer contrast level (default = digitizer-specific)
dropreport int Dropped frames reporting flag (default = 0 (disabled))
When this flag is set, the message dropped will be sent from the rightmost outlet
of the jit.dx.grab object, followed by the number of dropped frames, whenever
frame-dropping is detected.
dstrect int The portion of the output matrix used for decompressing media to the internal
matrix. (default = 0 0 (matrix width) (matrix height))
The proportions of the rectangle are expressed in the form left top right bottom .
All values are relative to the top left corner of the viewing area of the output
matrix.
format int The video digitizer format selection (default = digitizer-specific)
gain float The video digitizer gain (default = digitizer-specific)
Note that the jit.qt.grab object has an attribute called gain which controls audio ,
rather than video gain.
gamma float The video digitizer gamma (default = digitizer-specific)
hue float The video digitizer hue adjustment (default = digitizer-specific)
input int The current video digitizer input (default = digitizer-specific)
interp int Image interpolation flag (default = 0)
resolution int Preferred capture resolution for the digitizer (default = digitizer-specific)
If a resolution is specified, an attempt is made to configure the digitizer to capture
at that resolution.
samplerate int Sound digitizer sample rate (default = digitizer-specific)
44100 = 44.1 kHz
48000 = 48.0 kHz
(other rates may be available, but are digitizer-specific)
saturation float Video digitizer saturation level (default = digitizer-specific)
sharpness float Video digitizer sharpness level (default = digitizer-specific)
snddevice int The current sound digitizer (default = 0)
srcrect int Source rect from digitizer frame (default = 0 0 (matrix width) (matrix height))
unique int Unique frame filter flag (default = 0 (disabled))
When the flag is set, only new frames from the digitizer are output when the
object receives a bang. If no new frame has been received from the digitizer, the
jit.dx.grab object will not respond to the bang.
usedstrect int Destination rect flag (default = 0) When the flag is set, the dstrect attributes are
used when copying an input matrix to the internal matrix.
usesrcrect int Source rect flag (default = 0) When the flag is set, the srcrect attributes are used
when copying an input matrix to the internal matrix.
vdevice int The current video digitizer (default = 0)
whitebalance float The video digitizer white balance (color temperature) (default = digitizer-specific)
write_audio int Audio track write flag (default = 0) When the flag is set, an audio track is written
when grabbing images to disk.
write_video int Video track write flag (default = 1) When the flag is set, a video track is written
when grabbing images to disk.

Information for box attributes common to all objects

Examples

See Also
Name Description
jit.qt.effect QuickTime Effects for Jitter matrices
jit.qt.grab Digitize video from an external source
jit.qt.movie Play or edit a QuickTime movie
jit.qt.record Record a QuickTime movie
jit.qt.videoout Output video to QuickTime video output component
Tutorial 21: Working With Live Tutorial 21: Working With Live Video and Audio Input
Video and Audio Input
jit.dx.videoout
Output video to DirectX (Windows)

Description
The jit.dx.videoout object takes a matrix as input, compresses the data and sends it directly over FireWire to an attached DV
camera.

Matrix Operator
matrix inputs:1, matrix outputs:1
Name IOProc Planelink Typelink Dimlink Plane Dim Type
out n/a 1 1 1 1 1 char long float32 float64

Information for Jitter Matrix Operator (MOP) messages and attributes to this object

Messages
open Opens a connection to a FireWire device for video output. You must open the
connection before the jit.dx.videoout object does anything.
close Closes the connection to an open FireWire device. The connection is automatically
closed when the object is freed.

Information for box attributes common to all objects

Examples

See Also
Name Description
jit.qt.effect QuickTime Effects for Jitter matrices
jit.dx.grab Digitize video using DirectX (Windows)
jit.qt.grab Digitize video from an external source
jit.qt.movie Play or edit a QuickTime movie
jit.qt.record Record a QuickTime movie
jit.qt.videoout Output video to QuickTime video output component
jit.eclipse
Create images from images

Description
Divides a matrix sent into the left inlet into a grid with a specified number of rows and columns. Each box in the grid contains a
scaled-down representation of the overall matrix. Each box is then tinted so that the overall image resembles a second matrix
(sent into the right inlet). If the same image is used in both inputs, the result is a self-similar (or meta-) image.

Matrix Operator
matrix inputs:2, matrix outputs:1
Name IOProc Planelink Typelink Dimlink Plane Dim Type
in2 resamp 1 1 1 4 1 char
out n/a 1 1 1 4 1 char

Information for Jitter Matrix Operator (MOP) messages and attributes to this object

Attributes
Name Type g/s Description
blue float The amount of additional scaling applied to the blue channel (plane 3) of the
output matrix (default = 0.)
columns int The number of columns in the meta-image (default = 1)
green float The amount of additional scaling applied to the green channel (plane 2) of the
output matrix (default = 0.)
inv int Invert color flag (default = 0) When the flag is set, RGB attributes are inverted in
regions of the output image that are inverted.
mode int Color mode by which the object tints the output matrix (default = 0 (both matrices
color))
0 = both matrices are color
1 = matrix 1 is converted to greyscale
2 = matrix 2 is converted to greyscale
3 = both matrices are converted to greyscale

'Color Tint Color Frames' = TEXT_HERE


'Color Tint Monochrome Frames' = TEXT_HERE
'Monochrome Tint Color Frames' = TEXT_HERE
'Monochrome Tint Monochrome Frames' = TEXT_HERE
op int The mathematical operation used for tinting (default = 0 (addition))
0 = addition
1 = multiplication
'Add' = TEXT_HERE
'Multiply' = TEXT_HERE
red float The amount of additional scaling applied to the red channel (plane 1) of the output
matrix (default = 0.)
rows int The number of rows in the meta-image (default = 1)
thresh float The threshold luminosity value around which grid regions in the meta-image are
inverted in color (default = -1.01)
tint int Tint mode flag (default = 1) When the flag is set, tinting is based on the second
input matrix.

Information for box attributes common to all objects

Examples
See Also
Name Description
jit.altern Color screen with threshold
jit.roy Convert image to halftone image
jit.euler2quat
Convert Euler angles to quaternion

Description
Convert Euler X/Y/Z representation of an orientation to a quaternion.

Messages
bang Output the resulting quaternion conversion.
list x [float] A three element list of floating point numbers interpreted as Euler angles in
y [float] degrees, is converted to a quaternion and output.
z [float]

Attributes
Name Type g/s Description
euler float The Euler angles to be converted. (default = 0 0 0)
normalize int Normalize the quaternion before outputting (default = 0).
quat float (get) The resulting quaternion after the conversion.

Information for box attributes common to all objects

Examples

See Also
Name Description
jit.quat Quaternion multiplication
jit.quat2euler Quaternion to Euler conversion
jit.quat2axis Quaternion to angle-axis conversion
jit.axis2quat Convert angle-axis to quaternion
jit.anim.node Perform hierarchical transformation
jit.expr
Evaluate an expression to fill a matrix

Description
Evaluates expressions to fill an output matrix. The expression can contain any operator available from within jit.op, any functor
available from within jit.bfg, and many jitter MOPs. A variable number of inputs can be specified with an attribute argument
setting the inputs attribute.

Matrix Operator
matrix inputs:-1, matrix outputs:1
Name IOProc Planelink Typelink Dimlink Plane Dim Type
out n/a 1 1 1 1 1 char long float32 float64

Information for Jitter Matrix Operator (MOP) messages and attributes to this object

Messages
int Sets all matrix cells corresponding with input to int.
float Sets all matrix cells corresponding with input to float.
list input [list] Sets all matrix cells corresponding with input to list, on a per plane basis.

Attributes
Name Type g/s Description
inputs int Input count (default = 2)
cache int Toggles the cache intermediary values flag. The default is 1 (on). It may be
desirable to turn off when using generator operators such as jit.noise in the
expression, which should not be cached.
expr symbol The expression to evaluate. If one expression is specified, it is evaluated for all
planes. If multiple expressions are specified, they are evaluated on a plane by
plane basis.
precision symbol Sets the internal precision. The options are:

float32 (the default)


float64
verbose int Toggles the printing of expression information to Max Window.

Information for box attributes common to all objects

Examples
See Also
Name Description
expr Evaluate a mathematical expression
jit.charmap Map 256-point input to output
jit.op Apply binary or unary operators
jit.bfg Evaluate a procedural basis function graph
vexpr Evaluate a math expression for a list
Tutorial 39: Spatial Mapping Tutorial 39: Spatial Mapping
Tutorial 46: Manipulating Matrix Tutorial 46: Manipulating Matrix Data using JavaScript
Data using JavaScript
jit.fastblur
Blur/sharpen using optimized algorithm

Description
Performs several special-case convolution blur/sharpen operations on incoming matrices. Although it is less flexible than the
jit.convolve object, the jit.fastblur object will be quicker and easier to set up for the equivalent convolution, in most cases.

Matrix Operator
matrix inputs:1, matrix outputs:1
Name IOProc Planelink Typelink Dimlink Plane Dim Type
out n/a 1 1 1 1 1 char

Information for Jitter Matrix Operator (MOP) messages and attributes to this object

Attributes
Name Type g/s Description
center float The mathematical weighting of the center pixel when performing convolution
(default = 1.)
mode int The kernel shape (default = 0 (row))
0 = row
1 = column
2 = cross
3 = diagonal
4 = square

'Row' = TEXT_HERE
'Column' = TEXT_HERE
'Cross' = TEXT_HERE
'Diagonal' = TEXT_HERE
'Square' = TEXT_HERE
range int The number of pixels from the center pixel of the convolution kernel to its edge
(default = 1)
ring float The mathematical weighting of cells adjoining the center pixel when performing
convolution (default = 1.)
ripple float The scaling applied to outer cells when performing convolution (default = 1.) The
second ring of pixels is scaled by this factor in relation to the ring attribute when
performing convolution, while the third ring is scaled in relation to the second.

Information for box attributes common to all objects

Examples
See Also
Name Description
jit.convolve Convolve two matrices
jit.op Apply binary or unary operators
jit.fft
Perform a matrix-based FFT

Description
Performs both the Fast Fourier Transform and Inverse Fast Fourier Transform on an input matrix. It requires that the input has
two planes that represent complex numbers--plane 0 is the real component, and plane 1 is the imaginary component.

Matrix Operator
matrix inputs:1, matrix outputs:1
Name IOProc Planelink Typelink Dimlink Plane Dim Type
out n/a 1 1 1 2 1 float32 float64

Information for Jitter Matrix Operator (MOP) messages and attributes to this object

Attributes
Name Type g/s Description
inverse int Calculate inverse transform flag (default = 0)

Information for box attributes common to all objects

Examples

See Also
Name Description
jit.convolve Convolve two matrices
jit.histogram Calculate matrix histogram
jit.op Apply binary or unary operators
jit.fill
Fill a matrix with a list

Description
Fills one plane of a named matrix with the values of a list received in its left inlet. The offset and plane attributes determine the
cells to be filled. Upon completion, the jit.fill object sends a bang message out its left outlet.

Arguments
None.

Messages
int Fills the cell at the current offset with an int value
float Fills the cell at the current offset with a float value
list Fills the cells beginning at the current offset with list values

Attributes
Name Type g/s Description
matrix_name symbol The name of target matrix
plane int The plane in matrix to be filled (default = 0)
offset int The dimension offset into matrix to be filled (default = all zero)

Information for box attributes common to all objects

Examples

See Also
Name Description
jit.iter Iterate a matrix as lists or values
jit.matrix The Jitter Matrix!
jit.spill Unroll a matrix into a list
zl Process lists in many ways
Tutorial 11: Lists and Matrices Tutorial 11: Lists and Matrices
Tutorial 12: Color Lookup Tables Tutorial 12: Color Lookup Tables
jit.findbounds
Locate bounding dimensions for a value range

Description
Scans a matrix for values in the range [ min, max ] and sends out the minimum and maximum points that contain those values.
The minimum point is sent as a list out the leftmost outlet, and the maximum point is sent as a list out the second outlet. If both
points are all -1 values, then there are no points within the range.

Matrix Operator
matrix inputs:1, matrix outputs:0
Name IOProc Planelink Typelink Dimlink Plane Dim Type

Information for Jitter Matrix Operator (MOP) messages and attributes to this object

Attributes
Name Type g/s Description
boundmax int (get) The maximum bounding point
boundmin int (get) The minimum bounding point
max float The maximum value to search for (default = all 0.)
min float The minimum value to search for (default = all 0.)

Information for box attributes common to all objects

Examples

See Also
Name Description
jit.3m Report min/mean/max values
jit.op Apply binary or unary operators
Tutorial 25: Tracking the Position Tutorial 25: Tracking the Position of a Color in a Movie
of a Color in a Movie
jit.fluoride
Add a neon glow

Description
Provides an approximation of a neon glow effect. Individual cell values fade into a specified color as they approach a luminance
value. Cell values greater than the luminance value fade to black. Values outside of a tolerance boundary are passed.

Matrix Operator
matrix inputs:1, matrix outputs:1
Name IOProc Planelink Typelink Dimlink Plane Dim Type
out n/a 1 1 1 4 1 char

Information for Jitter Matrix Operator (MOP) messages and attributes to this object

Attributes
Name Type g/s Description
glow float The color of the glow in the form red green blue (default = 0. 1. 0.) All color values
should be in the range 0.-1.
lum float The luminosity threshold for the glow effect (default = 0.88)
mode int Output mode setting (default = 0 (greyscale))
0 = output is converted to greyscale after glow is applied
1 = output retains its color after glow is applied
'Black and White' = TEXT_HERE
'Color' = TEXT_HERE
tol float Tolerance level (or width) of the color range affected by the glow (default = 0.2)

Information for box attributes common to all objects

Examples

See Also
Name Description
jit.chromakey Key images based on chromatic distance
jit.lumakey Key based on distance from a luminance value
jit.fprint
Read/write a matrix as a text file

Description
Imports or exports a single matrix from or to a text file.

Matrix Operator
matrix inputs:1, matrix outputs:1
Name IOProc Planelink Typelink Dimlink Plane Dim Type
out n/a 1 1 1 1 1 char long float32 float64

Information for Jitter Matrix Operator (MOP) messages and attributes to this object

Messages
read filename [symbol] Open and read a single matrix from a text file. The optional argument specifies the
filename. The jit.fprint object expects text files to be formatted in the same fashion
in which it writes them. Attempting to read unformatted text files will likely return
an error.
write filename [symbol] Create a new text file for writing. The optional argument specifies a filename. The
text file is not written until a matrix is received by the jit.fprint object. After a
write attempt, the message write followed by two int arguments will be sent from
the object's right outlet. The first int indicates the success (1) or failure (0) of the
write operation, and the second int indicates the number of bytes written to the
file (if any).

Attributes
Name Type g/s Description
default_dir symbol Equivalent to defaultdir.
defaultdir symbol The default directory for writing files (default = default path)
coldelim symbol The column delimiter (default = tab)
planedelim symbol The matrix plane delimiter (default = space)
precision int The number of characters of floating-point precision (default = 6)
rowdelim symbol The row delimiter (default = carriage return)
writemode int Data write mode (default = 0 (integer))
0 = integers used when writing matrix values
1 = floats used when writing matrix values
'Integer' = TEXT_HERE
'Floating-Point' = TEXT_HERE

Information for box attributes common to all objects

Examples
See Also
Name Description
jit.print Print a matrix in the Max window
jit.textfile Read and write a matrix as an ASCII text file
jit.fpsgui
Display fps, ms, and matrix attributes

Description
Reports timing and matrix information. Currently available reports: fps (frames per second), ms (milliseconds between incoming
data), matrix type, dimensions, planecount, and name.

Arguments
None.

Messages
anything any-message [list] Any message sent to the object causes it to calculate fps and ms. The matrix
attribute displays show n/a .
getstate Sends a sequence of lists describing the incoming matrix's state out the object's
right outlet, one line per attribute. Each line listing line takes the form attribute-
name attribute-value1 attribute-value2 ... attribute-valueN .
jit_gl_texture name [symbol] Causes the object to calculate fps and ms. The name attribute shows the texture
name.
(mouse) Clicking with the mouse lets you select the jit.fpsgui object's display mode.

Attributes
Name Type g/s Description
bgcolor float Sets the RGBA values for the data background color of the jit.fpsgui object's
display.
bgcolor2 float Sets the RGBA values for the mode background color of the jit.fpsgui object's
display.
bordercolor float Sets the RGBA values for the border color of the jit.fpsgui object's display.
dim int (get) Displays the current dimensions of the incoming matrices.
fps float (get) Displays the current fps (frames per second) rate of the incoming matrices.
htextcolor float Sets the RGBA values for the mode text color of the jit.fpsgui object's display.
interval int The sampling period, in milliseconds, used when calculating fps and ms (default =
100)
mode int Sets the display mode (default = 0 (fps))
def.:0 0 = fps
1 = ms
2 = matrix type
3 = matrix dimensions
4 = matrix planecount
5 = matrix name
'fps' = TEXT_HERE
'ms' = TEXT_HERE
'type' = TEXT_HERE
'dim' = TEXT_HERE
'planes' = TEXT_HERE
'name' = TEXT_HERE
ms float (get) Displays the number of milliseconds elapsed between incoming data.
name symbol (get) Displays the current name of the incoming matrices.
planecount int (get) Displays the current planecount of the incoming matrices.
textcolor float Sets the RGBA values for the data text color of the jit.fpsgui object's display.
timeout int The time interval, in milliseconds, after which the timer resets (default = 2000)
type symbol (get) Displays the current data type of the incoming matrices.
usetimeout int Sets the timeout flag (default = 1). When the flag is set, use of the timeout
attribute is enabled.

Information for box attributes common to all objects

Examples

See Also
Name Description
jit.matrixinfo Report matrix planecount, type, dimensions
jit.freeframe
Utilize FreeFrame effects

Description
Provides support for using FreeFrame effects within Jitter. It supports both single and dual input effects, and 32-bit and 16-bit
data sizes.

Matrix Operator
matrix inputs:2, matrix outputs:1
Name IOProc Planelink Typelink Dimlink Plane Dim Type
in2 resamp 1 1 1 4 1 char
out n/a 1 1 1 4 1 char

Information for Jitter Matrix Operator (MOP) messages and attributes to this object

Messages
anything If the message selector matches the name of a parameter, functions like the param
message, taking a single float (or symbol, in the case of text parameters)
argument.

If the message selector matches the word get, followed by the name of a
parameter (e.g. getbrightness, the message has the same effect as the getparam
message, but requiring no further arguments.
geteffectlist Sends a list out the object's right outlet comprising the names of all available
FreeFrame effects, preceded by the word effectlist. On Macintosh, FreeFrame
effects must be located either in the /Library/Application Support/FreeFrame/>
folder, or in a directory called FreeFrame Plugins , within the Max search path.
On Windows, FreeFrame effects must be located either in the C:\Program
Files\Common Files\FreeFrame\ folder, or in a directory called FreeFrame
Plugins , within the Max search path.
getparam param [symbol/int] Sends a list out the object's right outlet containing the current value of the
parameter specified by the param argument (either by name or by index into the
list returned by getparamlist). The list is formatted as param param param-val
param-display . The param argument is the name of the parameters, the param-
val the value, and param-display is an alternate display value, for parameters
whose "real value", as understood by the parameter, lies outside of the range 0-1.
getparamlist Sends lists out the object's right outlet describing the parameters for the currently
selected effect, one list per parameter (see numparams). The list or lists are in the
form paramlist param-name param-type .

All parameters, regardless of type (with the exception of text), accept a single
floating-point number between 0 and 1 as input.

The parameter types are: boolean, event, red, green, blue, xpos, ypos, text,
standard.

After all parameters have been listed, the message paramlist done is output.

loadeffect effect-name [symbol] Selects an available FreeFrame effect for use. The effect must be specified by its
name, as reported by the geteffectlist message.
param param [symbol/int] Sets the value of the parameter specified by the param argument (either by name
value [float/symbol] or by index into the list returned by getparamlist). All parameters, regardless of
type (with the exception of text), accept a single floating-point number between 0
and 1 as input. See the getparamlist message for additional information on
parameter types.
reload
Causes the object to rescan the FreeFrame plugins folders and add any new
plugins to its list of effects. See the geteffectlist method for more details.

Attributes
Name Type g/s Description
fx symbol The currently loaded effect
inmode symbol The matrix input mode (jitter/freeframe).
The inmode and outmode attributes provide an optimization when building chains
of jit.freeframe objects. Because Jitter and FreeFrame use different byte-padding,
matrices generally have to be copied to a new buffer when the arrive at a
jit.freeframe object, and copied back into a Jitter matrix after processing, before
output. If several jit.freeframe objects will be used to sequentially process data,
this copying step can be avoided.
The first object in the chain should have inmode set to jitter, and outmode set to
freeframe. All subsequent objects should have both attributes set to freeframe,
except for the last one, which should have inmode set to freeframe, and outmode
set to jitter.
numparams int (get) The number of parameters for the currently loaded effect (default = -1)
A value of -1 indicates that there is no loaded effect.
outmode symbol The matrix output mode (jitter/freeframe).
The inmode and outmode attributes provide an optimization when building chains
of jit.freeframe objects. Because Jitter and FreeFrame use different byte-padding,
matrices generally have to be copied to a new buffer when the arrive at a
jit.freeframe object, and copied back into a Jitter matrix after processing, before
output. If several jit.freeframe objects will be used to sequentially process data,
this copying step can be avoided.
The first object in the chain should have inmode set to jitter, and outmode set to
freeframe. All subsequent objects should have both attributes set to freeframe,
except for the last one, which should have inmode set to freeframe, and outmode
set to jitter.

Information for box attributes common to all objects

Examples

See Also
Name Description
jit.qt.effect QuickTime Effects for Jitter matrices
jit.gen
Generate new Jitter MOP objects

Description
Generates new Jitter MOP objects from a patcher and code expressions. The patcher and code describes how each cell of a
jit.matrix will be processed by the jit.gen object.

Matrix Operator
matrix inputs:-1, matrix outputs:1
Name IOProc Planelink Typelink Dimlink Plane Dim Type
out n/a 1 1 1 1 1 char long float32 float64

Information for Jitter Matrix Operator (MOP) messages and attributes to this object

Messages
anything TEXT_HERE
(drag) TEXT_HERE
(mouse) Double-click to open gen patcher
destroy Destroy the currently compiled kernel
compile Compile gen patcher
jit.gen TEXT_HERE
open Open gen patcher
param name [symbol] Set parameter values
values [list]
wclose Close gen patcher

Attributes
Name Type g/s Description
dirty int (get) Gen patcher needs to recompile
gen symbol Gen patcher name
def.:
precision symbol Gen patcher kernel precision
def.:auto 'auto' = Auto-choose precision
'fixed' = Fixed point precision
'float32' = Floating point precisions (32-bit)
'float64' = Floating point precisions (64-bit)
t symbol Gen patcher title
title symbol Gen patcher title

Information for box attributes common to all objects

Color
hsl2rgb: Convert HSL to RGB
rgb2hsl: Convert RGB to HSL

Comparison
!=, neq: Returns 1 if in1 does not equal in2, else returns zero.
!=p, neqp: Returns in1 if it does not equal in2, else returns zero.
<, lt: Returns 1 if in1 is lesser (in the positive direction) than in2, else returns zero.
<=, lte: Returns 1 if in1 is equal to or lesser (in the positive direction) than in2, else returns zero.
<=p, ltep: Returns in1 if in1 is equal to or lesser (in the positive direction) than in2, else returns zero.
<p, ltp: Returns in1 if in1 is lesser (in the positive direction) than in2, else returns zero.
==, eq: Returns 1 if in1 equals in2, else returns zero.
==p, eqp: Returns in1 if it equals in2, else returns zero.
>, gt: Returns 1 if in1 is greater (in the positive direction) than in2, else returns zero.
>=, gte: Returns 1 if in1 is equal to or greater (in the positive direction) than in2, else returns zero.
>=p, gtep: Returns in1 if in1 is equal to or greater (in the positive direction) than in2, else returns zero.
>p, gtp: Returns in1 if in1 is greater (in the positive direction) than in2, else returns zero.
max, maximum: The maximum of the inputs
min, minimum: The minimum of the inputs
step: Akin to the GLSL step operator: 0 is returned if in1 < in2, and 1 is returned otherwise.

Constant
constant: A constant value
degtorad, DEGTORAD: the constant pi/180
e, E: the constant e
f, float: A constant float value, or a conversion of the incoming value to float.
halfpi, HALFPI: the constant pi/2
i, int: A constant integer value, or a conversion of the incoming value to integer.
invpi, INVPI: the constant 1/pi
ln10, LN10: the constant ln10
ln2, LN2: the constant ln2
log10e, LOG10E: the constant log10e
log2e, LOG2E: the constant log2e
pi, PI: the constant pi
radtodeg, RADTODEG: the constant 180/pi
sqrt1_2, SQRT1_2: the constant 1/sqrt(2)
sqrt2, SQRT2: the constant sqrt(2)
twopi, TWOPI: the constant 2*pi

Coordinate
cell: Cell coordinates of input matrix [0, dim-1]
dim: Dimensions of input matrix
norm: Normalized coordinates of input matrix [0, 1]
snorm: Signed normalized coordinates of input matrix [-1, 1]

Declare
param, Param: Named parameters can be modified from the host object of the gen patcher. The first argument specifies the
name of the parameter, the second argument specifies the initial value.

Expression
expr: Evaluates GenExpr code. Standard mathematical operators (+, -, *, / etc.) and gen patcher operators can be used. See the
GenExpr documentation for more detail.

Input-output
in: Receive input into a gen patcher
out: Send output from a gen patcher

Logic
!, not: Zero input returns 1, any other value returns zero.
&&, and: Returns 1 if both in1 and in2 are nonzero.
^^, xor: Returns 1 if one of in1 and in2 are nonzero, but not both.
bool: Any nonzero value becomes 1, zero passes through.
or, ||: Returns 1 if either in1 and in2 are nonzero.

Math
!%, rmod: Reverse modulo (remainder of second input / first input)
!-, rsub: Reverse subtraction (subtract second input from first)
!/, rdiv: Reverse division (divide second input by first)
%, mod: Modulo inputs (remainder of first input / second input)
*, mul: Multiply inputs
+, add: Add inputs
-, sub: Subtract inputs
/, div: Divide inputs
absdiff: Compute the absolute difference between two inputs
cartopol: Convert Cartesian values to polar format. Angles are in radians.
neg: Negate input
poltocar: Convert polar values to Cartesian format. Angles are in radians.

Numeric
abs: Negative values will be converted to positive counterparts.
ceil: Round the value up to the next higher integer
floor, trunc: Round the value down to the next lower integer
fract: Return only the fractional component
sign: Positive input returns 1, negative input returns -1, zero returns itself.

Powers
exp: Raise the mathemtatical value e to a power
exp2: Raise 2 to a power
ln, log: The natural logarithm
log10: The logarithm base 10 of the input
log2: The logarithm base 2 of the input
pow: Raise in1 to the power of in2
sqrt: The square root of the input

Range
clamp, clip: Clamps the input value between specified min and max. Ranges are inclusive (both min and max values may be
output). If two arguments are given, they correspond to the min and max values respectively. If one argument is given, it is
assumed to correspond to the maximum value, while the minimum is set by the second inlet. If no arguments are given, min and
max are specified by the second and third inlets (defaulting to 0 and 1 respectively).
fold: Low and high values can be specified by arguments or by inlets. The default range is 0..1.
scale: Similar to the Max scale and MSP scale~ objects. Inputs are: 1) value to scale, 2) input lower bound, 3), input upper bound,
4) output lower bound, 5) output upper bound, 6) exponential curve. Default lower and upper bounds are zero and one; default
exponential curve is 1 (linear). No bound clamping is performed. The high and low values can be reversed for inverted mapping.
wrap: Low and high values can be specified by arguments or by inlets. The default range is 0..1.

Route
?, switch: Selects between the second and third inputs according to the Boolean value of the first: returns in2 if in1 is nonzero,
else returns in3. If one argument is given, it specifies the 'true' value (and the right inlet is the 'false' value). If two arguments are
given, they are the true and false values.
mix: Mixes (interpolates) between inputs a and b according to the value of the third input t, using linear interpolation. The factor
(t) should vary between 0 (for a) and 1 (for b). If one argument is given, it specifies the mix (interpolation) factor.
smoothstep: Smoothstep is a scalar interpolation function commonly used in computer graphics. The function interpolates
smoothly between two input values based on a third one that should be between the first two. The returned value is clamped
between 0 and 1. The slope (i.e. derivative) of the smoothstep function starts at 0 and ends at 0.

Sampling
nearest: Nearest neighbor sample a matrix at a given coordinate (normalized). Nearest has a boundmode attribute that can be
set to wrap, mirror or clamp.
sample: Sample a matrix at a given coordinate (normalized) with linear interpolation. Sample has a boundmode attribute that
can be set to wrap, mirror or clamp.

Surface
circle: Equation of a circle taking input coordinates ranging from [0, 1]
cone: Equation of a cone taking input coordinates ranging from [0, 1]
cylinder: Equation of a cylinder taking input coordinates ranging from [0, 1]
plane: Equation of a plane taking input coordinates ranging from [0, 1]
sphere: Equation of a sphere taking input coordinates ranging from [0, 1]
torus: Equation of a torus taking input coordinates ranging from [0, 1]

Trigonometry
acos: The arc cosine of the input (returns radians)
acosh: The inverse hyperbolic cosine of the input
asin: The arc sine of the input (returns radians)
asinh: The inverse hyperbolic sine of the input
atan: The arc tangent of the input (returns radians)
atan2: Returns the angle to the coordinate (in2, in1) in radians.
atanh: The inverse hyperbolic tangent of the input
cos: The cosine of the input (in radians)
cosh: The hyperbolic cosine of the input
degrees: convert radians to degrees
hypot: Returns the length of the vector to (in1, in2).
radians: convert degrees to radians
sin: The sine of the input (in radians)
sinh: The hyperbolic sine of the input
tan: The tangent of the input (in radians)
tanh: The hyperbolic tangent of the input

Vector
concat: Concatenate vector values into a larger vector
cross: Take the cross product of two vectors
dot: Take the dot product of two vectors
length: Get the length of a vector
normalize: Normalize of a vector to unit length
reflect: Reflect a vector off a surface defined by a normal
swiz: Unpack and remap vector components
vec: Pack scalar values into a vector

Waveform
noise: A random number generator

Examples
Generate new Jitter MOP objects

See Also
Name Description
jit.pix Generates Jitter mop pixel processing objects from a patcher.
jit.gl.pix Generates pixel processing shaders from a patcher
jit.gl.slab Process texture data
jit.op Apply binary or unary operators
jit.expr Evaluate an expression to fill a matrix
jit.matrix The Jitter Matrix!
gen~ Generate native audio signal processing routines
Gen Overview Gen Overview
GenExpr GenExpr
Gen Common Operators Gen Common Operators
Jitter Operators Jitter Operators
jit.gencoord
Evaluate a procedural basis function graph

Description
Generates spatial coordinates across a grid. The output matrix will contain coordinate dimensional values in each plane (eg. RGB
== XYZ)

Matrix Operator
matrix inputs:1, matrix outputs:1
Name IOProc Planelink Typelink Dimlink Plane Dim Type
out n/a 1 1 1 1 1 char long float32 float64

Information for Jitter Matrix Operator (MOP) messages and attributes to this object

Attributes
Name Type g/s Description
offset float The dimensional offsets to use for generating the spatial grid coordinates (only
valid when an input matrix is not attached). (default = 0)
scale float The dimensional scale factors to use for generating the spatial grid coordinates
(only valid when an input matrix is not attached). (default = 0)

Information for box attributes common to all objects

Examples

See Also
Name Description
jit.matrix The Jitter Matrix!
jit.bfg Evaluate a procedural basis function graph
Tutorial 39: Spatial Mapping Tutorial 39: Spatial Mapping
jit.gl.asyncread
Read back from an OpenGL framebuffer

Description
Uses Pixel Buffer Objects (PBOs) to perform asynchronous reads of the OpenGL context a high framerates. The performance gain
comes from using two pixel buffer objects in tandem to amortize the cost of the read operation over time without blocking other
rendering commands from executing as is typically the case when naive methods are used.

Information for Jitter 3D Object (OB3D) messages and attributes to this object

Arguments
None.

Attributes
Name Type g/s Description
matrixoutput int Output a copy of the frame buffer (OpenGL render context). The output matrix
dimensions adapt to the size of the window.
mode symbol Sets the reading mode. The available modes are:

split: Split reads a single frame in two passes and the output is concurrent.
interleaved: Interleaved reads an entire frame into each internal buffer, switching
buffers every other frame. In interleaved mode, the readback is delayed for one
frame.
out_name symbol (get) Returns the name of the internal frame buffer (OpenGL render context).

Information for box attributes common to all objects

Examples

See Also
Name Description
jit.gl.slab Process texture data
jit.gl.videoplane Display video in OpenGL
jit.gl.camera
Set a rendering view

Description
Sets the properties needed to define a view in OpenGL. These include field of view, clipping planes, and perspective or
orthographic projection modes. In addition a position and orientation can be defined for a virtual camera in 3D space, and the
proper view will be generated from these transforms.

Information for Jitter 3D Object (OB3D) messages and attributes to this object

Messages
getviewportray screen-x [int] Return 6 values representing the world-space endpoints of a ray cast from the
screen-y [int] screen-x and screen-y arguments.

Attributes
Name Type g/s Description
adapt int Adapt the capture texture dimensions to the context window size (default = 1).
capture int Capture to texture flag (default = 0)
colormask int Color mask values for red, green, blue, and alpha channels. When set to 0, the
corresponding color component is ignored by OpenGL. See glColorMask for more
detail.
dim int Capture texture dimensions, used when adapt = 0 (default = 256 256).
erase_color float Background color of viewport and capture texture (default = 0.2 0.2 0.2 1.)
far_clip float The far clipping plane distance in 3D world (default = 100.)
frustum float Camera frustum values (left, right, bottom, top, near, far). projection_mode must
be set to frustum for these values to have an effect.
lens_angle float The lens angle of the OpenGL camera (default = 45.)
locklook int Force the camera to remain pointed at the lookat value, ignoring orientation
messages and attributes (default = 0).
lookat float 3D position at which the camera is pointed (default = 0. 0. 0.)
near_clip float The near clipping plane distance in 3D world (default = 0.1)
ortho int Orthographic projection mode (default = 0)
0 = orthographic projection off (perspective projection)
1 = orthographic projection on, using lens angle
2 = orthographic projection on, ignoring lens angle
out_name symbol Capture texture name
projection_mode symbol Camera projection mode sets how the projection matrix is generated. In standard
mode, the camera uses the ortho setting an related attributes such as near, far,
lens_angle, etc. to generate the projection matrix. In frustum mode, only the
frustum attribute is used to calculate the projection matrix.
'standard' = TEXT_HERE
'frustum' = TEXT_HERE
tripod int Force the camera to orient itself as if mounted on a tripod. Y-axis turn values are
applied in world-space regardless of animmode (default = 0).
type symbol Capture texture type (default = auto)
'auto' = TEXT_HERE
'char' = TEXT_HERE
'long' = TEXT_HERE
'half' = TEXT_HERE
'float' = TEXT_HERE
'float16' = TEXT_HERE
'float32' = TEXT_HERE
viewport float Viewport coordinates which set the left, bottom, width, and height of the viewport
(default = 0. 0. 1. 1.)
vp_mode symbol Viewport coordinate mode (default = normalized). Determines if the viewport
values are absolute or normalized coordinates.
'normalized' = TEXT_HERE
'absolute' = TEXT_HERE

Information for box attributes common to all objects

Examples

See Also
Name Description
jit.gl.render Render Jitter OpenGL objects
jit.gl.sketch Use drawing commands with OpenGL
jit.anim.node Perform hierarchical transformation
jit.anim.drive Animate a 3D transform
jit.gl.cornerpin
Map textures in a window

Description
Provides controls for mapping textures and matrices to an output window by repositioning the image corners. Mouse input is
received from the context window allowing for easy manipulation of corner positions.

Information for Jitter 3D Object (OB3D) messages and attributes to this object

Messages
reset Reset corner position attributes
sendtexture name [symbol] Send the output texture a message
message [symbol]
values [list]

Attributes
Name Type g/s Description
colormode symbol Matrix color mode
'argb' = TEXT_HERE
'uyvy' = TEXT_HERE
corner_radius int Pixel size of corner GUI (default = 10)
cornermode symbol Mode to determine how corner attributes are used to set corner position (default =
relative)
'relative' = Normalized coords relative to window size
'absolute' = Absolute window coordinates
'absolute_texture' = Absolute coordinates based on texture dimensions
displaylist int Geometry displaylist flag (default = 1)
drawcorners int Corner GUI flag (default = 1)
enable_mouse int Mouse interaction flag (default = 1)
interp int Enable interpolation of input image (default = 1)
lower_left float Lower left corner position (default = 0 1)
lower_right float Lower right corner position (default = 1 1)
preserve_aspect int Preserve aspect ratio flag of input image (default = 0)
rect_tex int Enable rectangular textures (default = 1)
texturename symbol Internal texture name
upper_left float Upper left corner position (default = 0 0)
upper_right float Upper right corner position (default = 1 0)

Information for box attributes common to all objects

Examples
Map textures in a window

See Also
Name Description
jit.gl.render Render Jitter OpenGL objects
jit.gl.videoplane Display video in OpenGL
jit.gl.texture Create OpenGL textures
jit.gl.slab Process texture data
jit.gl.skybox Render a skybox in OpenGL
jit.gl.cubemap
Manage a cubemap texture target

Description
Maintains a cubemap texture target in an OpenGL context. It has 6 inputs -- one for each face of the cube. Cubemaps are typically
used to map an environment for material effects such as reflection and refraction.

Information for Jitter 3D Object (OB3D) messages and attributes to this object

Arguments
None.

Messages
bind Sets binding of the cubemap to texture geometry.
panorama_matrix Load a matrix formatted in a cross shape containing every face of the cubemap.
read Read in a panorama formatted image file.
unbind Unbinds the cubemap after a bind operation.

Attributes
Name Type g/s Description
bordercolor float Sets the texture bordercolor
edge_length int The length in pixels of a cube edge. Each face of the sube will be
edge_length*edge_length in dimension.
file symbol Sets an image file to read that is in panorama format
filter symbol Filter applied to the texture.
matrix_name symbol (get) The named matrix to access (default = none)
mipmap symbol Texture mipmap style.
wrap symbol Texture wrapping mode.

Information for box attributes common to all objects

Examples

See Also
Name Description
jit.gl.graph
Graph floats into 3D space

Description
Renders one-dimensional floating point data as a three-dimensional shape.

Information for Jitter 3D Object (OB3D) messages and attributes to this object

Attributes
Name Type g/s Description
circpoints int The number of circumference points to render for each cylindrical slice. For
example, a value of 1 will render a line, a value of 2 will render a planar area, a
value of 3 will render the geometry using triangular prisms, etc.
radial int Toggles radial mode enable/disable. When enabled, the incoming data is
visualized about the circumference of a circle.
radialphase float Sets a phase offset when radial mode is enabled.
radialradius float Sets the radius when radial mode is enabled

Information for box attributes common to all objects

Examples

See Also
Name Description
jit.buffer~ Access an MSP buffer~ in matrix form
jit.catch~ Transform signal data into matrices
jit.gl.gridshape Generate simple geometric shapes as a grid
jit.gl.handle Use mouse movement to control position/rotation
jit.gl.isosurf Generate a GL based surface extraction
jit.gl.mesh Generate GL geometry from matrices
jit.gl.model Read and draw various 3D model formats
jit.gl.nurbs Generate NURBS surface
jit.gl.plato Generate platonic solids
jit.gl.render Render Jitter OpenGL objects
jit.gl.shader Manage a GL shader
jit.gl.sketch Use drawing commands with OpenGL
jit.gl.slab Process texture data
jit.gl.text2d Render bitmap text
jit.gl.text3d Render vector text
jit.gl.texture Create OpenGL textures
jit.gl.videoplane Display video in OpenGL
jit.gl.volume Create a volume visualization
jit.graph Perform floating-point data visualization
jit.plot (x,y) plotting of a two-plane matrix
jit.gl.gridshape
Generate simple geometric shapes as a grid

Description
Creates one of several simple shapes (sphere, torus, cylinder, opencyclinder, cube, opencube, plane, circle) laid out on a connected
grid. These shapes may be either rendered directly, or sent out the leftmost outlet as a matrix of values.

Information for Jitter 3D Object (OB3D) messages and attributes to this object

Messages
(drag) Accepts a jitmtl material file and applies it to the shape.

Attributes
Name Type g/s Description
color float Color
dim int The dimensions of the grid (default = 20 20)
displaylist int Cache in displaylist flag (default = 0) This feature may be used to speed up
rendering time by creating and storing a list of gl drawing commands on the
graphics card. This will have no effect if matrixoutput turned on.
gridmode int Grid render mode (default = 0 (quadrilateral grid))
0 = quad_grid (quadrilateral grid)
1 = tri_grid (triangular grid)
matrixoutput int TEXT_HERE
'Off' = TEXT_HERE
'On' = TEXT_HERE
'On With Transform' = TEXT_HERE
rad_minor float The minor radius of a torus, if one is rendered or sent out as a matrix. (default =
0.25)
shape symbol The shape to be used (default = sphere) Supported shapes are:
sphere
torus
cylinder
opencyclinder
cube
opencube
plane
circle
'sphere' = TEXT_HERE
'torus' = TEXT_HERE
'cylinder' = TEXT_HERE
'opencylinder' = TEXT_HERE
'cube' = TEXT_HERE
'opencube' = TEXT_HERE
'plane' = TEXT_HERE
'circle' = TEXT_HERE
'cone' = TEXT_HERE
'capsule' = TEXT_HERE

Information for box attributes common to all objects

Examples
See Also
Name Description
jit.gl.graph Graph floats into 3D space
jit.gl.handle Use mouse movement to control position/rotation
jit.gl.isosurf Generate a GL based surface extraction
jit.gl.mesh Generate GL geometry from matrices
jit.gl.model Read and draw various 3D model formats
jit.gl.nurbs Generate NURBS surface
jit.gl.plato Generate platonic solids
jit.gl.render Render Jitter OpenGL objects
jit.gl.shader Manage a GL shader
jit.gl.sketch Use drawing commands with OpenGL
jit.gl.slab Process texture data
jit.gl.text2d Render bitmap text
jit.gl.text3d Render vector text
jit.gl.texture Create OpenGL textures
jit.gl.videoplane Display video in OpenGL
jit.gl.volume Create a volume visualization
Tutorial 32: Camera View Tutorial 32: Camera View
Tutorial 33: Polygon Modes, Tutorial 33: Polygon Modes, Colors and Blending
Colors and Blending
Tutorial 37: Geometry Under the Tutorial 37: Geometry Under the Hood
Hood
Tutorial 41: Shaders Tutorial 41: Shaders
Tutorial 42: Slab: Data Processing Tutorial 42: Slab: Data Processing on the GPU
on the GPU
jit.gl.handle
Use mouse movement to control position/rotation

Description
jit.gl.handle responds to mouse clicks and drags in the destination by generating rotate and position messages out its left outlet.

Information for Jitter 3D Object (OB3D) messages and attributes to this object

Messages
reset Returns jit.gl.handle and attached objects to the original viewing origin and
undoes all rotation.

Attributes
Name Type g/s Description
auto_handle int Enable/disable auto handle mode. When enabled the handle will perform mouse
picking to select 3D objects under the mouse. This mode is enabled by default
when the jit.gl.handle left inlet is unconnected.
auto_rotate int Continue spinning along last rotation when no UI input is present (default = 0)
auto_time int The time between automatic rotations for auto_rotate (default = 0)
hilite_color float Set the hilite color, used when select_mode is hilite (default = 1. 1. 0. 1.).
hover int Enable/disable mouse hovering (default = 0).
radius float The radius of control sphere in 3D world (default = 1.0)
rgb_axes int Sphere axis color flag (default = 1) When the flag is set, the sphere axes are drawn
in RGB colors, Otherwise, the color attribute determines the color used.
select_mode symbol Set the selection mode to use when auto_handle = 1 (default = none).
'none' = TEXT_HERE
'bounds' = TEXT_HERE
'wireframe' = TEXT_HERE
'hilite' = TEXT_HERE
'depth' = TEXT_HERE
tracking float The rotation amount relative to amount of mouse movement (default = 1.)
visible int Visibility flag (default = 1) When the flag is set, the sphere axes are visible in the
3D world.

Information for box attributes common to all objects

Examples
See Also
Name Description
jit.gl.graph Graph floats into 3D space
jit.gl.gridshape Generate simple geometric shapes as a grid
jit.gl.isosurf Generate a GL based surface extraction
jit.gl.mesh Generate GL geometry from matrices
jit.gl.model Read and draw various 3D model formats
jit.gl.nurbs Generate NURBS surface
jit.gl.plato Generate platonic solids
jit.gl.render Render Jitter OpenGL objects
jit.gl.shader Manage a GL shader
jit.gl.sketch Use drawing commands with OpenGL
jit.gl.slab Process texture data
jit.gl.text2d Render bitmap text
jit.gl.text3d Render vector text
jit.gl.texture Create OpenGL textures
jit.gl.videoplane Display video in OpenGL
jit.gl.volume Create a volume visualization
Tutorial 32: Camera View Tutorial 32: Camera View
Tutorial 36: 3D Models Tutorial 36: 3D Models
jit.gl.imageunit
Use Apple Image Units

Description
Loads any Apple Image Unit and permits the processing of incoming matrix and texture data, with resulting texture output,
similar to jit.gl.slab.

Information for Jitter 3D Object (OB3D) messages and attributes to this object

Messages
geteffectlist Sends the names of all the available Image Units out the right-most outlet.
getparam name [symbol] Sends the data values for the indicated shader parameter for the currently loaded
Image Unit out the right-most outlet. (synonym for getparamval)
getparamdefault name [symbol] Sends the default data values for the indicated shader parameter for the currently
loaded Image Unit out the right-most outlet.
getparamidentity name [symbol] Sends the data values to result in no effect for the indicated shader parameter for
the currently loaded Image Unit out the right-most outlet.
getparamlist Sends the names of all the currently loaded Image Unit parameters out the right-
most outlet.
getparammax name [symbol] Sends the recommended maximum value for the indicated parameter for the
currently loaded Image Unit out the right-most outlet.
getparammin name [symbol] Sends the recommended minimum value for the indicated parameter for the
currently loaded Image Unit out the right-most outlet.
getparamtype name [symbol] Sends the name of the datatype for the indicated parameter for the currently
loaded Image Unit out the right-most outlet.
getparamslidermax name [symbol] Sends the recommended maximum UI value for the indicated parameter for the
currently loaded Image Unit out the right-most outlet.
getparamslidermin name [symbol] Sends the recommended minimum UI value for the indicated parameter for the
currently loaded Image Unit out the right-most outlet.
getparamval name [symbol] Sends the data values for the indicated shader parameter for the currently loaded
Image Unit out the right-most outlet.
loadeffect name [symbol] Loads the given Image Unit.
param Sets a parameter of the imageunit (e.g., param param_name [list of param
values] ).
sendinput message [list] Sends the input jit.gl.texture object attached to the active inlet the corresponding
message.
sendoutput message [list] Sends the output jit.gl.texture object the corresponding message.
read name [symbol] Loads the given Image Unit. (synonym for loadeffect)

Attributes
Name Type g/s Description
thru int Thru mode flag (default = 1) When the flag is set, a matrix is output when another
one is received.
activeinput int Input number used for jit_matrix method (default = 0) Useful for multiple input
Image Units used from Java or JavaScript.
adapt int Enables or disables adapting and resizing to input source dimensions (default = 1).
colormode symbol The colorspace mode to use for each input textures (default = auto). Supported
modes are:
auto
luminance
intensity
depth
lumalpha
rgb
argb
uyvy
dim int The dimensions of the output jit.gl.texture object when adapt is disabled (default
= 256 256)
dimscale float Sets the scaling of output dims based on the object's leftmost input.
fx symbol Image Unit filter name (default = "Color Matrix") Possible choices are values
returned from geteffectlist. Similar to loadeffect method, but can be specified as
an attribute argument.
inputs int Input count (default = 2)
out_name symbol (get) Returns the name of the internal jit.gl.texture object.
paramsafe int Parameter limit flag (default = 0) Permits the limiting of parameter values to the
range specified by the Image Unit.
verbose int Verbose mode flag (default = 0) In verbose mode, the jit.gl.imageunit object will
print out messages useful for debugging.

Information for box attributes common to all objects

Examples

See Also
Name Description
jit.gl.graph Graph floats into 3D space
jit.gl.gridshape Generate simple geometric shapes as a grid
jit.gl.handle Use mouse movement to control position/rotation
jit.gl.isosurf Generate a GL based surface extraction
jit.gl.mesh Generate GL geometry from matrices
jit.gl.model Read and draw various 3D model formats
jit.gl.nurbs Generate NURBS surface
jit.gl.plato Generate platonic solids
jit.gl.shader Manage a GL shader
jit.gl.sketch Use drawing commands with OpenGL
jit.gl.slab Process texture data
jit.gl.text2d Render bitmap text
jit.gl.text3d Render vector text
jit.gl.texture Create OpenGL textures
jit.gl.videoplane Display video in OpenGL
jit.gl.volume Create a volume visualization
jit.gl.isosurf
Generate a GL based surface extraction

Description
Creates a geometric surface from a volumetric density field. The polygonization occurs at locations where the density values
intersect the edges of cells inside a subdivided cartesian grid.

Information for Jitter 3D Object (OB3D) messages and attributes to this object

Messages
(drag) TEXT_HERE

Attributes
Name Type g/s Description
autocolor symbol The autocolor mode for calculating vertex colors (default = normal) Supported
modes are:
none
normal (normal direction)
sample (density values)
autonormals int Enables or disables the calculation of normal directions used for calculating
lighting (default = 1).
dim int The dimensions of the subdivided grid (default = 20 20 20)
displaylist int Cache in displaylist flag (default = 0) This feature may be used to speed up
rendering time by creating and storing a list of gl drawing commands on the
graphics card. This will have no effect if matrixoutput turned on.
epsilon float The epsilon value used for determining the delta for sampling normal directions.
(default = 0.12)
isolevel float The density threshold for constructing the surface. (default = 1.0)
matrixoutput int TEXT_HERE
'Off' = TEXT_HERE
'On' = TEXT_HERE
'On With Transform' = TEXT_HERE
mode int The mode of subdivision (default = cubes) Supported modes are:
cubes
tetra

'cubes' = TEXT_HERE
'tetra' = TEXT_HERE

Information for box attributes common to all objects

Examples
See Also
Name Description
jit.gl.graph Graph floats into 3D space
jit.gl.gridshape Generate simple geometric shapes as a grid
jit.gl.handle Use mouse movement to control position/rotation
jit.gl.mesh Generate GL geometry from matrices
jit.gl.model Read and draw various 3D model formats
jit.gl.nurbs Generate NURBS surface
jit.gl.plato Generate platonic solids
jit.gl.render Render Jitter OpenGL objects
jit.gl.shader Manage a GL shader
jit.gl.sketch Use drawing commands with OpenGL
jit.gl.slab Process texture data
jit.gl.text2d Render bitmap text
jit.gl.text3d Render vector text
jit.gl.texture Create OpenGL textures
jit.gl.videoplane Display video in OpenGL
jit.gl.volume Create a volume visualization
jit.gl.light
Place a light source in a 3D scene

Description
Contains the properties needed to define a light source in OpenGL. These include light type (directional, point and spot), light
color, attenuation, and spot angle and falloff. In addition a position (for point and spot) and orientation (for directional and spot)
can be defined for a virtual light in 3D space.

Information for Jitter 3D Object (OB3D) messages and attributes to this object

Attributes
Name Type g/s Description
ambient float The color and opacity of the ambient light component in the form red green blue
opacity (default = 0. 0. 0. 1. (opaque black)) All values should be in the range 0.-1.
atten_const float The constant factor in the attenuation formula: 1.0 means never attenuate, 0.0 is
complete attenuation. The attenuation parameters determine how the light source
diminishes with distance.
atten_linear float The linear factor in the attenuation formula: 1 means attenuate evenly over the
distance. The attenuation parameters determine how the light source diminishes
with distance.
atten_quad float The quadratic factor in the attenuation formula: adds a curvature to the
attenuation formula. The attenuation parameters determine how the light source
diminishes with distance.
diffuse float The color and opacity of the diffuse light component in the form red green blue
opacity (default = 1. 1. 1. 1. (opaque white)) All values should be in the range 0.-1.
direction float Sets the direction the light points. Only applies to directional and spot lights.
lookat float TEXT_HERE
specular float Color and opacity of specular light component (default = 1. 1. 1. 1. (opaque white))
The first three floats in the range 0.-1. specify the RGB components of the specular
light color. The fourth float (also in the range 0.-1.) specifies opacity.
spot_angle float Defines the cone angle for spot type lights (default = 90)
spot_falloff float Defines the rate of falloff of the light from the center, to the edges of the cone
(default = 0). Only applies to spot type lights.
type symbol Light type
'point' = TEXT_HERE
'directional' = TEXT_HERE
'spot' = TEXT_HERE

Information for box attributes common to all objects

Examples
See Also
Name Description
jit.gl.render Render Jitter OpenGL objects
jit.gl.sketch Use drawing commands with OpenGL
jit.gl.material Generate materials for 3D objects
jit.gl.lua
Script OpenGL and Jitter with Lua.

Description
jit.gl.lua provides and interface to both OpenGL and Jitter through the Lua scripting language. jit.gl.lua is similar to the js object
for JavaScript.

Information for Jitter 3D Object (OB3D) messages and attributes to this object

Messages
int Send an int to the msg_int function.
float Send an int to the msg_float function.
list Send an int to the msg_list function.
anything Call a function with arbitrary arguments.
call Explicitly call a function with arbitrary arguments.
closebang TEXT_HERE
(mouse) Double-click to open Lua editing window
loadbang When the loadbang message is triggered, jit.gl.lua will look for a loadbang()
function in the currently running Lua script and call it.
open Opens the text window where the object's Lua source file can be edited.
read Read a Lua script
wclose Closes the text window where the object's Lua source file is edited.

Attributes
Name Type g/s Description
args symbol any symbols or numbers can be entered that will be assigned to the Lua variable
'args'. args[1] is the first typed-in argument.
autowatch int Enable autowatching of the loaded script file.
file symbol The file to load.
gc int Garbage collection flag.
inlets int The number of inlets.
last_inlet int (get) With scripts with multiple inlets, this attribute tracks what inlet was last used by
an incoming message, enabling scripts to generate different behavior depending on
what inlet a message is sent to.
matrixoutput int TEXT_HERE
'Off' = TEXT_HERE
'On' = TEXT_HERE
'On With Transform' = TEXT_HERE
outlets int The number of outlets.
path symbol (get) The path of the loaded script.

Information for box attributes common to all objects

Examples
See Also
Name Description
js Execute Javascript
jit.gl.sketch Use drawing commands with OpenGL
jit.gl.lua Overview jit.gl.lua Overview
jit.gl.lua OpenGL Bindings jit.gl.lua OpenGL Bindings
jit.gl.lua Color Bindings jit.gl.lua Color Bindings
jit.gl.lua Vector Math jit.gl.lua Vector Math
jit.gl.material
Generate materials for 3D objects

Description
Produces shaders for high quality rendering that automatically adapt to texture inputs and the number of active lights.

Matrix Operator
matrix inputs:0, matrix outputs:1
Name IOProc Planelink Typelink Dimlink Plane Dim Type
out n/a 1 1 1 1 1 char

Information for Jitter Matrix Operator (MOP) messages and attributes to this object

Information for Jitter 3D Object (OB3D) messages and attributes to this object

Messages
bind Bind the material for use
(drag) Drag and drop a Jitter material file
ambient_texture name [symbol] Set ambient texture
environment_texture name [symbol] Set the environment texture. The environment texture can be a jit.gl.texture or a
jit.gl.cubemap)
(mouse) Open the materials browser
diffuse_texture name [symbol] Set diffuse texture
emission_texture name [symbol] Set emission texture
getparamdefault name [symbol] Get parameter default value
getparamlist Get list of parameter names
getparamtype name [symbol] Get parameter type
getparamval name [symbol] Get the parameter value
heightmap_texture Set heightmap texture
glossmap_texture Set glossmap texture
normals_texture name [symbol] Set the normals texture. The normals texture will add a bump-mapping effect to
the material.
param name [symbol] Set material parameter value
values [list]
open TEXT_HERE
specular_texture name [symbol] Set specular texture
reset TEXT_HERE
reset_colors TEXT_HERE
reset_shading_model TEXT_HERE
unbind Unbind the material from use
wclose TEXT_HERE

Attributes
Name Type g/s Description
darkness float Material darkness. Only valid when the diffuse shading model is minnaert.
diffuse_model symbol Diffuse shading model
'lambert' = Lambertian diffuse shading model
'oren_nayer' = Oren-Nayer diffuse shading model
'toon' = Toon diffuse shading model
'minnaert' = Minnaert diffuse shading model
diffuse_size float Diffuse toon component size. Only valid when the diffuse shading model is toon.
diffuse_smooth float Diffuse toon component smoothness. Only valid when the diffuse shading model is
toon.
drawto symbol Render context name
fog symbol Fog type
'none' = No fog
'linear' = Linear fog
'exp' = Exponential fog
'exp2' = Squared exponential fog
override int Override jit.gl object color material attributes
roughness float Material roughness. Only valid when the diffuse shading model is oren_nayer.
specular_model symbol Specular shading model
'blinn' = Blinn specular shading model
'phong' = Phong specular shading model
'toon' = Toon specular shading model
'ward' = Ward specular shading model
'cook_torrance' = Cook-Torrance specular shading model
specular_size float Specular toon component size. Only valid when the specular shading model is
toon.
specular_smooth float Specular toon component smoothness. Only valid when the specular shading
model is toon.
type symbol (get) Material type (a descriptive name of the material).

Information for box attributes common to all objects

Examples

See Also
Name Description
jit.gl.cubemap Manage a cubemap texture target
jit.gl.model Read and draw various 3D model formats
jit.gl.render Render Jitter OpenGL objects
jit.gl.shader Manage a GL shader
jit.gl.texture Create OpenGL textures
jit.gl.mesh
Generate GL geometry from matrices

Description
Creates a geometric surface from a jit.matrix connected to the left-most inlet containing spatial coordinates. Additional geometry
can be specified by attaching other jit.matrix objects to the other inlets.

Information for Jitter 3D Object (OB3D) messages and attributes to this object

Messages
color_matrix Specifies a matrix of color values. This must be the same size as the matrix
specified by the vertex_matrix message, and can be a 3 or 4 plane matrix.
bind Binds the internal mesh buffers for drawing.
bitangent_matrix The word bitangent_matrix, followed by a symbol, specifies a matrix of bitangent
values. This must be the same size as the matrix specified by the vertex_matrix
message. It must be a 3 plane matrix.
(drag) Drag and drop a Jitter material file
edgeflag_matrix The word edgeflag_matrix, followed by a symbol, specifies a matrix of edge flag
values. This must be the same size as the matrix specified by the vertex_matrix
message. It must be a 1 plane matrix.
index_matrix The word index_matrix, followed by a symbol, specifies a matrix of indices. It can
be any size, but it must have 1 plane and be an integer matrix.
normal_matrix The word normal_matrix, followed by a symbol, specifies a matrix of normal
values. This must be the same size as the matrix specified by the vertex_matrix
message. It must be a 3 plane matrix.
reset The word reset resets all parameters to their default states.
texcoord_matrix The word texcoord_matrix, followed by a symbol, specifies a matrix of texture
coordinate values. This must be the same size as the matrix specified by the
vertex_matrix message. It can be a 2, 3, or 4 plane matrix.
specular_matrix The word specular_matrix, followed by a symbol, specifies a matrix of specular
values
tangent_matrix The word tangent_matrix, followed by a symbol, specifies a matrix of tangent
values. This must be the same size as the matrix specified by the vertex_matrix
message. It must be a 3 plane matrix.
vertex_attr_matrix The word vertex_attr_matrix, followed by a symbol, specifies a matrix of
arbitrary per-vertex data
vertex_matrix The word vertex_matrix, followed by a symbol, specifies a matrix of vertex values.
It can be 3 or 4 planes.
unbind Unbinds the internal mesh buffers after drawing.

Attributes
Name Type g/s Description
auto_bitangents int Enables or disables the calculation of bitangent (aka binormal) directions (only
available if texcoords and normals exist) (default = 0).
auto_colors int Enables or disables the calculation of vertex colors (default = 0).
auto_normals int Enables or disables the calculation of normal directions used for calculating
lighting (default = 1).
auto_tangents int Enables or disables the calculation of tangent directions (only available if
texcoords and normals exist) (default = 0).
cache_mode symbol
The mode to use for the geometry cache. (default = var) Supported modes are:
'auto' = TEXT_HERE
'vertexarray' = TEXT_HERE
'vertexbuffer' = TEXT_HERE
'displaylist' = TEXT_HERE
'none' = TEXT_HERE
color_mode symbol The mode to use for the calculating vertex colors. (default = position) Supported
modes are:
'vertex' = TEXT_HERE
'position' = TEXT_HERE
'texcoord' = TEXT_HERE
'normal' = TEXT_HERE
'tangent' = TEXT_HERE
'bitangent' = TEXT_HERE
'edgeflag' = TEXT_HERE
draw_mode symbol The mode to use for rendering the geometry. (default = tri_grid) Supported modes
are:
'tri_grid' = TEXT_HERE
'quad_grid' = TEXT_HERE
'points' = TEXT_HERE
'lines' = TEXT_HERE
'line_strip' = TEXT_HERE
'line_loop' = TEXT_HERE
'triangles' = TEXT_HERE
'tri_fan' = TEXT_HERE
'quads' = TEXT_HERE
'quad_strip' = TEXT_HERE
'polygon' = TEXT_HERE
'lines_adjacency' = TEXT_HERE
'line_strip_adjacency' = TEXT_HERE
'triangles_adjacency' = TEXT_HERE
'triangle_strip_adjacency' = TEXT_HERE
matrixoutput int TEXT_HERE
'Off' = TEXT_HERE
'On' = TEXT_HERE
'On With Transform' = TEXT_HERE

Information for box attributes common to all objects

Examples
See Also
Name Description
jit.gl.graph Graph floats into 3D space
jit.gl.gridshape Generate simple geometric shapes as a grid
jit.gl.handle Use mouse movement to control position/rotation
jit.gl.isosurf Generate a GL based surface extraction
jit.gl.model Read and draw various 3D model formats
jit.gl.nurbs Generate NURBS surface
jit.gl.plato Generate platonic solids
jit.gl.render Render Jitter OpenGL objects
jit.gl.shader Manage a GL shader
jit.gl.sketch Use drawing commands with OpenGL
jit.gl.slab Process texture data
jit.gl.text2d Render bitmap text
jit.gl.text3d Render vector text
jit.gl.texture Create OpenGL textures
jit.gl.videoplane Display video in OpenGL
jit.gl.volume Create a volume visualization
jit.gl.model
Read and draw various 3D model formats

Description
jit.gl.model Reads and draws a variety of 3D model formats, such as OBJ, Collada, and Blender. Only tessellated polygons are
drawn, and surfaces that are not tessellated are converted before drawing. Certain model formats, such as Collada, support
skinned animation.

Information for Jitter 3D Object (OB3D) messages and attributes to this object

Messages
(drag) Drag and drop model files
animenable anim-index Enable a model animation. If two arguments are provided, the first is the
(optional) [int] animation index to enable. Otherwise the current animation is used.
enable [int]
animloop anim-index Enable/disable looping on an animation. Looping on animations is enabled by
(optional) [int] default. If two arguments are provided, the first is the animation index to enable.
loop-enable Otherwise the current animation is used.
[int]
animlooppoints anim-index Set the loop points of an animation, if looping is currently enabled on that
(optional) [int] animation. If two arguments are provided, the first is the animation index to
loop-start enable. Otherwise the current animation is used.
[float]
loop-stop
[float]
animrate anim-index Set an animation's rate. If two arguments are provided, the first is the animation
(optional) [int] index, otherwise the current animation is used.
rate [float]
animreset anim-index Reset the state of an animation. Time is set to 0., rate to 1., weight to 1., and the
(optional) [int] loop points are set to the beginning and end of the animation. If two arguments
are provided, the first is the animation index to enable. Otherwise the current
animation is used.
animtime anim-index Jump to a specific time, in seconds, of an animation. If two arguments are
(optional) [int] provided, the first is the animation index, otherwise the current animation is used.
time [float]
animweight anim-index Set an animation's weight which determines how much influence the animation
(optional) [int] has on the affected mesh. If two arguments are provided, the first is the animation
weight [float] index, otherwise the current animation is used.
copynodestoclipboard Copy all nodes in the model as jit.anim.node objects, to the clipboard. When the
nodes are pasted in the patch, they will control the internal nodes of the model.
Make sure the name attribute is set before using this feature.
getbonenames Sends a list of the bones currently loaded in the model, if any, out the dumpout.
getanim_dict anim-index Send a description of the animation at anim-index as a dictionary out the
[int] dumpout.
getanimnames Sends a list of the scenes named animations out the dumpout. Some model files
don't support named animations, and therefore the names will not be sent, even
though animations are present.
getnodenames Sends a list of the scene nodes currently loaded in the model out the dumpout.
getmaterial_dict drawgroup Send a description of the drawgroup material as a dictionary out the dumpout. If
(optional) [int] no argument, use the current drawgroup attribute.
gettexnames Sends a list of all the textures currently loaded in the model out the dumpout.
nodebind model node Takes two args, the name of the node in the model to bind, and the name of an
name [symbol] jit.anim.node object to bind to.
jit.anim.node
name [symbol]
nodeanimenable model node Toggle the animation of the named node. If disabled, model animations will have
name [symbol] no effect on that node.
anim-enable
[int]
nodereset model node Resets the named node in the model to it's initial spatial transform state.
name [symbol]
nodesetinitial model node Sets the named nodes initial transform state to it's current transform.
name [symbol]
read Loads an model file from disk. The read message will attempt to find the model
file in the Max search path and load it. If no file name is specified, a file dialog box
is presented.
texgroup group-number The texgroup message is used to apply a named texture to a specific mesh within
[int] the model. The model's mesh-groups are specified in its model file. The texture
texture-name applied to a group will override any textures which have been applied to the object
[symbol] using the texture attribute, and textures loaded from the model file.
sendmaterial drawgroup [int] Send the internal material for drawgroup a message. See jit.gl.material for
message possible messages and attributes.
[symbol]
values [list]
sendtexture texture name Send the internal named texture a message. See jit.gl.texture for possible
[symbol] messages and attributes.
message
[symbol]
values [list]

Attributes
Name Type g/s Description
animblendmode int Determine how multiple enabled animations will be blended (default = 0 -
Average).
'Average' = Weights will be averaged to equal 1
'Cumulative' = Weights will be added and can go greater than 1
drawgroup int If non-zero, draw only one mesh. If zero, draw all mesh groups in the model
(default = 0).
drawskeleton int If enabled draw a wireframe representation of the bones in the model (default =
0).
file symbol Load a model file
find_instances int Mesh instance removal on import (default = 1). An optional post-processing step
when importing the model file. Instanced meshes are removed by referencing one
master.
fix_normals int Fix normals on import (default = 0). An optional post-processing step when
importing the model file. Tries to fix normal vectors that are facing inwards.
gen_normals int Generate normals on import (default = 1). An optional post-processing step when
importing the model file.
gen_tangents int Generate tangents on import (default = 1). An optional post-processing step when
importing the model file. Calculates tangents and bitangents if possible.
hasbones int (get) Indicates whether the loaded model has bone nodes.
material_mode int Mode for applying built-in material properties of a model. (default = 1 - Diffuse)
'Ignore (Inherit Colors From OB3D)' = TEXT_HERE
'Diffuse (Use Diffuse Only)' = TEXT_HERE
'All (Use All Color Values)' = TEXT_HERE
'JMTL (Use Jitter Material)' = TEXT_HERE
matrixoutput int TEXT_HERE
'Off' = TEXT_HERE
'On' = TEXT_HERE
'On With Transform' = TEXT_HERE
mode symbol Determines the method used to draw the model (default = var).
'displaylist' = Displaylist (not the fastest, but will work on any card)
'var' = Vertex Arrays
'vbo' = Vertex Buffer Objects
nodeaxes int If non-zero, draw a RGB axes at the location of all the nodes in the model.
normalize int Normalize model coordinates flag (default = 1). When enabled, the model is scaled
to the range (-1.,1.) for the x, y, and z axes.
numanimations int (get) Indicates the number of animations in the model.
numgroups int (get) Indicates the number of mesh groups. A mesh group consists of vertex data and
material data.
optimize int Optimize vertices and nodes on import (default = 1). An optional post-processing
step when importing the model file. Identical vertices are jointed to optimize
indexing, small meshes are joined if possible, and Nodes with no data assigned are
collapsed and joined.
smoothing_angle float Specifies the edge angle above which to smooth vertex normals (default = 89.)
verbose int Verbose mode flag (default = 0). If enabled, messages useful for debugging are
printed to the Max window.

Information for box attributes common to all objects

Examples

See Also
Name Description
jit.gl.mesh Generate GL geometry from matrices
jit.gl.render Render Jitter OpenGL objects
jit.gl.texture Create OpenGL textures
jit.gl.material Generate materials for 3D objects
jit.gl.camera Set a rendering view
Tutorial 36: 3D Models Tutorial 36: 3D Models
jit.gl.multiple
Create multiple object instances

Description
Uses several jit.matrix objects to repeatedly draw an instance of a jit.gl object like jit.gl.mesh or jit.gl.gridshape. It attaches to a
named instance of a jit.gl (OB3D) object provided by the name attribute.

Information for Jitter 3D Object (OB3D) messages and attributes to this object

Messages
(drag) Drag and drop a Jitter material file
color_matrix matrix name Specifies a named matrix to use for the color parameter if it's in the glparams list.
[symbol] Must be a 4-plane float32 matrix in RGBA format.
position_matrix matrix name Specifies a named matrix to use for the position parameter if it's in the glparams
[symbol] list. Must be a 3-plane float32 matrix.
rotate_matrix matrix name Specifies a named matrix to use for the rotate (angle-axis) parameter if it's in the
[symbol] glparams list. Must be a 4-plane float32 matrix.
rotatexyz_matrix matrix name Specifies a named matrix to use for the rotatexyz parameter if it's in the glparams
[symbol] list. Must be a 3-plane float32 matrix.
scale_matrix matrix name Specifies a named matrix to use for the scale parameter if it's in the glparams list.
[symbol] Must be a 3-plane float32 matrix.
tex_plane_s_matrix matrix name Specifies a named matrix to use for the tex_plane_s parameter if it's in the
[symbol] glparams list. Must be a 4-plane float32 matrix. The tex_map attribute of the
target gl object must be set to 1 or 3.
tex_plane_t_matrix matrix name Specifies a named matrix to use for the tex_plane_t parameter if it's in the
[symbol] glparams list. Must be a 4-plane float32 matrix. The tex_map attribute of the
target gl object must be set to 1 or 3.
texture_matrix matrix name Specifies a named matrix to use for the texture parameter if it's in the glparams
[symbol] list. Must be a char matrix.

Attributes
Name Type g/s Description
dimparam symbol The name of the input parameter to wrap all other input matrices to.
glparams symbol The list of OB3D attributes corresponding to object inlets that are modifiable by
passing in a matrix. Valid attributes are position, rotate (angle-axis), rotatexyz,
scale, color, and texture.
matrixoutput int TEXT_HERE
'Off' = TEXT_HERE
'On' = TEXT_HERE
'On With Transform' = TEXT_HERE
targetmode int Flag for draw mode. 1 = draw_raw, 0 = draw.
targetname symbol The name of the jit.gl object to attach to and draw multiple times.
texture symbol The list of textures that could potentially be bound to the OB3D object. The
specific texture can be specified by passing in a char matrix where the values of
the matrix index into the texture list.

Information for box attributes common to all objects

Examples
See Also
Name Description
jit.gl.graph Graph floats into 3D space
jit.gl.gridshape Generate simple geometric shapes as a grid
jit.gl.handle Use mouse movement to control position/rotation
jit.gl.isosurf Generate a GL based surface extraction
jit.gl.model Read and draw various 3D model formats
jit.gl.nurbs Generate NURBS surface
jit.gl.plato Generate platonic solids
jit.gl.render Render Jitter OpenGL objects
jit.gl.shader Manage a GL shader
jit.gl.sketch Use drawing commands with OpenGL
jit.gl.slab Process texture data
jit.gl.text2d Render bitmap text
jit.gl.text3d Render vector text
jit.gl.texture Create OpenGL textures
jit.gl.videoplane Display video in OpenGL
jit.gl.volume Create a volume visualization
jit.gl.node
Create hierarchical rendering groups

Description
Use jit.gl.node to construct hierarchical rendering groups. jit.gl.node creates sub-contexts of child objects that can be modified,
rendered, and captured together as a functional group.

Information for Jitter 3D Object (OB3D) messages and attributes to this object

Messages
draw Draw the node
sendoutput name [symbol] Send messages to the internal texture
message [symbol]
values [list]

Attributes
Name Type g/s Description
adapt int Adapt the capture texture dimensions to the context window size (default = 1).
capture int Capture to the internal texture. When enabled, all rendering is captured to texture
and the texture name is output out the left outlet. When disabled, rendering is
performed according to the parent context, which can be another jit.gl.node or a
jit.gl.render object.
dim int Internal texture dimensions
erase_color float Internal texture erase color
matrixoutput int TEXT_HERE
'Off' = TEXT_HERE
'On' = TEXT_HERE
'On With Transform' = TEXT_HERE
out_name symbol Internal texture name
type symbol Internal texture type
'auto' = TEXT_HERE
'char' = TEXT_HERE
'long' = TEXT_HERE
'half' = TEXT_HERE
'float' = TEXT_HERE
'float16' = TEXT_HERE
'float32' = TEXT_HERE

Information for box attributes common to all objects

Examples
See Also
Name Description
jit.gl.gridshape Generate simple geometric shapes as a grid
jit.gl.render Render Jitter OpenGL objects
jit.gl.texture Create OpenGL textures
jit.gl.nurbs
Generate NURBS surface

Description
Renders a Non-Uniform Rational B-Spline (NURBS) surface. A NURBS is a mathematical model that lets you represent virtually
any desired shape, from points, straight lines, and polylines to conic sections (circles, ellipses, parabolas, and hyperbolas) to free-
form curves with arbitrary shapes.

Information for Jitter 3D Object (OB3D) messages and attributes to this object

Messages
ctlmatrix matrix-name [symbol] Copies the named matrix to the control point matrix. Matrices must have a
planecount of 3 or 4, and should be typefloat32 or float64
rand Generates a random set of control points.

Attributes
Name Type g/s Description
closed int The closed flag for each axis in the form x y (default = 0 0). If closed about an
axis, the nurbs surface will knot to smoothly close the surface across that axis.
ctlshow int Control point rendering flag (default = 0) When the flag is set, the control points
are rendered.
dim int The dimensions of the grid (default = 20 20)
displaylist int Cache in displaylist flag (default = 0) This feature may be used to speed up
rendering time by creating and storing a list of gl drawing commands on the
graphics card. This will have no effect if matrixoutput turned on.
matrixoutput int TEXT_HERE
'Off' = TEXT_HERE
'On' = TEXT_HERE
'On With Transform' = TEXT_HERE
order int The interpolation order in the form x y (default = 3 3). The minimum
interpolation order is 1 1. The maximum order is set by the values (control; max =
control matrix width-1 height-1)

Information for box attributes common to all objects

Examples
See Also
Name Description
jit.gl.graph Graph floats into 3D space
jit.gl.gridshape Generate simple geometric shapes as a grid
jit.gl.handle Use mouse movement to control position/rotation
jit.gl.isosurf Generate a GL based surface extraction
jit.gl.mesh Generate GL geometry from matrices
jit.gl.model Read and draw various 3D model formats
jit.gl.plato Generate platonic solids
jit.gl.render Render Jitter OpenGL objects
jit.gl.shader Manage a GL shader
jit.gl.sketch Use drawing commands with OpenGL
jit.gl.slab Process texture data
jit.gl.text2d Render bitmap text
jit.gl.text3d Render vector text
jit.gl.texture Create OpenGL textures
jit.gl.videoplane Display video in OpenGL
jit.gl.volume Create a volume visualization
jit.gl.path
Generate and render a path in OpenGL

Description
The jit.gl.path object generates and renders a 3D path. See the jit.path object for more information on the underlying path
structure. The 3D visualization can be rendered as either a line, an extruded line (ribbon), an extruded circle (tube), or an
extruded 2D contour. The path stores 10 values: position x/y/z, color r/g/b/a, scale x/y, and orient angle.
For more information on how the extrusion is handled, see the GLE library: http://www.linas.org/gle

Information for Jitter 3D Object (OB3D) messages and attributes to this object

Messages
addcolor r [float] Add color values to the last point in the path.
g [float]
b [float]
a [float]
addcontour contour-vals [list] Set the contour to be used for pathstylecontour. The contour-vals are a list of X
and Y position values describing a contour in 2D space. A minimum of 4 are
required.
addorient orient [float] Add an orientation value to the last point in the path.
addscale scale-x [float] Add scale values to the last point in the path.
scale-y [float]
append x [float] Append point values to the end of the path.
y [float]
z [float]
r [float]
g [float]
b [float]
a [float]
scale-x [float]
scale-y [float]
orient [float]
clear Remove all points from the path
delete index [int] Delete the point at index
calchandles Calculate the path handles of each point in the path using the Catmull-Rom
method. This will overwrite any previously stored handles.
closepath Close the path by adding a point to the end equal to the first point.
edit index [int] Edit the point at index
x [float]
y [float]
z [float]
r [float]
g [float]
b [float]
a [float]
scale-x [float]
scale-y [float]
orient [float]
edithandle index [int] Edit the point handle at index
x [float]
y [float]
z [float]
r [float]
g [float]
b [float]
a [float]
scale-x [float]
scale-y [float]
orient [float]
gethandle index [int] Get handle values at index and output through dump outlet.
getpoint index [int] Get point values at index and output through dump outlet.
insert index [int] Insert a new point at index
x [float]
y [float]
z [float]
r [float]
g [float]
b [float]
a [float]
scale-x [float]
scale-y [float]
orient [float]
setcolor index [int] Set color values at index
r [float]
g [float]
b [float]
a [float]
setorient index [int] Set orientation value at index
orient [float]
setscale index [int] Set scale values at index
scale-x [float]
scale-y [float]

Attributes
Name Type g/s Description
autohandles int Enable the calculation of handle values every time the path is edited (default = 1).
closed int (get) Indicates the path is closed (first and last points are equal).
displaylist int Cache in displaylist flag (default = 0) This feature may be used to speed up
rendering time by creating and storing a list of gl drawing commands on the
graphics card.
drawhandles int Enable drawing of path handles, for debugging (default = 0).
endcap int Enable the closing of extruded path endpoints. (default = 0)
evalin float A parameter between 0 and 1 to determine where in the path rendering starts
(default = 0.).
evalout float A parameter between 0 and 1 to determine where in the path rendering ends
(default = 1.).
extrudescale float 2D scaling factor for extrusion contours in the form x y (default = 1. 1.).
interpmode symbol Path interpolation method (default = linear).
'linear' = Linear interpolation
'spline' = Hermite interpolation
joinstyle symbol Extrusion segment join method (default = angle). See the GLE library for more
information.
'raw' = TEXT_HERE
'angle' = TEXT_HERE
'cut' = TEXT_HERE
'round' = TEXT_HERE
normgen symbol Normal generation method for extruded paths (default = none). See the GLE
library for more information.
'none' = No generation
'facet' = Normal vector per facet
'edge' = Normal vectors lie along edges
'pathedge' = Normal vectors lie along edges and interpolate between segments
pathstyle symbol Path drawing method (default = line).
'line' = TEXT_HERE
'ribbon' = TEXT_HERE
'tube' = TEXT_HERE
'contour' = TEXT_HERE
pointcount int (get) Number of path points (default = 0).
segments int Number of segments between points (default = 20).
texscale float The 3D scaling factor for textures in the form x y z (default = 1. 1. 1.) .
texturemode int Texturing coord generation method for extruded paths (default = 1). See the GLE
library for more information.
'none' = No texture coord generation
'vertex_flat' = Vertex X is U, accumulated segment length is V
'normal_flat' = Normal vector X is U, accumulated segment length is V
'vertex_cylinder' = Vertex cylinder mapping for U, accumulated segment length for
V
'normal_cylinder' = Normal cylinder mapping for U, accumulated segment length
for V
'vertex_sphere' = Vertex sphere mapping
'normal_sphere' = Normal sphere mapping
'vertex_model_flat' = same as vertex_flat but with untransformed vertices
'normal_model_flat' = same as normal_flat but with untransformed vertices
'vertex_model_cylinder' = same as vertex_cylinder but with untransformed
vertices
'normal_model_cylinder' = same as normal_cylinder but with untransformed
vertices
'vertex_model_sphere' = same as vertex_sphere but with untransformed vertices
'normal_model_sphere' = same as normal_sphere but with untransformed
vertices

Information for box attributes common to all objects

Examples

Generate and render a path in OpenGL

See Also
Name Description
jit.path Evaluates a series of N-dim points as a path
jit.anim.path Evaluate a path of 3D transform points
jit.gl.sketch Use drawing commands with OpenGL
jit.gl.physdraw
A physics opengl debug drawer

Description
The jit.gl.physdraw object performs debug drawing of the objects in a physics simulation, including jit.phys.body,
jit.phys.multiple, and constraint objects such as jit.phys.hinge and jit.phys.6dof. A valid opengl context and a valid
jit.phys.world context are required for debug drawing of the physics world.

Information for Jitter 3D Object (OB3D) messages and attributes to this object

Attributes
Name Type g/s Description
constraintsize float Set the size for drawing contraints in the physics world (default = 2).
contactsize float Set the size for drawing contact points and vectors in the physics world (default =
6).
draw_aabb int Enable drawing of the physics object's aabb (axis-aligned bounding box) (default
= 0).
draw_bodies int Enable rigid body drawing (default = 1).
draw_worldbox int Enable worldbox drawing (default = 1).
rgb int Drawer color flag (default = 1). When the flag is set, drawer uses RGB colors.
Otherwise, the color attribute determines the color used.
worldname symbol The name of a jit.phys.world context this drawer is bound to.

Information for box attributes common to all objects

Examples

physics opengl debug drawer

See Also
Name Description
jit.phys.body A rigid body and collision shape
jit.phys.world Collision detection and rigid body dynamics
jit.phys.multiple Uses matrices to simulate multiple rigid bodies
jit.gl.picker
Mouse picking in an opengl context

Description
The jit.gl.picker object responds to mouse interaction in the destination by reporting the name of jit.gl (OB3D) objects
intersecting with the mouse.

Information for Jitter 3D Object (OB3D) messages and attributes to this object

Attributes
Name Type g/s Description
hover int Enable mouse hovering (default = 1)

Information for box attributes common to all objects

Examples

Mouse picking in an opengl context

See Also
Name Description
jit.phys.picker Constraint picking in a physics world
jit.gl.handle Use mouse movement to control position/rotation
jit.gl.pix
Generates pixel processing shaders from a patcher

Description
The jit.gl.pix object generates new pixel processing shaders from a patcher. jit.gl.pix is essentially a jit.gl.slab object whose
shader files are generated from jit.expr-like expressions that can be in either text or patcher form.

Information for Jitter 3D Object (OB3D) messages and attributes to this object

Messages
anything TEXT_HERE
(drag) Drag and drop a .genjit Gen patcher
(mouse) Open the Gen patcher
compile Compile the Gen patcher
dispose Disposes the currently loaded shader, passing the data through using the default
multi-texturing behavior.
dump TEXT_HERE
getparamdefault Sends the default data values for the indicated shader parameter for the internal
jit.gl.shader object out the right-most outlet.
getparamdescription Get a parameter description
getparamlist Sends the names of all the internal jit.gl.shader object shader parameters out the
right-most outlet.
getparamtype Sends the name of the datatype for the indicated shader parameter for the internal
jit.gl.shader object out the right-most outlet.
getparamval Sends the data values for the indicated shader parameter for the internal
jit.gl.shader object out the right-most outlet.
jit.gl.pix TEXT_HERE
open Open the Gen patcher
param Sets the given shader parameter with the given atom values as defined in a JXS
(Jitter shader) file.
read TEXT_HERE
sendinput Sends the input jit.gl.texture object attached to the active inlet the corresponding
message. An optional integer as a first argument lets one send the message to a
specific input (zero based, left to right).
sendoutput Sends the output jit.gl.texture object the corresponding message.
sendshader Sends the internal jit.gl.shader object the corresponding message.
wclose Close the Gen patcher

Attributes
Name Type g/s Description
thru int Thru mode flag (default = 1) When the flag is set, a matrix is output when another
one is received.
activeinput int Input number used for jit_matrix method (default = 0) Useful for multiple input
Image Units used from Java or JavaScript.
adapt int Enables or disables adapting and resizing to input source dimensions (default = 1).
def.:1
colormode symbol The colorspace mode to use for each input textures (default = auto). Supported
modes are:
auto
luminance
intensity
depth
lumalpha
rgb
argb
uyvy

'argb' = TEXT_HERE
'uyvy' = TEXT_HERE
depth float The depth or z-offset for the slab geometry. (default = 0.0)
dim int The dimensions of the output jit.gl.texture object when adapt is disabled (default
= 720 480)
dimscale float The dimension scaling factors of the output jit.gl.texture object when adapt is
enabled (default = 1. 1.). This is useful for upsampling or downsampling shaders
(such as uyvy conversion) which can adapt with the following logic:
output.dim[0] = input.dim[0]*dimscale[0];
output.dim[1] = input.dim[1]*dimscale[1];
dirty int (get) Gen patcher dirty flag
displaylist int Cache in displaylist flag (default = 0) This feature may be used to speed up
rendering time by creating and storing a list of gl drawing commands on the
graphics card. This will have no effect if matrixoutput turned on.
edges int Flags to enable or disable rendering each edge (only valid when shape == edges)
(default = 1 1 1 1)/
file symbol TEXT_HERE
gen symbol The name of the gen patcher to use.
def.:
inputs int Input count (default = 2)
out_name symbol (get) Returns the name of the internal jit.gl.texture object.
rect float The extent or rectangular coordinates bounding the slab geometry (default = 0 0 1
1)/
shape symbol The shape or geometry to render (default = cubes) Supported modes are:
quad
grid
edges
subdiv int The number of subdivisions to use for generating grid based geometry (only valid
when shape == grid) (default = 1 1)
t symbol Gen patcher title
texrect float The extent or rectangular coordinates bounding the texture coordinates for the
slab geometry (default = 0 0 1 1)/
title symbol Gen patcher title
type symbol The name of the datatype to use. (default = auto) Supported modes are:
auto (adapt to matrix datatype)
char (8bit unsigned byte)
long (32bit integer)
half (16bit float)
float (32bit float)
float16 (16bit float)
float32 (32bit float)

'auto' = TEXT_HERE
'char' = TEXT_HERE
'long' = TEXT_HERE
'half' = TEXT_HERE
'float' = TEXT_HERE
'float16' = TEXT_HERE
'float32' = TEXT_HERE
wrap int Flags to enable or disable wrapping along each edge (only valid when shape ==
edges) (default = 0 0 0 0)

Information for box attributes common to all objects

Color
hsl2rgb: Convert HSL to RGB
rgb2hsl: Convert RGB to HSL

Comparison
!=, neq: Returns 1 if in1 does not equal in2, else returns zero.
!=p, neqp: Returns in1 if it does not equal in2, else returns zero.
<, lt: Returns 1 if in1 is lesser (in the positive direction) than in2, else returns zero.
<=, lte: Returns 1 if in1 is equal to or lesser (in the positive direction) than in2, else returns zero.
<=p, ltep: Returns in1 if in1 is equal to or lesser (in the positive direction) than in2, else returns zero.
<p, ltp: Returns in1 if in1 is lesser (in the positive direction) than in2, else returns zero.
==, eq: Returns 1 if in1 equals in2, else returns zero.
==p, eqp: Returns in1 if it equals in2, else returns zero.
>, gt: Returns 1 if in1 is greater (in the positive direction) than in2, else returns zero.
>=, gte: Returns 1 if in1 is equal to or greater (in the positive direction) than in2, else returns zero.
>=p, gtep: Returns in1 if in1 is equal to or greater (in the positive direction) than in2, else returns zero.
>p, gtp: Returns in1 if in1 is greater (in the positive direction) than in2, else returns zero.
max, maximum: The maximum of the inputs
min, minimum: The minimum of the inputs
step: Akin to the GLSL step operator: 0 is returned if in1 < in2, and 1 is returned otherwise.

Constant
constant: A constant value
degtorad, DEGTORAD: the constant pi/180
e, E: the constant e
f, float: A constant float value, or a conversion of the incoming value to float.
halfpi, HALFPI: the constant pi/2
i, int: A constant integer value, or a conversion of the incoming value to integer.
invpi, INVPI: the constant 1/pi
ln10, LN10: the constant ln10
ln2, LN2: the constant ln2
log10e, LOG10E: the constant log10e
log2e, LOG2E: the constant log2e
pi, PI: the constant pi
radtodeg, RADTODEG: the constant 180/pi
sqrt1_2, SQRT1_2: the constant 1/sqrt(2)
sqrt2, SQRT2: the constant sqrt(2)
twopi, TWOPI: the constant 2*pi

Coordinate
cell: Cell coordinates of input matrix [0, dim-1]
dim: Dimensions of input matrix
norm: Normalized coordinates of input matrix [0, 1]
snorm: Signed normalized coordinates of input matrix [-1, 1]

Declare
param, Param: Named parameters can be modified from the host object of the gen patcher. The first argument specifies the
name of the parameter, the second argument specifies the initial value.

Expression
expr: Evaluates GenExpr code. Standard mathematical operators (+, -, *, / etc.) and gen patcher operators can be used. See the
GenExpr documentation for more detail.

Input-output
in: Receive input into a gen patcher
out: Send output from a gen patcher

Logic
!, not: Zero input returns 1, any other value returns zero.
&&, and: Returns 1 if both in1 and in2 are nonzero.
^^, xor: Returns 1 if one of in1 and in2 are nonzero, but not both.
bool: Any nonzero value becomes 1, zero passes through.
or, ||: Returns 1 if either in1 and in2 are nonzero.

Math
!%, rmod: Reverse modulo (remainder of second input / first input)
!-, rsub: Reverse subtraction (subtract second input from first)
!/, rdiv: Reverse division (divide second input by first)
%, mod: Modulo inputs (remainder of first input / second input)
*, mul: Multiply inputs
+, add: Add inputs
-, sub: Subtract inputs
/, div: Divide inputs
absdiff: Compute the absolute difference between two inputs
cartopol: Convert Cartesian values to polar format. Angles are in radians.
neg: Negate input
poltocar: Convert polar values to Cartesian format. Angles are in radians.

Numeric
abs: Negative values will be converted to positive counterparts.
ceil: Round the value up to the next higher integer
floor, trunc: Round the value down to the next lower integer
fract: Return only the fractional component
sign: Positive input returns 1, negative input returns -1, zero returns itself.

Powers
exp: Raise the mathemtatical value e to a power
exp2: Raise 2 to a power
ln, log: The natural logarithm
log10: The logarithm base 10 of the input
log2: The logarithm base 2 of the input
pow: Raise in1 to the power of in2
sqrt: The square root of the input

Range
clamp, clip: Clamps the input value between specified min and max. Ranges are inclusive (both min and max values may be
output). If two arguments are given, they correspond to the min and max values respectively. If one argument is given, it is
assumed to correspond to the maximum value, while the minimum is set by the second inlet. If no arguments are given, min and
max are specified by the second and third inlets (defaulting to 0 and 1 respectively).
fold: Low and high values can be specified by arguments or by inlets. The default range is 0..1.
scale: Similar to the Max scale and MSP scale~ objects. Inputs are: 1) value to scale, 2) input lower bound, 3), input upper bound,
4) output lower bound, 5) output upper bound, 6) exponential curve. Default lower and upper bounds are zero and one; default
exponential curve is 1 (linear). No bound clamping is performed. The high and low values can be reversed for inverted mapping.
wrap: Low and high values can be specified by arguments or by inlets. The default range is 0..1.

Route
?, switch: Selects between the second and third inputs according to the Boolean value of the first: returns in2 if in1 is nonzero,
else returns in3. If one argument is given, it specifies the 'true' value (and the right inlet is the 'false' value). If two arguments are
given, they are the true and false values.
mix: Mixes (interpolates) between inputs a and b according to the value of the third input t, using linear interpolation. The factor
(t) should vary between 0 (for a) and 1 (for b). If one argument is given, it specifies the mix (interpolation) factor.
smoothstep: Smoothstep is a scalar interpolation function commonly used in computer graphics. The function interpolates
smoothly between two input values based on a third one that should be between the first two. The returned value is clamped
between 0 and 1. The slope (i.e. derivative) of the smoothstep function starts at 0 and ends at 0.

Sampling
nearest: Nearest neighbor sample a matrix at a given coordinate (normalized). Nearest has a boundmode attribute that can be
set to wrap, mirror or clamp.
sample: Sample a matrix at a given coordinate (normalized) with linear interpolation. Sample has a boundmode attribute that
can be set to wrap, mirror or clamp.

Surface
circle: Equation of a circle taking input coordinates ranging from [0, 1]
cone: Equation of a cone taking input coordinates ranging from [0, 1]
cylinder: Equation of a cylinder taking input coordinates ranging from [0, 1]
plane: Equation of a plane taking input coordinates ranging from [0, 1]
sphere: Equation of a sphere taking input coordinates ranging from [0, 1]
torus: Equation of a torus taking input coordinates ranging from [0, 1]

Trigonometry
acos: The arc cosine of the input (returns radians)
acosh: The inverse hyperbolic cosine of the input
asin: The arc sine of the input (returns radians)
asinh: The inverse hyperbolic sine of the input
atan: The arc tangent of the input (returns radians)
atan2: Returns the angle to the coordinate (in2, in1) in radians.
atanh: The inverse hyperbolic tangent of the input
cos: The cosine of the input (in radians)
cosh: The hyperbolic cosine of the input
degrees: convert radians to degrees
hypot: Returns the length of the vector to (in1, in2).
radians: convert degrees to radians
sin: The sine of the input (in radians)
sinh: The hyperbolic sine of the input
tan: The tangent of the input (in radians)
tanh: The hyperbolic tangent of the input

Vector
concat: Concatenate vector values into a larger vector
cross: Take the cross product of two vectors
dot: Take the dot product of two vectors
length: Get the length of a vector
normalize: Normalize of a vector to unit length
reflect: Reflect a vector off a surface defined by a normal
swiz: Unpack and remap vector components
vec: Pack scalar values into a vector

Examples

Generates pixel processing shaders from a patcher

See Also
Name Description
jit.gen Generate new Jitter MOP objects
Generates pixel processing shaders from a patcher
jit.gl.slab Process texture data
jit.expr Evaluate an expression to fill a matrix
jit.matrix The Jitter Matrix!
gen~ Generate native audio signal processing routines
Gen Overview Gen Overview
GenExpr GenExpr
Gen Common Operators Gen Common Operators
Jitter Operators Jitter Operators
jit.gl.plato
Generate platonic solids

Description
Produces one of five platonic solids: tetrahedron, cube, octahedron, dodecahedron, or icosahedron.

Information for Jitter 3D Object (OB3D) messages and attributes to this object

Messages
(drag) Drag and drop a Jitter material file

Attributes
Name Type g/s Description
matrixoutput int TEXT_HERE
'Off' = TEXT_HERE
'On' = TEXT_HERE
'On With Transform' = TEXT_HERE
shape int The Platonic solid to be drawn (default = 1 (tetrahedron)) The solid may by
specified by name. The allowable names are tetrahedron, cube, octahedron,
dodecahedron, or icosahedron.

The solid may alternately be specified by number: 1 = tetrahedron 2 = cube 3 =


octahedron 4 = dodecahedron 5 = icosahedron

Information for box attributes common to all objects

Examples

See Also
Name Description
jit.gl.graph Graph floats into 3D space
jit.gl.gridshape Generate simple geometric shapes as a grid
jit.gl.handle Use mouse movement to control position/rotation
jit.gl.isosurf Generate a GL based surface extraction
jit.gl.mesh Generate GL geometry from matrices
jit.gl.model Read and draw various 3D model formats
jit.gl.nurbs Generate NURBS surface
jit.gl.render Render Jitter OpenGL objects
jit.gl.shader Manage a GL shader
jit.gl.sketch Use drawing commands with OpenGL
jit.gl.slab Process texture data
jit.gl.text2d Render bitmap text
jit.gl.text3d Render vector text
jit.gl.texture Create OpenGL textures
jit.gl.videoplane Display video in OpenGL
jit.gl.volume Create a volume visualization
Tutorial 34: Using Textures Tutorial 34: Using Textures
jit.gl.render
Render Jitter OpenGL objects

Description
Use jit.gl.render to render Jitter OpenGL objects to a rendering destination. jit.gl.render drives the rendering of 3D graphics,
setting up and invoking the drawing of each frame. jit.gl.render can draw to jit.window, jit.pwindow, and jit.matrix.

Information for Jitter 3D Object (OB3D) messages and attributes to this object

Messages
erase Erase the render destination contents
deletetexture texture name [symbol] Delete the named texture
depth_clear TEXT_HERE
depth_grab texture name [symbol] Copy the depth buffer to a named texture
draw_pixels matrix name [symbol] Draw the matrix as pixels
drawclients layer [int] Draw all automatic clients
drawswap Draw all automatic clients and swap buffers
jit_glchunk TEXT_HERE
interp Enable/Disable [int] Toggle interpolation for the currently selected named texture
line_loop Set the draw primitive to line loops
line_strip Set the draw primitive to line strips
lines Set the draw primitive to lines
points Set the draw primitive to points
quad_strip Set the draw primitive to quad strips
quads Set the draw primitive to quads
polygon Set the draw primitive to polygons
quad_grid Set the draw primitive to quad grids
point_sprite Set the draw primitive to point sprites
swap Swap rendering buffers
updateclients Update the render list
test Draws a set of SMPTE standard color bars
texture TEXT_HERE
sendtexture texture name [symbol] Send the named texture a message
message name [symbol]

message arguments
[list]
usetexture texture name [symbol] Use the named texture when drawing primitives
to_texture texture name [symbol] Copy the previously drawn frame to the named texture
tri_fan Set the draw primitive to triangle fans
tri_grid Set the draw primitive to triangle grids
tri_strip Set the draw primitive to triangle strips
triangles Set the draw primitive to triangles
screentoworld x [float] Converts screen coordinates to world coordinates, output out the dump outlet. The
y [float] input x and y input coordinates are in pixels, and the input z coordinate is in
z [float] normalized distance from camera (0.-1.), where 0. is the near clipping plane and 1.
is the far clipping plane.
worldtoscreen x [float] Converts world coordinates to screen coordinates
y [float]
z [float]

Attributes
Name Type g/s Description
accelerated int Enable hardware-accelerated rendering
aux_buffers int Number of auxiliary buffers available
camera float Camera position
copy_texture symbol Named texture to copy the framebuffer to
debug int Enable debugging
doublebuffer int Enable double buffering
draw_buffer symbol Drawing buffer
'default' = TEXT_HERE
'back' = TEXT_HERE
'front' = TEXT_HERE
'back_left' = TEXT_HERE
'back_right' = TEXT_HERE
'front_left' = TEXT_HERE
'front_right' = TEXT_HERE
'left' = TEXT_HERE
'right' = TEXT_HERE
'front_and_back' = TEXT_HERE
drawto symbol TEXT_HERE
erase_color float Erase color
erase_mode symbol Erase mode sets how jit.gl.render clears out the frame when the erase message is
sent. The default mode blends the previous frame with the next frame. The
clearcolor mode calls glClearColor with jit.gl.render's current erase_color value.
'default' = Frame blending
'clearcolor' = call to glClearColor
far_clip float Far clipping plane distance
fsaa int Enable Full-Scene Anti-Aliased drawing
geom_rows int Vertex connection mode (default = 0 (connect along columns))
0 = connect vertices in 2D geometry matrix along columns
1 = connect vertices in 2D geometry matrix along rows
lens_angle float Camera lens angle
light_ambient float Ambient lighting color
light_diffuse float Diffuse lighting color
light_global_ambient float Global ambient lighting color
light_position float Light position
light_specular float Specular lighting color
lookat float Camera lookat position
matrixoutput int TEXT_HERE
'Off' = TEXT_HERE
'On' = TEXT_HERE
'On With Transform' = TEXT_HERE
near_clip float Near clipping plane distance
point_atten float Point attenuation factor for point sprites
point_fade float Point fade threshold for point sprites
primitive symbol Current drawing primitive
quality int Enable quality rendering
shared_context symbol Context name to share resources with
stereo int Enable stereo rendering
sync int Enable vertical sync
up float Camera up vector
verbose int Enable printing messages to the Max window

Information for box attributes common to all objects

Examples

See Also
Name Description
jit.gl.graph Graph floats into 3D space
jit.gl.gridshape Generate simple geometric shapes as a grid
jit.gl.handle Use mouse movement to control position/rotation
jit.gl.isosurf Generate a GL based surface extraction
jit.gl.mesh Generate GL geometry from matrices
jit.gl.model Read and draw various 3D model formats
jit.gl.nurbs Generate NURBS surface
jit.gl.plato Generate platonic solids
jit.gl.shader Manage a GL shader
jit.gl.sketch Use drawing commands with OpenGL
jit.gl.slab Process texture data
jit.gl.text2d Render bitmap text
jit.gl.text3d Render vector text
jit.gl.texture Create OpenGL textures
jit.gl.videoplane Display video in OpenGL
jit.gl.volume Create a volume visualization
Tutorial 30: Drawing 3D text Tutorial 30: Drawing 3D text
Tutorial 31: Rendering Tutorial 31: Rendering Destinations
Destinations
Tutorial 32: Camera View Tutorial 32: Camera View
Tutorial 33: Polygon Modes, Tutorial 33: Polygon Modes, Colors and Blending
Colors and Blending
Tutorial 34: Using Textures Tutorial 34: Using Textures
Tutorial 35: Lighting and Fog Tutorial 35: Lighting and Fog
Tutorial 37: Geometry Under the Tutorial 37: Geometry Under the Hood
Hood
Tutorial 47: Using Jitter Object Tutorial 47: Using Jitter Object Callbacks in JavaScript
Callbacks in JavaScript
jit.gl.shader
Manage a GL shader

Description
Manages the process of compiling, binding and submitting a shader to OpenGL. A shader consists of both a vertex program and a
fragment (aka pixel) program, which can be defined in a.html shader description file (JXS), or submitted individually. Currently
the high level languages GLSL and CG, as well as ARB, and NV assembly programs are supported.

Information for Jitter 3D Object (OB3D) messages and attributes to this object

Messages
(drag) When a shader file is dragged from the Max 5 File Browser to a jit.gl.shader
object, the file will be loaded.
arb vpfile [symbol] Loads the given arb vertex and fragment programs from disk.
fpfile [symbol]
arbfp fpfile [symbol] Loads the given arb fragment program from disk.
arbvp vpfile [symbol] Loads the given arb vertex program from disk.
dispose Dispose of and unload the current shader.
dump type [symbol] Dumps the indicated shader data to the max console window. Valid types are
params, source, assembly.
cg vpfile [symbol] Loads the given cg vertex and fragment programs from disk.
fpfile [symbol]
cgfp fpfile [symbol] Loads the given cg fragment program from disk.
cgvp vpfile [symbol] Loads the given cg vertex program from disk.
bind Manually binds and compiles the shader object.
compile Manually compiles the shader object.
getparamdefault name [symbol] Sends the default data values for the indicated shader parameter out the right-
most outlet.
getparamdescription Get a parameter description
getparamlist Sends the names of all the shader parameters out the right-most outlet.
getparamtype name [symbol] Sends the name of the datatype for the indicated shader parameter out the right-
most outlet.
getparamval name [symbol] Sends the data values for the indicated shader parameter out the right-most outlet.
flush_cache Clears the shader cache which stores loaded programs that have been compiled in
order to minimize compile time for shaders that have already been compiled and
have not been modified on disk.
glsl vpfile [symbol] Loads the given glsl vertex and fragment programs from disk.
fpfile [symbol]
glslfp fpfile [symbol] Loads the given glsl fragment program from disk.
glslvp vpfile [symbol] Loads the given glsl vertex program from disk.
param Sets the given shader parameter with the given atom values as defined in a JXS
(Jitter shader) file.
program_param A geometry shader program parameter.
read filename [symbol] Loads the given JXS shader file from disk.

unbind Manually unbinds the shader object.

Attributes
Name Type g/s Description
compiler symbol The compiler to use for compiling shader programs. (default = native) Supported
compilers are:
native (native compiler in graphics driver)
internal (internal jitter compiler)
file symbol The shader description file (JXS) to use (default = none)
matrixoutput int TEXT_HERE
'Off' = TEXT_HERE
'On' = TEXT_HERE
'On With Transform' = TEXT_HERE
prefer symbol The language to prefer if multiple programs have been specified. (default = none)
Supported options are:
none
glsl
cg
arb
nv
shader symbol For internal use only.
verbose int Enables or disables verbose output to the max console window (default = 0).

Information for box attributes common to all objects

Examples

See Also
Name Description
jit.gl.graph Graph floats into 3D space
jit.gl.gridshape Generate simple geometric shapes as a grid
jit.gl.handle Use mouse movement to control position/rotation
jit.gl.isosurf Generate a GL based surface extraction
jit.gl.mesh Generate GL geometry from matrices
jit.gl.model Read and draw various 3D model formats
jit.gl.nurbs Generate NURBS surface
jit.gl.plato
Generate platonic solids
jit.gl.render Render Jitter OpenGL objects
jit.gl.sketch Use drawing commands with OpenGL
jit.gl.slab Process texture data
jit.gl.text2d Render bitmap text
jit.gl.text3d Render vector text
jit.gl.texture Create OpenGL textures
jit.gl.videoplane Display video in OpenGL
jit.gl.volume Create a volume visualization
Tutorial 41: Shaders Tutorial 41: Shaders
jit.gl.sketch
Use drawing commands with OpenGL

Description
Records and draws based on 3-D drawing commands. These commands range from simple turtle graphics to the majority of the
OpenGL API.

Information for Jitter 3D Object (OB3D) messages and attributes to this object

Messages
anything The jit.gl.sketch object accepts a list of drawing commands.
circle radius [float] Draws a circle with radius specified by radius and center point at the current
theta-start [float] drawing position. If theta-start and theta-end are specified, then an arc will be
drawn instead of a full circle. The theta-start and theta-end arguments are in
theta-end [float] terms of degrees (0-360). The current shapeorient and shapeslice values will
also affect the drawing.
cmd_delete mutex group Deletes index or all instances of the command specified by the command
index [int] argument from the command list.
command
[symbol]
endmutex group
cmd_enable mutex group Enables/disables command in the command list.
index [int]
command
[symbol]
endmutex group
0/1 [int]
cmd_insert index [int] Inserts command at position index in the command list.
command
[symbol]
command-args
[variable]
cmd_replace index [int] Replaces position index in the command list with command .
command
[symbol]
command-args
[variable]
dimorient The word dimorient followed by a zero or one, affects the drawmatrix command.
The default is 0.
drawmatrix Draws a matrix. The format of the message is
drawmatrix <matrixname> <drawing primitive> <texflag> <normalflag>
<colorflag>
texflag values are specified as follows: 0=use, 1=ignore, 2=auto
normalflag values are specified as follows: 0=use, 1=ignore, 2=auto
colorflag values are specified as follows: 0=use, 1=ignore
edgeflag values are specified as follows: 0=use, 1=ignore
drawobject The word drawobject, followed by a symbol that specifies an object name and a
0/1 flag that specifies whether or not to ignore the OB3D attributes, draws a
named jit.gl object.
cube scale-x [float] Draws a box with width 2* scale-x , height 2* scale-y , depth 2* scale-z , and
scale-y [float] center point at the current drawing position. If scale-y and scale-z are not
scale-z [float] specified, they will assume the same value as scale-x . The current shapeorient ,
shapeslice , and shapeprim values will also affect the drawing.
cylinder radius1 [float] Draws a cylinder with top radius specified by radius1 , bottom radius specified by
radius2 [float] radius2 , length specified by mag , and center point at the current drawing
mag [float] position. If theta-start and theta-end are specified, then a patch will be drawn
theta-start [float] instead of a full cylinder. The theta-start and theta-end arguments are in terms of
degrees (0-360). The current shapeorient, shapeslice, and shapeprim values
theta-end [float] will also affect the drawing.
beginstroke Begin definition of a stroked path of the style specified by a following stroke_style
argument. Currently supported stroke styles are "
basic2d
line
framecircle radius [float] Draws the circumference of the circle with radius specified by radius and center
theta-start [float] point at the current drawing position. If theta-start and theta-end are specified,
then an arc will be drawn instead of a full circle. The theta-start and theta-end
theta-end [float] arguments are in terms of degrees (0-360). The current shapeorient and
shapeslice values will also affect the drawing.
frameellipse radius1 [float] Draws the circumference of the ellipse specified by radius1 , radius2 and center
radius2 [float] point at the current drawing position. If theta-start and theta-end are specified,
theta-start [float] then an arc will be drawn instead of a full ellipse. The theta-start and theta-end
arguments are in terms of degrees (0-360). The current shapeorient and
theta-end [float] shapeslice values will also affect the drawing.
framequad x1 [float] Draws the frame of the quadrilateral specified by the four points x1 y1 z1 x2 y2 z2
y1 [float] x3 y3 z3 x4 y4 z4 .
z1 [float]
x2 [float]
y2 [float]
z2 [float]
x3 [float]
y3 [float]
z3 [float]
x4 [float]
y4 [float]
z4 [float]
frametri x1 [float] Draws the frame of the triangle specified by the three points x1 y1 z1 x2 y2 z2 x3
y1 [float] y3 z3 .
z1 [float]
x2 [float]
y2 [float]
z2 [float]
x3 [float]
y3 [float]
z3 [float]
ellipse radius1 [float] Draws the ellipse specified by radius1 , radius2 and center point at the current
radius2 [float] drawing position. If theta-start and theta-end are specified, then an arc will be
theta-start [float] drawn instead of a full ellipse. The theta-start and theta-end arguments are in
terms of degrees (0-360). The current shapeorient and shapeslice values will
theta-end [float] also affect the drawing.
endstroke Ends the definition of a stroked path and renders the path.
getcamera Returns the x, y, and z coordinates of the camera location.
getcmd_index index [int] Sends the command list item at index as a message out the object's right outlet.
getcmdlist Sends the command list as a series of messages out the object's right outlet. The
command list is bracketed by max messages that indicate the beginning and the of
the current command list, and the command list is output between these two lines,
one line per command. The output takes the form:
cmdlist_begin index
cmdlist index command-name command-arg1 ... command-argN
cmdlist index ....
cmdlist_end
glalphafunc Please see the OpenGL "Red Book" or "Blue Book" for more information.
glbegin draw-prim Please see the OpenGL "Red Book" or "Blue Book" for more information.
[symbol]
glbindprogram Please see the OpenGL "Red Book" or "Blue Book" for more information.
glbindtexture texture-name Please see the OpenGL "Red Book" or "Blue Book" for more information.
[symbol]
glblendfunc mutex group Please see the OpenGL "Red Book" or "Blue Book" for more information.
src-function-
name [symbol]
src-function-
number [int]
endmutex group
mutex group
dst-function-
name [symbol]
dst-function-
number [int]
endmutex group
glclear Please see the OpenGL "Red Book" or "Blue Book" for more information.
glclearcolor red [float] Please see the OpenGL "Red Book" or "Blue Book" for more information.
green [float]
blue [float]
alpha [float]
glcleardepth depth [float] Please see the OpenGL "Red Book" or "Blue Book" for more information.
glclipplane mutex group Please see the OpenGL "Red Book" or "Blue Book" for more information.
plane-name
[symbol]
plane-number
[int]
endmutex group
coefficient1
[float]
coefficient2
[float]
coefficient3
[float]
coefficient4
[float]
glcolor near [float] Please see the OpenGL "Red Book" or "Blue Book" for more information.
far [float]
glcolormask red [int] Please see the OpenGL "Red Book" or "Blue Book" for more information.
green [int]
blue [int]
alpha [int]
glcolormaterial mutex group Please see the OpenGL "Red Book" or "Blue Book" for more information.
face-name
[symbol]
face-number
[int]
endmutex group
lighting-mode
[sumbol]
glcullface mutex group Please see the OpenGL "Red Book" or "Blue Book" for more information.
face-name
[symbol]
face-number
[int]
endmutex group
gldepthmask 0/1 [int] Please see the OpenGL "Red Book" or "Blue Book" for more information.
gldepthrange Please see the OpenGL "Red Book" or "Blue Book" for more information.
gldisable capability Please see the OpenGL "Red Book" or "Blue Book" for more information.
[symbol]
gldrawpixels matrix-name Please see the OpenGL "Red Book" or "Blue Book" for more information.
[symbol]
gledgeflag 0/1 [int] Please see the OpenGL "Red Book" or "Blue Book" for more information.
glenable capability Please see the OpenGL "Red Book" or "Blue Book" for more information.
[symbol]
glend Please see the OpenGL "Red Book" or "Blue Book" for more information.
glfinish Please see the OpenGL "Red Book" or "Blue Book" for more information.
glflush Please see the OpenGL "Red Book" or "Blue Book" for more information.
glfog parameter-name Please see the OpenGL "Red Book" or "Blue Book" for more information.
[symbol]
parameter-value
[float]
glfrustum left [float] Please see the OpenGL "Red Book" or "Blue Book" for more information.
right [float]
bottom [float]
top [float]
near [float]
far [float]
glhint target [symbol] Please see the OpenGL "Red Book" or "Blue Book" for more information.
mode [symbol]
glget Please see the OpenGL "Red Book" or "Blue Book" for more information.
gllight mutex group Please see the OpenGL "Red Book" or "Blue Book" for more information.
light-name
[symbol]
light-number
[int]
endmutex group
parameter-name
[symbol]
parameter-
values [float list]
gllightmodel light-model Please see the OpenGL "Red Book" or "Blue Book" for more information.
[symbol]
values [float list]
gllinestipple factor [int] Please see the OpenGL "Red Book" or "Blue Book" for more information.
bit-pattern [int]
gllinewidth width [float] Please see the OpenGL "Red Book" or "Blue Book" for more information.
glloadidentity Please see the OpenGL "Red Book" or "Blue Book" for more information.
glloadmatrix matrix-name Please see the OpenGL "Red Book" or "Blue Book" for more information.
[symbol]
gllogicop opcode [symbol] Please see the OpenGL "Red Book" or "Blue Book" for more information.
glmaterial mutex group Please see the OpenGL "Red Book" or "Blue Book" for more information.
face-name
[symbol]
face-number
[int]
endmutex group
parameter-name
[symbol]
parameter-
values [float list]
glmatrixmode mutex group Please see the OpenGL "Red Book" or "Blue Book" for more information.
mode-name
[symbol]
mode-number
[int]
endmutex group
glmultmatrix matrix-name Please see the OpenGL "Red Book" or "Blue Book" for more information.
[symbol]
glnormal x [float] Please see the OpenGL "Red Book" or "Blue Book" for more information.
y [float]
z [float]
glortho left [float] Please see the OpenGL "Red Book" or "Blue Book" for more information.
right [float]
bottom [float]
top [float]
near [float]
far [float]
glpixeltransfer parameter-name Please see the OpenGL "Red Book" or "Blue Book" for more information.
[symbol]
parameter-value
[float]
glpixelzoom x-factor [float] Please see the OpenGL "Red Book" or "Blue Book" for more information.
y-factor [float]
glpointsize size [float] Please see the OpenGL "Red Book" or "Blue Book" for more information.
glpolygonmode mutex group Please see the OpenGL "Red Book" or "Blue Book" for more information.
face-name
[symbol]
face-number
[int]
endmutex group
mutex group
mode-name
[symbol]
mode-number
[int]
endmutex group
glpolygonoffset factor [float] Please see the OpenGL "Red Book" or "Blue Book" for more information.
units [float]
glpopattrib Please see the OpenGL "Red Book" or "Blue Book" for more information.
glpopmatrix Please see the OpenGL "Red Book" or "Blue Book" for more information.
glpushattrib Please see the OpenGL "Red Book" or "Blue Book" for more information.
glpushmatrix Please see the OpenGL "Red Book" or "Blue Book" for more information.
glrasterpos x [float] Please see the OpenGL "Red Book" or "Blue Book" for more information.
y [float]
z [float]
w [float]
glreadpixels matrix-name Please see the OpenGL "Red Book" or "Blue Book" for more information.
[symbol]
x [int]
y [int]
width [int]
height [int]
glrect x1 [float] Please see the OpenGL "Red Book" or "Blue Book" for more information.
y1 [float]
x2 [float]
y2 [float]
glrotate angle [float] Please see the OpenGL "Red Book" or "Blue Book" for more information.
x [float]
y [float]
z [float]
glscale x-scale [float] Please see the OpenGL "Red Book" or "Blue Book" for more information.
y-scale [float]
z-scale [float]
glscissor x [int] Please see the OpenGL "Red Book" or "Blue Book" for more information.
y [int]
width [int]
height [int]
glshademodel mutex group Please see the OpenGL "Red Book" or "Blue Book" for more info.
model-name
[symbol]
model-number
[int]
endmutex group
glunbindprogram Please see the OpenGL "Red Book" or "Blue Book" for more information.
gltexcoord s [float] Please see the OpenGL "Red Book" or "Blue Book" for more information.
t [float]
gltexenv parameter-name Please see the OpenGL "Red Book" or "Blue Book" for more information.
[symbol]
parameter-
values [float list]
gltexgen mutex group Please see the OpenGL "Red Book" or "Blue Book" for more information.
coordinate-name
[symbol]
coordinate-
number [int]
endmutex group
mutex group
parameter-name
[symbol]
parameter-
number [int]
endmutex group
parameter-
values [float list]
gltexparameter parameter-name Please see the OpenGL "Red Book" or "Blue Book" for more information.
[symbol]
parameter-
values [list]
gltranslate delta-x [float] Please see the OpenGL "Red Book" or "Blue Book" for more information.
delta-y [float]
delta-z [float]
glvertex x [float] Please see the OpenGL "Red Book" or "Blue Book" for more information.
y [float]
z [float]
glviewport x [int] Please see the OpenGL "Red Book" or "Blue Book" for more information.
y [int]
width [int]
height [int]
glulookat Please see the OpenGL "Red Book" or "Blue Book" for more information.
gluortho2d Please see the OpenGL "Red Book" or "Blue Book" for more information.
gluperspective Please see the OpenGL "Red Book" or "Blue Book" for more information.
glutessbegincontour Please see the OpenGL "Red Book" or "Blue Book" for more information.
glutessbeginpolygon Please see the OpenGL "Red Book" or "Blue Book" for more information.
glutessedgeflag 0/1 [int] Please see the OpenGL "Red Book" or "Blue Book" for more information.
glutessendcontour Please see the OpenGL "Red Book" or "Blue Book" for more information.
glutessendpolygon Please see the OpenGL "Red Book" or "Blue Book" for more information.
glutessnormal x [float] Please see the OpenGL "Red Book" or "Blue Book" for more information.
y [float]
z [float]
glutessmatrix matrix-name Draws a matrix using the tessellator as a set of vertices and colors. Dim 0
[symbol] represents a single vertex/color. Dim 1 represents a single contour. Dim 2
represents a single polygon.
glutessproperty property-name Please see the OpenGL "Red Book" or "Blue Book" for more information.
[symbol]
property-values
[list]
glutessvertex x [float] Please see the OpenGL "Red Book" or "Blue Book" for more information.
y [float]
z [float]
move delta-x [float] Moves the drawing position delta-x delta-y delta-z relative to the current drawing
delta-y [float] position.
delta-z [float]
moveto x [float] Moves the drawing position to the location specified by x y z .
y [float]
z [float]
line delta-x [float] Draws a line from the current drawing position to the location delta-x delta-y
delta-y [float] delta-z relative to the current drawing position.
delta-z [float]
lineto x [float] Draws a line from the current drawing position to the location specified by x y z .
y [float]
z [float]
linesegment x1 [float] Draws a line from the location specified by x1 y1 z1 to the location specified by x2
y1 [float] y2 z2 .
z1 [float]
x2 [float]
y2 [float]
z2 [float]
plane scale-x1 [float] Draws a plane with top width 2* scale-x1 , left height 2* scale-y1 , bottom width 2*
scale-y1 [float] scale-x2 , right height 2* scale-y2 , and center point at the current drawing
scale-x2 [float] position. If scale-y1 is not specified, it will assume the same value as scale-x1 . If
scale-y2 [float] scale-x2 and scale-y2 are not specified, they will assume the same values as scale-
x1 and scale-y1 respectively. The current shapeorient, shapeslice, and
shapeprim values will also affect the drawing.
point x [float] Draws a point at the location specified by x y z .
y [float]
z [float]
reset Delete all elements of the command list.
quad x1 [float] Draws the quadrilateral specified by the four points x1 y1 z1 x2 y2 z2 x3 y3 z3 x4
y1 [float] y4 z4 .
z1 [float]
x2 [float]
y2 [float]
z2 [float]
x3 [float]
y3 [float]
z3 [float]
x4 [float]
y4 [float]
z4 [float]
tri x1 [float] Draws the triangle specified by the three points x1 y1 z1 x2 y2 z2 x3 y3 z3 .
y1 [float]
z1 [float]
x2 [float]
y2 [float]
z2 [float]
x3 [float]
y3 [float]
z3 [float]
screentoworld The word screentoworld, followed by a pair of numbers that specify x and y
coordinates, returns an array containing the x , y , and z world coordinates
associated with a given screen pixel using the same the depth from the camera as
0,0,0. Optionally a third depth arg may be specified, which may be useful for hit
detection and other applications. The depth value is typically specified in the range
0.-1. where 0 is the near clipping plane, and 1. is the far clipping plane.
shapeorient rot-x [float] Sets the current orientation for shape drawing commands (circle, framecircle,
rot-y [float] ellipse, frameellipse, sphere, cylinder, torus, cube, and plane). The rot-x , rot-
rot-z [float] y , and rot-z arguments are in terms of degrees (0-360). The order in which the
orientation is applied is first rotate about x axis rot-x , then rotate about y axis
rot-y , and finally rotate about z axis rot-z .
shapeprim draw-prim Sets the current drawing primitive for shape drawing commands (circle,
[symbol] framecircle, ellipse, frameellipse, sphere, cylinder, torus, cube, and plane).
Valid values for draw-prim are:
lines
line_loop
line_strip
points
polygon
quads
quad_grid
quad_strip
triangles
tri_grid
tri_fan
tri_strip
shapeslice slice-a [int] Sets the current level of decimation (resolution) for shape drawing commands
slice-b [int] (circle, framecircle, ellipse, frameellipse, sphere, cylinder, torus, cube, and
plane).
sphere radius [float] Draws a sphere with radius specified by radius and center point at the current
theta1-start drawing position. If theta1-start , theta1-end , theta2-start , and theta2-end are
[float] specified, then a patch will be drawn instead of a full sphere. The theta1-start ,
theta1-end theta1-end , theta2-start , and theta2-end arguments are in terms of degrees (0-
[float] 360). The current shapeorient, shapeslice, and shapeprim values will also affect
theta2-start the drawing.
[float]
theta2-end
[float]
roundedplane The message roundedplane round_amount scale_x scale_y draws a rounded
plane with width 2 * scale_x , and height 2 * scale_y and center point at the
current drawing position. The size of the rounded portion of the plane is
determined by the round_amount argument. If scale_y is not specified, it will
assume the same value as scale_x .
torus radius1 [float] Draws a torus with major radius specified by radius1 , minor radius specified by
radius2 [float] radius1 , and center point at the current drawing position. If theta1-start , theta1-
theta1-start end , theta2-start , and theta2-end are specified, then a patch will be drawn
[float] instead of a full torus. The theta1-start , theta1-end , theta2-start , and theta2-
theta1-end end arguments are in terms of degrees (0-360). The current shapeorient,
[float] shapeslice, and shapeprim values will also affect the drawing.
theta2-start
[float]
theta2-end
[float]
strokeparam The word strokeparam, followed by a parameter name argument and a list of
parameter values, sets the current value of the parameter specified by the
parameter_name argument to be the value specified by parameter_value
argument(s). Some parameters are global for the extent of a stroked path
definition, while others may vary on a point by point basis.
strokepoint The word strokepoint, followed by three numbers that specify x , y , z
coordinates, defines an anchor point at the location specified by those coordinates.
Some stroke styles (such as basic2d) will ignore the z coordinate.
worldtoscreen The word worldtoscreen, followed by three numbers that specify x , y , z
coordinates, returns an array containing the x , y , and depth screen coordinates
associated with a given world coordinate. The depth value is typically specified in
the range 0.-1. where 0 is the near clipping plane, and 1. is the far clipping plane.

Attributes
Name Type g/s Description
autonormal int Automatically generate normals for tri and quad primitives (default = 0)
displaylist int Cache in a displaylist (default = 0)
immediate int Toggles immediate mode. When immediate mode is enabled, a message will be
executed when it is submitted rather than on draw.
pushstate int Toggles pushing all attributes on draw.

Information for box attributes common to all objects

Examples

See Also
Name Description
jit.gl.graph Graph floats into 3D space
jit.gl.gridshape Generate simple geometric shapes as a grid
jit.gl.handle Use mouse movement to control position/rotation
jit.gl.isosurf Generate a GL based surface extraction
jit.gl.mesh Generate GL geometry from matrices
jit.gl.model Read and draw various 3D model formats
jit.gl.nurbs Generate NURBS surface
jit.gl.plato Generate platonic solids
jit.gl.render Render Jitter OpenGL objects
jit.gl.shader Manage a GL shader
jit.gl.slab Process texture data
jit.gl.text2d Render bitmap text
jit.gl.text3d Render vector text
jit.gl.texture Create OpenGL textures
jit.gl.videoplane Display video in OpenGL
jit.gl.volume Create a volume visualization
Tutorial 40: Drawing in OpenGL Tutorial 40: Drawing in OpenGL using jit.gl.sketch
using jit.gl.sketch
jit.gl.skybox
Render a skybox in OpenGL

Description
The jit.gl.skybox object renders a skybox in a opengl world. A skybox is a cube that remains infinitely far away from the camera,
and gives the illusion of distant 3D surroundings. The jit.gl.cubemap object is used to texture the skybox.

Information for Jitter 3D Object (OB3D) messages and attributes to this object

Attributes
Name Type g/s Description
displaylist int Cache in displaylist flag (default = 0) This feature may be used to speed up
rendering time by creating and storing a list of gl drawing commands on the
graphics card.
infinite int When enabled the skybox is rendered at an infinite distance from the camera
(default = 1).

Information for box attributes common to all objects

Examples

See Also
Name Description
jit.gl.camera Set a rendering view
jit.gl.cubemap Manage a cubemap texture target
jit.gl.sketch Use drawing commands with OpenGL
jit.gl.slab
Process texture data

Description
Process texture data on the graphics card. jit.gl.slab performs general grid-based processing specified by shader programs.

Information for Jitter 3D Object (OB3D) messages and attributes to this object

Messages
(drag) Load a JXS shader file
dispose Dispose the current slab shader
dump type [symbol] Dump the slab shader data to the Max console window.
getparamdefault name [symbol] Report slab shader parameter's default value
getparamdescription Get a parameter description
getparamlist Report slab shader parameter names
getparamtype name [symbol] Report slab shader parameter's type
getparamval name [symbol] Report slab shader parameter's value
param name [symbol] Set a slab shader parameter value
message
[symbol]
values [list]
sendinput name [symbol] Send an input texture a message
message
[symbol]
values [list]
sendoutput name [symbol] Send the output texture a message
message
[symbol]
values [list]
sendshader name [symbol] Send the slab shader a message
message
[symbol]
values [list]
read filename [symbol] Load a JXS shader file

Attributes
Name Type g/s Description
thru int Enable thru mode
activeinput int The current number used for the jit_matrix method, which is useful for multiple
input filters used from Java or JavaScript.
adapt int Enable adapt to input
def.:1
colormode symbol Texture color mode
'argb' = TEXT_HERE
'uyvy' = TEXT_HERE
depth float Slab geometry depth
dim int Output dimensions
dimscale float The output dimension scaling factor of the output is useful for upsampling or
downsampling shaders.
output.dim = input.dim*dimscale
displaylist int Slab geometry uses displaylist
edges int Enable edge rendering
file symbol Slab shader file
inputs int Slab input count
out_name symbol (get) Output texture name
rect float Slab geometry rect
shape symbol Slab geometry shape
subdiv int The number of subdivisions to use for generating grid based geometry (only valid
when shape == grid)
texrect float Texture rectangle
type symbol Output texture type
'auto' = TEXT_HERE
'char' = TEXT_HERE
'long' = TEXT_HERE
'half' = TEXT_HERE
'float' = TEXT_HERE
'float16' = TEXT_HERE
'float32' = TEXT_HERE
wrap int Enable edge wrapping

Information for box attributes common to all objects

Examples

See Also
Name Description
jit.gl.graph Graph floats into 3D space
jit.gl.gridshape Generate simple geometric shapes as a grid
jit.gl.handle Use mouse movement to control position/rotation
jit.gl.isosurf Generate a GL based surface extraction
jit.gl.mesh Generate GL geometry from matrices
jit.gl.model Read and draw various 3D model formats
jit.gl.nurbs Generate NURBS surface
jit.gl.plato Generate platonic solids
jit.gl.render Render Jitter OpenGL objects
jit.gl.shader Manage a GL shader
jit.gl.sketch Use drawing commands with OpenGL
jit.gl.text2d Render bitmap text
jit.gl.text3d Render vector text
jit.gl.texture Create OpenGL textures
jit.gl.videoplane Display video in OpenGL
jit.gl.volume Create a volume visualization
Tutorial 42: Slab: Data Processing Tutorial 42: Slab: Data Processing on the GPU
on the GPU
jit.gl.text2d
Render bitmap text

Description
Draws bitmap text in the named drawing context. The text can be sent as a symbol, a list of symbols, or as a jit.matrix containing
char data. When a jit.matrix is used, each row of the matrix is interpreted as one line of text.

Information for Jitter 3D Object (OB3D) messages and attributes to this object

Messages
append text [list] Appends the specified symbol or list to the stored text string.
classic classic [int] Macintosh only
When classic mode is enabled, the characters are drawn using the glBitmap
mechanism in the OpenGL machine. This produces characters which are not
antialiased and cannot be rotated or scaled. On PC, this is the only supported
behavior, and there is no possibility to turn on/off.
face face-variant [list] Specifies the face variant of the current font. One or more face variants may be
specified. The supported font faces are normal, bold, and italic. Note that some
fonts do not contain different faces.
font fontname [symbol] Specifies the font in which to draw. An optional size parameter can follow the font.
size [int]
size size [int] Specifies the size in which to draw.
text text [list] Replaces the current text string with a symbol or list of symbols.

Attributes
Name Type g/s Description
align int Alignment for rows of text. (default = 0 (left))
0 = left
1 = center
2 = right
floatchomp int Toggles floating-point precision rounding.
floatplaces int When float point precision rounding is enabled set via the floatchomp attribute,
this value sets the precision of the number.
interp int Macintosh only
Controls whether interpolation is used to draw textures when not in classic mode.
(default = 1)
leadscale float The leading between multiple rows of text as a multiple of the standard leading.
(default = 1.)
plane int The plane of a multi-plane char input matrix which will be interpreted as text.
(default = 0)
screenmode int Macintosh only
If screenmode = 1, some 3D transformations are skipped so that pixel-accurate
text can be drawn. The origin of the text on screen is determined by the usual
projection of the object's position, but the text remains the same size. Rotation is
only applied around the z axis. Screenmode is useful for making fixed-size labels
which follow objects in space. With screenmode off, the text is transformed in
space in the usual way for an OB3D-group object. (default = 1)
tracking float The tracking (intra-character spacing) as a multiple of the standard tracking for
the face. (default = 1.)

Information for box attributes common to all objects


Examples

See Also
Name Description
jit.gl.graph Graph floats into 3D space
jit.gl.gridshape Generate simple geometric shapes as a grid
jit.gl.handle Use mouse movement to control position/rotation
jit.gl.isosurf Generate a GL based surface extraction
jit.gl.mesh Generate GL geometry from matrices
jit.gl.model Read and draw various 3D model formats
jit.gl.nurbs Generate NURBS surface
jit.gl.plato Generate platonic solids
jit.gl.render Render Jitter OpenGL objects
jit.gl.shader Manage a GL shader
jit.gl.sketch Use drawing commands with OpenGL
jit.gl.slab Process texture data
jit.gl.text3d Render vector text
jit.gl.texture Create OpenGL textures
jit.gl.videoplane Display video in OpenGL
jit.gl.volume Create a volume visualization
jit.gl.text3d
Render vector text

Description
Draws 3D text in the named drawing context. The text can be sent as a symbol, a list of symbols, or as a jit.matrix containing char
data. When a jit.matrix is used, each row of the matrix is interpreted as one line of text.

Information for Jitter 3D Object (OB3D) messages and attributes to this object

Messages
append text-to-append [list] Appends the specified symbol or list to the stored text string.
face face-variant [list] Specifies the face variant of the current font. One or more face variants may be
specified. The Supported font faces are normal, bold, italic, underline, outline,
shadow, condense, and extend.
font fontname [symbol] Specifies the font and size in which to draw.
size [int]
style Equivalent to face.
text text [list] Replace the current text string with a symbol or list of symbols.

Attributes
Name Type g/s Description
align int Text alignment mode (default = 0 (left))
0 = left
1 = center
2 = right
depth float The depth (z extent) of the 3D geometry relative to the height of the font (default =
0.) If a depth of 0 is used, no extruded character sides are generated, which will
draw much faster.
floatchomp int Toggles floating-point precision rounding.
floatplaces int When float point precision rounding is enabled set via the floatchomp attribute,
this value sets the precision of the number.
leadscale float The leading between multiple rows of text as a multiple of the standard leading.
(default = 1.)
matrixoutput int TEXT_HERE
'Off' = TEXT_HERE
'On' = TEXT_HERE
'On With Transform' = TEXT_HERE
plane int The plane of a multi-plane char input matrix which will be interpreted as text.
(default = 0)
precision float Sets the precision of the quadratic curve calculation [0 ->inf], The default is 1.0
tracking float The tracking (intra-character spacing) as a multiple of the standard tracking for
the face. (default = 1.)

Information for box attributes common to all objects

Examples
See Also
Name Description
jit.gl.graph Graph floats into 3D space
jit.gl.gridshape Generate simple geometric shapes as a grid
jit.gl.handle Use mouse movement to control position/rotation
jit.gl.isosurf Generate a GL based surface extraction
jit.gl.mesh Generate GL geometry from matrices
jit.gl.isosurf Generate a GL based surface extraction
jit.gl.mesh Generate GL geometry from matrices
jit.gl.model Read and draw various 3D model formats
jit.gl.nurbs Generate NURBS surface
jit.gl.plato Generate platonic solids
jit.gl.render Render Jitter OpenGL objects
jit.gl.shader Manage a GL shader
jit.gl.sketch Use drawing commands with OpenGL
jit.gl.slab Process texture data
jit.gl.text2d Render bitmap text
jit.gl.texture Create OpenGL textures
jit.gl.videoplane Display video in OpenGL
jit.gl.volume Create a volume visualization
Tutorial 30: Drawing 3D text Tutorial 30: Drawing 3D text
jit.gl.texture
Create OpenGL textures

Description
Creates OpenGL textures - buffers of image data used in drawing 3D geometry. jit.gl.texture is similar to jit.matrix except that
textures reside on the graphics card.

Information for Jitter 3D Object (OB3D) messages and attributes to this object

Messages
begin_capture Start texture capture
bind Bind the texture
end_capture End texture capture
read filename [symbol] Load image into texture
unbind Unbind the texture
tomatrix name [symbol] Update the named jit.matrix with the texture
subtex_matrix Submit a matrix as a subtexture

Attributes
Name Type g/s Description
thru int Enable thru mode
adapt int Adapt to input
anisotropy int Anisotropic filter width
apply symbol Texture apply mode
'auto' = TEXT_HERE
'replace' = TEXT_HERE
'decal' = TEXT_HERE
'modulate' = TEXT_HERE
'blend' = TEXT_HERE
'combine' = TEXT_HERE
autoclear int Auto-clear texture during capture
autoscale int Auto-scale texture coordinates
blendcolor float Texture blend color
bordercolor float Texture border color
capture_buffer symbol The capture buffer type when capture is enabled.
'color' = TEXT_HERE
'depth' = TEXT_HERE
capture_depthbits int Capture buffer depth bits
capture_source symbol Capture source buffer
colormode symbol Texture color mode
'auto' = TEXT_HERE
'alpha' = TEXT_HERE
'depth' = TEXT_HERE
'intensity' = TEXT_HERE
'luminance' = TEXT_HERE
'lumalpha' = TEXT_HERE
'rgb' = TEXT_HERE
'argb' = TEXT_HERE
'uyvy' = TEXT_HERE
compare_func symbol Shadow mapping comparison function
compare_mode symbol Shadow mapping comparison mode
compress symbol Texture compression mode
'none' = TEXT_HERE
'dxt1' = TEXT_HERE
'dxt3' = TEXT_HERE
'dxt5' = TEXT_HERE
correction symbol Texture compression mode
'fastest' = TEXT_HERE
'nicest' = TEXT_HERE
debug int Visual debug mode
defaultimage symbol Texture default image
'checker' = TEXT_HERE
'black' = TEXT_HERE
'white' = TEXT_HERE
dim int Texture dimensions
dstdimend int Matrix destination dimension end position
dstdimstart int name source dimension start position
erase_color float Capture erase color
file symbol Image or file to load
filter symbol Texture filter mode
'none' = TEXT_HERE
'nearest' = TEXT_HERE
'linear' = TEXT_HERE
flip int Flip texture
function symbol Texture multitexturing combine function
'replace' = TEXT_HERE
'modulate' = TEXT_HERE
'add' = TEXT_HERE
'addisgned' = TEXT_HERE
'subtract' = TEXT_HERE
'interpolate' = TEXT_HERE
'dot3rgb' = TEXT_HERE
'dot3rgba' = TEXT_HERE
matrixoutput int TEXT_HERE
'Off' = TEXT_HERE
'On' = TEXT_HERE
'On With Transform' = TEXT_HERE
mipmap symbol Enable mipmap interpolation
'none' = TEXT_HERE
'nearest' = TEXT_HERE
'linear' = TEXT_HERE
'bilinear' = TEXT_HERE
'trilinear' = TEXT_HERE
mode symbol Texture update mode
'dynamic' = TEXT_HERE
'static' = TEXT_HERE
'capture' = TEXT_HERE
offset int Texture submission offset
operand symbol Texture multitexturing operand
'color' = TEXT_HERE
'oneminuscolor' = TEXT_HERE
'alpha' = TEXT_HERE
'oneminusalpha' = TEXT_HERE
priority float Texture priority
rectangle int Enable texture rectangle mode
share int Enable texture sharing
source symbol The texture source targets to use for both source and destination textures (only
when apply == combine).
'texture' = TEXT_HERE
'color' = TEXT_HERE
'constant' = TEXT_HERE
'previous' = TEXT_HERE
srcdimend int Matrix source dimension end position
srcdimstart int Matrix source dimension start position
texgen symbol Texture coordinate generation mode
'none' = TEXT_HERE
'objectspace' = TEXT_HERE
'eyespace' = TEXT_HERE
'environment' = TEXT_HERE
'projected' = TEXT_HERE
texture_mode symbol Depth texture mode
'luminance' = TEXT_HERE
'intensity' = TEXT_HERE
'alpha' = TEXT_HERE
type symbol Texture type
'auto' = TEXT_HERE
'char' = TEXT_HERE
'long' = TEXT_HERE
'half' = TEXT_HERE
'float' = TEXT_HERE
'float16' = TEXT_HERE
'float32' = TEXT_HERE
usedstdim int Enable matrix destination dimension
usesrcdim int Enable matrix source dimension
weight int The weight factors for combining both source and destination textures (only when
apply == combine).
wrap symbol Texture wrap mode
'clamp' = TEXT_HERE
'repeat' = TEXT_HERE
'clampedge' = TEXT_HERE
'clampborder' = TEXT_HERE
'mirroredrepeat' = TEXT_HERE

Information for box attributes common to all objects

Examples
See Also
Name Description
jit.gl.graph Graph floats into 3D space
jit.gl.gridshape Generate simple geometric shapes as a grid
jit.gl.handle Use mouse movement to control position/rotation
jit.gl.isosurf Generate a GL based surface extraction
jit.gl.mesh Generate GL geometry from matrices
jit.gl.model Read and draw various 3D model formats
jit.gl.nurbs Generate NURBS surface
jit.gl.plato Generate platonic solids
jit.gl.render Render Jitter OpenGL objects
jit.gl.shader Manage a GL shader
jit.gl.sketch Use drawing commands with OpenGL
jit.gl.slab Process texture data
jit.gl.text2d Render bitmap text
jit.gl.text3d Render vector text
jit.gl.videoplane Display video in OpenGL
jit.gl.volume Create a volume visualization
Tutorial 42: Slab: Data Processing Tutorial 42: Slab: Data Processing on the GPU
on the GPU
jit.gl.videoplane
Display video in OpenGL

Description
Provides a quick way to show video in OpenGL. Unlike other Jitter OpenGL objects it also has video specific controls.

Information for Jitter 3D Object (OB3D) messages and attributes to this object

Messages
sendtexture name [symbol] Send the output texture a message
message [symbol]
values [list]

Attributes
Name Type g/s Description
client_storage int Enable client storage
colormode symbol Matrix color mode
'argb' = TEXT_HERE
'uyvy' = TEXT_HERE
dim int Geometry grid dimensions
displaylist int Geometry displaylist flag
gridmode int Geometry grid render mode
interp int Enable interpolation
matrixoutput int TEXT_HERE
'Off' = TEXT_HERE
'On' = TEXT_HERE
'On With Transform' = TEXT_HERE
nudge float Texture nudge factor
rect_tex int Enable rectangular textures
tex_offset_x float Texture x-offset
tex_offset_y float Texture y-offset
tex_scale_x float Texture x-scale
tex_scale_y float Texture y-scale
texturename symbol Internal texture name

Information for box attributes common to all objects

Examples
See Also
Name Description
jit.gl.graph Graph floats into 3D space
jit.gl.gridshape Generate simple geometric shapes as a grid
jit.gl.handle Use mouse movement to control position/rotation
jit.gl.isosurf Generate a GL based surface extraction
jit.gl.mesh Generate GL geometry from matrices
jit.gl.model Read and draw various 3D model formats
jit.gl.nurbs Generate NURBS surface
jit.gl.plato Generate platonic solids
jit.gl.render Render Jitter OpenGL objects
jit.gl.shader Manage a GL shader
jit.gl.sketch Use drawing commands with OpenGL
jit.gl.slab Process texture data
jit.gl.text2d Render bitmap text
jit.gl.text3d Render vector text
jit.gl.texture Create OpenGL textures
jit.gl.volume Create a volume visualization
Tutorial 42: Slab: Data Processing Tutorial 42: Slab: Data Processing on the GPU
on the GPU
jit.gl.volume
Create a volume visualization

Description
Creates a transparent volume from a volumetric density field. This process is GL accelerated by using graphics hardware.

Information for Jitter 3D Object (OB3D) messages and attributes to this object

Attributes
Name Type g/s Description
bounds int Flag which enables or disables the rendering of the bounding box surrounding the
volume (default = 0).
clip int Flag for enabling a controllable clip plane to slice the volume along an arbitrary
axis (default = 0)
clipangle float Rotation angles per axis for the clip plane (default = 0 0 0)
clipaxis float Axis coefficients for the clip plane (default = 1 0 0)
cubes int Flag which enables or disables cube subdivision (default = 1).
density float The density threshold for constructing the surface. (default = 0.5)
displaylist int Cache in displaylist flag (default = 0) This feature may be used to speed up
rendering time by creating and storing a list of gl drawing commands on the
graphics card. This will have no effect if matrixoutput turned on.
distance float The distance offset from the camera. (default = -5)
ds float Step size in raycast mode
exposure float Exposure in raycast mode
intensity float The intensity scale factor for multiplying against volume density values. (default =
0.5)
mode symbol Rendering mode
'slices' = TEXT_HERE
'raycast' = TEXT_HERE
raycast_adapt int Raycast mode adapts resolution to rendering destination
raycast_dim int Resolution of raycast mode
samples int Number of samples in raycast mode
slices int Sets he number of slices used as proxies for rendering the volume data.

Information for box attributes common to all objects

Examples
See Also
Name Description
jit.gl.graph Graph floats into 3D space
jit.gl.gridshape Generate simple geometric shapes as a grid
jit.gl.handle Use mouse movement to control position/rotation
jit.gl.isosurf Generate a GL based surface extraction
jit.gl.mesh Generate GL geometry from matrices
jit.gl.model Read and draw various 3D model formats
jit.gl.nurbs Generate NURBS surface
jit.gl.plato Generate platonic solids
jit.gl.render Render Jitter OpenGL objects
jit.gl.shader Manage a GL shader
jit.gl.sketch Use drawing commands with OpenGL
jit.gl.slab Process texture data
jit.gl.text2d Render bitmap text
jit.gl.text3d Render vector text
jit.gl.texture Create OpenGL textures
jit.gl.videoplane Display video in OpenGL
jit.glop
Produce feedback with gain staging

Description
Performs feedback on either the input matrix or the output matrix, and provides a gain stage for control.

Matrix Operator
matrix inputs:1, matrix outputs:1
Name IOProc Planelink Typelink Dimlink Plane Dim Type
out n/a 1 1 1 1 1 char long float32 float64

Information for Jitter Matrix Operator (MOP) messages and attributes to this object

Attributes
Name Type g/s Description
gain float The per-plane gain factor for feedback (default = 1.)
mode int Feedback mode (default = 0 (feedback output))
0 = perform feedback on output matrix
1 = perform feedback on input matrix
'Apply to Output' = TEXT_HERE
'Apply to Input' = TEXT_HERE

Information for box attributes common to all objects

Examples

See Also
Name Description
jit.op Apply binary or unary operators
jit.wake Feedback with convolution stage
jit.glue
Glue many matrices into one

Description
Composites multiple input matrices together as if they were rectangular pieces of a whole.

Matrix Operator
matrix inputs:-1, matrix outputs:1
Name IOProc Planelink Typelink Dimlink Plane Dim Type
out n/a 1 1 0 1 1 char long float32 float64

Information for Jitter Matrix Operator (MOP) messages and attributes to this object

Attributes
Name Type g/s Description
syncinlet int The inlet number which will cause the jit.glue object to output a new composite
matrix when a matrix is received at the specified inlet (default = 0)
A value of -1 will cause the object to output a new matrix in response to a matrix
received at all inlets
columns int The number of columns to use when gluing the matrix together (default = 1)
If you specify the columns attribute in the object box, The number of inlets will be
equal to the number of rows multiplied by the number of columns. If you change
the rows * columns attributes later, the size of the split regions will change, but
the number of inlets will not change.
rows int The number of rows to use when gluing the matrix together (default = 1)
If you specify the rows attribute in the object box, The number of inlets will be
equal to the number of rows multiplied by the number of columns. If you change
this value later you will change the compositing effect, but the number of inlets
will not change.

Information for box attributes common to all objects

Examples
See Also
Name Description
jit.concat Concatenate two matrices
jit.demultiplex Demultiplex (deinterleave) one matrix into two
jit.matrix The Jitter Matrix!
jit.multiplex Multiplex (interleave) two matrices into one matrix
jit.scissors Cut up a matrix into evenly spaced sub matrices
jit.split Split a matrix into two matrices
Tutorial 13: Scissors and Glue Tutorial 13: Scissors and Glue
jit.grab
Digitize video from an external source

Description
Use the jit.grab object to digitize video from any video digitizer and decompress the signal into a Jitter matrix. On OSX,
QuickTime is used; on Windows, DirectX is used.

Matrix Operator
matrix inputs:1, matrix outputs:1
Name IOProc Planelink Typelink Dimlink Plane Dim Type
out n/a 1 1 1 4 1 char

Information for Jitter Matrix Operator (MOP) messages and attributes to this object

Messages
defaults Restores digitizer image control defaults.
close Closes an open sequence grab component. The component is automatically closed
when the object is freed.
exportimage filename [symbol] Export the current frame as an image file with the name specified by the first
file-type [symbol] argument. The second argument sets the file type (default = png). Available file
use-dialog [int] types are png, bmp, jpeg, macpaint, photoshop, pict, qtimage, sgi, tga and
tiff. An optional use-dialog argument of 1 will open a File dialog to allow you to
enter the image file settings.
You can use the Max Preferences to specify a default image resolution.
getinputlist Reports the list of available inputs to the video digitizer from the object's right
outlet, preceded by the word inputlist. Note that the digitizer must be open in
order for this method to function.
getsnddevlist Reports the list of available sound digitizers from the object's right outlet,
preceded by the word snddevlist.
getsndinputlist Reports the list of available inputs for the current sound digitizer from the object's
right outlet, preceded by the word sndinputlist. Note that the digitizer must be
open in order for this method to function.
getvdevlist Reports the list of available video digitizers from the object's right outlet, preceded
by the word vdevlist.
open Opens a sequence grab component. A component must be explicitly opened before
the jit.qt.grab object will began digitizing.
settings Opens the standard video digitizer settings dialog box.
snd_settings Opens the standard sound digitizer settings dialog box.
stop Stops grabbing to disk.
write videofilename [symbol]
Starts grabbing to disk. If the write_split attribute is disabled, only one filename
audiofilename [symbol] argument is required; Otherwise, the video and audio filenames are required. If no
filename arguments are supplied, a file dialog box will open.
FPS [float]
codec [symbol] The default FPS is 30. frames/sec.
spatialquality [symbol] The default codec is raw. The following list of codecs is deprecated (retained for
temporalquality reference). See codeclist for the preferred method to list valid system codecs.
[symbol] Supported codecs are raw, cinepak, graphics, animation, video, componentvideo,
keyframes [symbol] jpeg, mjpega, mjpegb, sgi, planarrgb, macpaint, gif, photocd, qdgx, avrjpeg,
opendmljpeg, bmp, winraw, vector, qd, h261, h263, dvntsc, dvpal, dvpropal, flc,
targa, png, tiff, componentvideosigned, componentvideounsigned, cmyk,
microsoft, sorenson, indeo4, argb64, rgb48, alphagrey32, grey16, mpegyuv420,
yuv420, sorensonyuv9 and mpeg4.

The default spatialquality and temporalquality values are max. Supported quality
settings are lossless, max, min, low, normal, and high. Note that minimum quality
is, in many cases, the codec's default quality. Use "low" quality for consistent
results.

The default keyframes is 0, which will cause keyframes to be inserted


automatically, as necessary.

Attributes
Name Type g/s Description
bitrate int The sound digitizer bit depth (default = digitizer-specific)
8 = digitize sound at 8-bit resolution
16 = digitize sound at 16-bit resolution
brightness float The video digitizer brightness level (default = digitizer-specific)
channels int The sound digitizer channel selection (default = digitizer-specific)
1 = digitize sound in mono
2 = digitize sound in stereo
colormode symbol The output matrix's color encoding (default = argb)
'argb' = ARGB (alpha, red, green, blue) colormode
'uyvy' = UYVY (YUV 4:2:2 packed) colormode
contrast float The video digitizer contrast level (default = digitizer-specific)
dropreport int Dropped frames reporting flag (default = 0 (disabled))
When this flag is set, the message dropped will be sent from the rightmost outlet
of the jit.qt.grab object, followed by the number of dropped frames, whenever
frame-dropping is detected.
dstrect int The portion of the output matrix used for decompressing media to the internal
matrix. (default = 0 0 (matrix width) (matrix height))
The proportions of the rectangle are expressed in the form left top right bottom .
All values are relative to the top left corner of the viewing area of the output
matrix.
gamma float The video digitizer gamma (default = digitizer-specific)
hue float The video digitizer hue adjustment (default = digitizer-specific)
input int The current video digitizer input (default = digitizer-specific)
interp int Image interpolation flag (default = 0)
samplerate int Sound digitizer sample rate (default = digitizer-specific)
48000 = 48kHz
44100 = 44.1kHz
32000 = 32kHz
22050 = 22.050kHz
22254 = 22kHz
16000 = 16kHz
11127 = 11kHz
11025 = 11.025kHz
8000 = 8000 Hz
saturation float Video digitizer saturation level (default = digitizer-specific)
sharpness float Video digitizer sharpness level (default = digitizer-specific)
snddevice int The current sound digitizer (default = 0)
srcrect int Source rect from digitizer frame (default = 0 0 (matrix width) (matrix height))
unique int Unique frame filter flag (default = 0 (disabled))
When the flag is set, only new frames from the digitizer are output when the
object receives a bang. If no new frame has been received from the digitizer, the
jit.qt.grab object will not respond to the bang.
usedstrect int Destination rect flag (default = 0) When the flag is set, the dstrect attributes are
used when copying an input matrix to the internal matrix.
usesrcrect int Source rect flag (default = 0) When the flag is set, the srcrect attributes are used
when copying an input matrix to the internal matrix.
vdevice int The current video digitizer (default = 0)
write_audio int Audio track write flag (default = 0) When the flag is set, an audio track is written
when grabbing images to disc.
write_video int Video track write flag (default = 1) When the flag is set, a video track is written
when grabbing images to disc.

Information for box attributes common to all objects

Examples

See Also
Name Description
jit.qt.effect QuickTime Effects for Jitter matrices
jit.qt.grab Digitize video from an external source
jit.dx.grab Digitize video using DirectX (Windows)
jit.qt.movie Play or edit a QuickTime movie
jit.qt.record Record a QuickTime movie
jit.dx.videoout Output video to DirectX (Windows)
jit.qt.videoout Output video to QuickTime video output component
Tutorial 21: Working With Live Tutorial 21: Working With Live Video and Audio Input
Video and Audio Input
jit.gradient
Generate Chebyshev gradients

Description
Generates a 4-plane char matrix containing a gradient curve that runs along the horizontal axis (i.e. it smoothly fades from left to
right). You can select the cell values to fade between as well as Chebyshev coefficients to generate more complex curves and
ripples.

Matrix Operator
matrix inputs:1, matrix outputs:1
Name IOProc Planelink Typelink Dimlink Plane Dim Type
out n/a 1 1 1 4 1 char

Information for Jitter Matrix Operator (MOP) messages and attributes to this object

Attributes
Name Type g/s Description
cheby float A list of Chebyshev coefficients to generate the curve for the gradient (default = 1.)
end float The cell value for the end of the gradient (default = 1. 1. 1. 1.)
start float The cell value for the start of the gradient (default = 0. 0. 0. 0.)

Information for box attributes common to all objects

Examples

See Also
Name Description
jit.alphablend Blend two images with an alpha channel image
jit.charmap Map 256-point input to output
Tutorial 12: Color Lookup Tables Tutorial 12: Color Lookup Tables
jit.graph
Perform floating-point data visualization

Description
Renders floating point data as a two-dimensional plot.

Matrix Operator
matrix inputs:1, matrix outputs:1
Name IOProc Planelink Typelink Dimlink Plane Dim Type
out n/a 1 1 1 4 2 char

Information for Jitter Matrix Operator (MOP) messages and attributes to this object

Attributes
Name Type g/s Description
brgb int Three chars represent the red, green and blue values of the background color to
render
clearit int If non-zero the cells of the matrix will be cleared to the brgb color before
rendering.
frgb int Four chars represent the alpha, red, green and blue values of the color to render
height int The height of the output matrix (default=240)
mode int Five different modes are possible: mode 0 renders points, mode 1 renders lines,
mode 2 renders area between the float value and the horizontal axis at 0.0, and
mode 3 renders the area in a bipolar way (reflected in the horizontal axis). Unlike
the other modes, which all expect one-dimensional matrices, mode 4 expects a two
dimensional matrix, with one row of upper and one row of lower values, which it
then renders as vertical bars, coloring the space between the lower and upper
values.
'Points' = TEXT_HERE
'Lines' = TEXT_HERE
'Area' = TEXT_HERE
'Bi-Polar Area' = TEXT_HERE
'Bar' = TEXT_HERE
rangehi float The floating point value to map to the top of the graph (default=1.0)
rangelo float The floating point value to map to the bottom of the graph (default=-1.0)

Information for box attributes common to all objects

Examples
See Also
Name Description
jit.gl.graph Graph floats into 3D space
jit.buffer~ Access an MSP buffer~ in matrix form
jit.catch~ Transform signal data into matrices
jit.peek~ Read matrix data as an audio signal
jit.poke~ Write an audio signal into a matrix
jit.release~ Transforms matrix data into signals
peek~ Read and write sample values
poke~ Write sample values to a buffer by index
Tutorial 48: Frames of MSP Tutorial 48: Frames of MSP signals
signals
jit.grgb2argb
Convert GRGB to ARGB

Description
Converts a 4-plane char GRGB (green left, red, green right, blue) matrix into a 4-plane char ARGB (alpha, red, green, blue)
matrix. A default alpha channel (all on) is added and horizontal dimension is doubled for the output to account for this half red
and blue chroma, macro pixel input format.

Matrix Operator
matrix inputs:1, matrix outputs:1
Name IOProc Planelink Typelink Dimlink Plane Dim Type
out n/a 1 1 0 4 1 char

Information for Jitter Matrix Operator (MOP) messages and attributes to this object

Information for box attributes common to all objects

Examples

See Also
Name Description
jit.argb2grgb Convert ARGB to GRGB
jit.argb2uyvy Convert ARGB to UYVY
jit.colorspace Convert between colorspaces
jit.traffic Multiply the planar vector by a matrix
Jitter GL Object (OB3D) Messages
Messages and attributes common to the GL group

Description
Jitter GL objects have a common set of attributes for how to do their 3D rendering, and messages related to drawing. This
includes things like position, rotation, scaling, blending mode, texture, lighting, material properties and other useful tasks.

Arguments
Name Units Type Opt Description
context-name symbol opt Explicitly sets the OpenGL rendering context by name. If this is absent, the Jitter
GL object will use the next higher jit.gl.render or jit.gl.node object in the patcher
hierarchy as the rendering context.

Messages
bang Equivalent to the draw message.
draw Draws the object in the named drawing destination. If the matrixoutput attribute
is supported and set to 1, the geometry matrices are sent out the object's left
outlet.
drawraw Equivalent to draw with the inherit_all attribute set to 1.
drawimmediate Equivalent to draw but ignoring any potential renderer setup
anim_move x [float] Move the object along the axis provided, relative to the space indicated by
y [float] animmode.
z [float]
anim_turn x [float] Rotate the object along each axis by the amount provided, relative to the space
y [float] indicated by animmode.
z [float]
anim_grow x [float] Scale the object along each axis by the amount provided.
y [float]
z [float]
anim_reset Reset the local transformation attributes to their defalut values (position = 0 0 0,
rotatexyz = 0 0 0, and scale = 1 1 1)
update_node Update the node transformation attributes.
import_material Import a Jitter material file (.jitmtl).
export_material Export material state as a material file (.jitmtl).

Attributes
Name Type g/s Description
animmode symbol Determines which space the anim_move and anim_turn messages will affect the
position and orientation of this object (default = parent).
'local' = Rotate relative to local axis
'parent' = Rotate relative to parent axis
'world' = Rotate relative to world axis
antialias int Antialiasing flag (default = 0) On some hardware, the blend_enable attribute
must also be enabled for antialiasing to work.
automatic int Automatic rendering flag (default = 1) When the flag is set, rendering occurs when
the associated jit.gl.render object receives a bang message
auto_material int Automatic material attributes flag (default = 1) When the flag is set, and lighting is
enabled for the object, the diffuse and ambient material components for the object
will be set to the object's color, and the specular and emissive lighting components
are disabled.
aux_color float The auxiliary color in the form red green blue alpha (default = 0. 0. 0. 0.) The list
elements should be in the range 0.-1.
axes int x/y/z axis rendering off/on (default = 0)
blend symbol The named blending mode. The possble values are:
add = blend_mode 1 1
multiply = blend_mode 2 1
screen = blend_mode 4 1
exclusion = blend_mode 4 5
colorblend = blend_mode 3 4
alphablend = blend_mode 6 7
coloradd = blend_mode 3 1
alphaadd = blend_mode 6 1
blend_enable int Blending flag (default = 0) When the flag is set, blending is enabled for all
rendered objects.
blend_mode int The source and destination planes associated with the blend mode (default = 6 7)
Blend modes are specified in the form src_blend_mode dst_blend_mode. The
supported modes are:
0 = zero
1 = one
2 = destination color
3 = source color
4 = one minus destination color
5 = one minus source color
6 = source alpha
7 = one minus source alpha
8 = destination alpha
9 = one minus destination alpha
10 = source alpha saturate
camera float The camera position in 3D space (default = 0. 0. 2.) Camera position is specified as
a set of floating point numbers that correspond to a camera position with respect
to the x, y, and z axes.
capture symbol The name of a texture to be rendered to - e.g. jit.gl.nurbs @capture mytex will
capture to jit.gl.texture @name mytex.
color float The draw color in the form red green blue alpha (default = 1. 1. 1. 1.) The list
elements should be in the range 0.-1.
cull_face int Face culling mode (default = 0 (no culling))
0 = no culling
1 = cull front faces
2 = cull back faces
depth_clear int Depth buffer clear flag (default = 0) When the flag is set, the depth buffer is
cleared before rendering the object.
depth_enable int Depth buffering flag (default = 1) When the flag is set, depth buffering is enabled.
dest_dim int Destination dimensions width height (default = jit.gl.render destination
dimensions)
drawto symbol The named drawing context in which to draw (default = none) A named drawing
context is a named instance of a jit.window, jit.pwindow, or jit.matrix object that
has an instance of the jit.gl.render object associated with it.
enable int Enable flag (default = 1) When the flag is set, drawing is enabled.
far_clip float The far clipping plane distance in 3D world (default = 100.)
fog_params float The fog parameters in the form red green blue alpha density start end (default = 0.
0. 0. 0. 0. 0. 0.) The list's color elements should be in the range 0.-1.
fog float The amount of fog effect (default = 0.)
inherit_all int Inherit all flag (default = 0) When the flag is set, all GL attributes from named
drawing context are inherited.
inherit_color int Inherit color flag (default = 0) When the flag is set, all color attributes from the
named drawing context are inherited.
inherit_depth int Inherit depth buffer flag (default = 0) When the flag is set, all depth buffer
attributes from the named drawing context are inherited.
inherit_fog int Inherit fog attributes flag (default = 0) When the flag is set, all fog attributes from
the named drawing context are inherited.
inherit_material int Inherit material attributes flag (default = 0) When the flag is set, all lighting and
material attributes from the named drawing context are inherited.
inherit_poly int Inherit polygon attributes flag (default = 0) When the flag is set, all polygon
attributes from the named drawing context are inherited.
inherit_texture int Inherit texture attributes flag (default = 0) When the flag is set, all texture
attributes from the named drawing context are inherited.
inherit_transform int Inherit transform attributes flag (default = 0) When the flag is set, all transform
attributes from the named drawing context are inherited.
layer int Object layer number (default = 0) When in automatic mode, the layer number
determines he rendering order (low to high). Objects in the same layer have no
guarantee which will be rendered first.
lens_angle float The lens angle of the OpenGL camera (default = 45.)
lighting_enable int Lighting enabled flag (default = 0) When the flag is set, lighting is calculated.
light_ambient float The color and opacity of the ambient light component in the form red green blue
opacity (default = 0. 0. 0. 1. (opaque black)) All values should be in the range 0.-
1.
light_diffuse float The color and opacity of the diffuse light component in the form red green blue
opacity (default = 1. 1. 1. 1. (opaque white)) All values should be in the range 0.-1.
light_global_ambient float The color and opacity of the global ambient light component in the form red
green blue opacity (default = 0.2 0.2 0.2 1.) All values should be in the range 0.-
1.
light_position float The position of the light source in XYZ coordinates and the light type (default = 1.
1. 1. 0.)
When the last number is 0., t The light is treated as a directional source if 0. is the
final number. Otherwise, diffuse and specular lighting calculations are based on
the actual location of the light in eye coordinates, and attenuation is enabled.
light_specular float Color and opacity of specular light component (default = 1. 1. 1. 1. (opaque white))
The first three floats in the range 0.-1. specify the RGB components of the specular
light color. The fourth float (also in the range 0.-1.) specifies opacity.
line_width float The drawing line width (default = 1.)
lookat float 3D position at which the camera is pointed (default = 0. 0. 0.)
mat_ambient float The ambient light material property in the form red green blue alpha (default = 0.
0. 0. 0.) The list elements should be in the range 0.-1.
mat_diffuse float The diffuse light material property in the form red green blue alpha (default = 0.
0. 0. 0.) The list elements should be in the range 0.-1.
mat_emission float The material emission property in the form red green blue alpha (default = 0. 0. 0.
0.) The list elements should be in the range 0.-1.
mat_specular float The specular light material property in the form red green blue alpha (default = 0.
0. 0. 0.) The list elements should be in the range 0.-1.
matfile symbol The Jitter material file to apply (.jitmtl)
matrixoutput int Matrix output mode (default = 0)
0 = issue render commands
1 = output geometry matrices
2 = output geometry matrices with local transform applied
name symbol The instance name (default = UID)
near_clip float The near clipping plane distance in 3D world (default = 0.1)
ortho int Orthographic projection mode (default = 0)
0 = orthographic projection off (perspective projection)
1 = orthographic projection on, using lens angle
2 = orthographic projection on, ignoring lens angle
point_size float The draw point size (default = 1.)
poly_mode int Polygon rendering modes (default 0 0) Rendering modes are expressed in the
form frontface backface. Supported rendering modes are:
0 = render as filled polygons
1 = render as lines
2 = render as points
position float The 3D origin in the form x y z (default = 0. 0. 0.)
rotate float The angle of rotation and the three axes about which the rotation is performed in
the form rotation-angle x y z (default = 0. 0. 1. 0.)
rotatexyz float Sets the current rotation (which in Jitter is expressed in angle/axis format) to the
concatenation of rotations about the positive x, y, and z axes (in that order).
Angles are expressed in degrees. Sets the current rotation (which in Jitter is
expressed in angle/axis format) to the concatenation of rotations about the
positive x, y, and z axes (in that order). Angles are expressed in degrees.
scale float The 3D scaling factor in the form x y z (default = 1. 1. 1.)
shininess float The material shininess value (default = 16.0) The value should be a float in the
range 0.-255.
smooth_shading int Smooth shading flag (default = 0) When the flag is set, smooth shading is used
when rendering.
tex_map int Mode for automatic generation of texture coordinate controls (default = 0)
0 = no coordinates are generated.
1 = OpenGL's texture generation is used with mode GL_OBJECT_LINEAR. This
applies the texture in a fixed orientation relative to the object.
2 = OpenGL's texture generation is used with mode GL_SPHERE_MAP. This can
be used to create a reflection effect.
3 = OpenGL's texture generation is used with mode GL_EYE_LINEAR. This
applies the texture in a fixed orientation relative to OpenGL's eye coordinates.
Modes 1 and 3 are affected by the value of the tex_plane_s and tex_plane_t
attributes listed below.
tex_plane_s float The texture generation coefficients a b c d that apply to tex_map modes 1 and 3.
(default = 1. 0. 0. 0.)
The four coefficients define a plane used to generate the s texture coordinate,
which corresponds to the x axis of the texture image. If the tex_map mode is 1, s =
ax + by + cz + dw, where x, y, z, and w are the homogeneous coordinates of the
vertex.
tex_plane_t float The texture generation coefficients a b c d, which apply to tex_map modes 1 and 3.
(default = 0. 1. 0. 0)
The four coefficients define a plane which is used to generate the t texture
coordinate, which corresponds to the y axis of the texture image.
shader symbol The name of the shader to be applied (default = none)
texture symbol The name of the texture to be applied (default = none). If multiple textures are
specified, uses multi-texturing.
transform_reset int Modelview and projection transform reset flag (default = 0) When the flag is set,
the modelview and projection transforms are set to the identity transform before
rendering the object. This is useful for sprite or billboard overlays, or automatic
scaling to window size. The transform_reset flag modes are:
0 = do nothing (default)
1 = proportional orthographic glOrtho(-aspect, aspect, -1.0, 1.0, near_clip,
far_clip);
2 = orthographic normalized glOrtho(-1.0, 1.0, -1.0, 1.0, near_clip, far_clip);
3 = proportional perspective with near clip = 0.001 gluPerspective(lens_angle,
aspect, 0.001/*near_clip*/, far_clip);
4 = normalized perspective with near clip = 0.001 gluPerspective(lens_angle, 1.0,
0.001/*near_clip*/, far_clip);
up float The 3D vector towards which the top of the camera points (default = 0. 1. 0.)
verbose int Toggles printing messages to the Max Window.
viewalign int View aligned transformation flag (default = 0)
Jitter Matrix Operators
Messages and attributes common to Jitter matrix operators

Description
Since the matrix is Jitter's focus, it is not surprising that the majority of Jitter objects fall in this category of Matrix Operators.
Every Matrix operator has some number of matrix inputs and some number of matrix outputs. Matrix inputs are referred to by
the names "in", "in2", "in3", etc., from left to right, and matrix outputs are referred to by the names "out", "out2", "out3", etc.,
from left to right--i.e. the names are appended by the input/output number except for the first (leftmost) input and first
(leftmost) output which are simply named "in" and "out". We will refer to the input or output name names as the "I/O-name".

Matrix inputs and outputs typically each have their own matrices internally where information is kept. This is necessary because
Jitter is an asynchronous framework (i.e. all the matrices don't arrive at all inputs at the same time). Various aspects of matrix
inputs and outputs can be set using the command [I/O-name] combined with one of the following suffixes: "_dim" which will set
the dimensions of the specified I/O matrix, "_type" which will set the type of the specified matrix, "_planecount" which will set
the plane of the specified matrix, or "_name" which will set the name of the specified matrix. There is one special case which does
not have an internal matrix and this is the first input "in". This is the case since this special input actually triggers the calculation
of the matrix operator, so it doesn't need to be cached until a calulation takes place, unlike the other inputs. Therefore there is no
mechanism to set the dim, planecount, type, or name of "in".

Matrix operators accept what we'll refer to as "matrix args"--i.e. [planecount (int)] [ type (symbol)] [dim (int list)]. if these
arguments are present, the adapt attribute will be turned off, otherwise it will be turned on. If adapt mode is turned on, each time
a matrix is received in the first input, there will also be the equivalent of setting the dim, planecount, and type attributes to that of
the input matrix. If the other inputs and outputs are linked to these attributes, this will affect their linked attributes as well. See
the "MOP" table to determine which inputs and outputs will be linked to which attributes when adapt mode is turned on. For the
leftmost input this is not applicable, and hence all columns are labelled "n/a".

The jit.matrix object is a named matrix which may be used to matrix data storage and retrieval, resampling, and matrix type and
planecount conversion operations.

Arguments
Name Units Type Opt Description
planecount int opt Explicitly sets the number of planes for the output and any righthand inputs. If
this is absent, the Matrix Operator will typically adapt to the lefthand incoming
matrix attributes, except for special case operators.
type symbol opt Explicitly sets the type of the matrix for the output and any righthand inputs. If
this is absent, the Matrix Operator will typically adapt to the lefthand incoming
matrix attributes, except for special case operators.
dimensions list opt Explicitly sets the dimensions of the matrix for the output and any righthand
inputs. If this is absent, the Matrix Operator will typically adapt to the lefthand
incoming matrix attributes, except for special case operators.

Messages
bang Equivalent to the outputmatrix message.
clear Sets all cell values in a matrix to zero.
exportattrs filename [symbol] Exports an object's current attributes values in XML format. If no filename is
specified, a file dialog will open to let you choose a file.
getattributes Sends a sequence of lists out the object's right outlet describing the object's
attributes, one line per attribute. Each line listing line takes the form attribute
attribute-name get get-value set foo set-value data-type(s) number-of-values .
getstate Sends a sequence of lists describing the object's state out the object's right outlet,
one line per attribute. Each line listing line takes the form attribute-name
attribute-value1 attribute-value2 ... attribute-valueN .
importattrs filename [symbol] Imports attributes specified in XML format to set the object's attributes. If no
filename is specified, a file dialog will open to let you choose a file.
jit_matrix matrix-name [symbol] Handles input for th named matrix. If this messages is received in the left inlet,
output is typically triggered. If this message is received in any other inlet, the data
is typically cached until the jit_matrix message is received in the left inlet.
outputmatrix Sends the matrix out the left outlet.
summary Sends a sequence of lists describing the object and it attributes and messages out
the rightmost outlet of the object. The first output line takes the form summary
objectname object-name . The second and third lines describe the number of
inlets and outlets for the object in the form summary
(matrixinputcount/matrixoutletcount) number-of-(inlets/outlets) . The fourth
line describes the matrixoutput in the form summary matrixoutput descriptor
planelink planelink-value typelink typelink-value dimlink dimlink-value types
data-type(s) . Each attribute for the object is then listed, one attribute per line.
Each line listing takes the form summary attribute attribute-name attribute-
value1 attribute-value2 ... attribute-valueN .

Attributes
Name Type g/s Description
adapt int Matrix adaptation flag (default = 0 if matrix arguments are present, otherwise 1)
When the flag is set, the jit.matrix object will adapt to the incoming matrix
planecount, type, and dimensions.
[in/out]_dim int The matrix data dimensions (default = 1 1)
[in/out]_name symbol The input or output name of the matrix (default = UID)
[in/out]_planecount int The number of planes in matrix input our output data. Except in special cases, this
value is equal to the planecount.
[in/out]_type symbol The input or output matrix data type. Except in special cases, this value is equal to
type.
[in/out]_type symbol The input or output matrix data type. Except in special cases, this value is equal to
type.
outputmode int Output mode (default = 1 (calculate and output matrix))
0 = No output
1 = Calculate and output the matrix
2 = Pass input (no calculation)
3 = Pass output (no calculation)
type int The matrix data type (default = char
Supported data types are char, long, float32, or float64.
jit.hatch
Perform crosshatch filtering

Description
Divides an incoming matrix into a grid. Along the central axes of each square, the color value of the original top-left pixel is
visible.

Matrix Operator
matrix inputs:1, matrix outputs:1
Name IOProc Planelink Typelink Dimlink Plane Dim Type
out n/a 1 1 1 4 1 char

Information for Jitter Matrix Operator (MOP) messages and attributes to this object

Attributes
Name Type g/s Description
bgcolor float The background color in the form alpha red green blue (default = 0. 0. 0. 0.) All
values are in the range 0.-1.
grid int The square size (default = 5)
thresh float The luminance threshold (default = 0.)
Color values above the threshold are eligible for hatching. Otherwise, they are
replaced by the background color.

Information for box attributes common to all objects

Examples

See Also
Name Description
jit.altern Color screen with threshold
jit.eclipse Create images from images
jit.roy Convert image to halftone image
jit.hello
Show an example of Jitter attributes

Description
Stores text in the text attribute. This object only exists as an illustration of how attributes work.

Attributes
Name Type g/s Description
text symbol Some text to store

Information for box attributes common to all objects

Examples

See Also
Name Description
jit.histogram
Calculate matrix histogram

Description
Calculates the histogram for a series of input matrices. The histogram is the distribution of values for each of the matrix's planes.

Matrix Operator
matrix inputs:1, matrix outputs:1
Name IOProc Planelink Typelink Dimlink Plane Dim Type
out n/a 1 0 0 1 1 long char

Information for Jitter Matrix Operator (MOP) messages and attributes to this object

Attributes
Name Type g/s Description
autoclear int Autoclear flag (default = 1) When the flag is set, the matrix is cleared following
output.
normalize int Normalization mode. The normalization modes are:

0: no normalization
1: per channel normalization
2: channel-linked normalization
Channel-linked normalization may be of limited value for video signals where the
alpha channel is composed of all zero values.
normval int Normalization flag (default = 0) When the flag is set, histogram values to the
range [0, normval ] are normalized.

Information for box attributes common to all objects

Examples

See Also
Name Description
jit.3m Report min/mean/max values
jit.fft Perform a matrix-based FFT
jit.hsl2rgb
Convert HSL to RGB

Description
Converts a 4 plane matrix of AHSL (alpha, hue, saturation, lightness) data to ARGB (alpha, red, green, blue) data.

Matrix Operator
matrix inputs:1, matrix outputs:1
Name IOProc Planelink Typelink Dimlink Plane Dim Type
out n/a 1 1 1 4 1 char float32 float64

Information for Jitter Matrix Operator (MOP) messages and attributes to this object

Information for box attributes common to all objects

Examples

See Also
Name Description
jit.colorspace Convert between colorspaces
jit.hue Rotate hue
jit.rgb2luma Converts RGB to monochrome (luminance)
jit.rgb2hsl Convert HSL to RGB
jit.traffic Multiply the planar vector by a matrix
jit.hue
Rotate hue

Description
Performs a hue rotation, preserving the luminance values.

Matrix Operator
matrix inputs:1, matrix outputs:1
Name IOProc Planelink Typelink Dimlink Plane Dim Type
out n/a 1 1 1 4 1 char

Information for Jitter Matrix Operator (MOP) messages and attributes to this object

Attributes
Name Type g/s Description
hue_angle float The hue rotation angle, in degrees (default = 0.)

Information for box attributes common to all objects

Examples

See Also
Name Description
Rotate hue
jit.hsl2rgb Convert HSL to RGB
jit.rgb2hsl Convert HSL to RGB
jit.traffic Multiply the planar vector by a matrix
Tutorial 7: Image Level Tutorial 7: Image Level Adjustment
Adjustment
Tutorial 14: Matrix Positioning Tutorial 14: Matrix Positioning
jit.iter
Iterate a matrix as lists or values

Description
Iterates through all the cells of a matrix, sending a message or list for each cell out the object's left outlet. Output is one item per
plane of data. A list of ints is sent out the middle outlet that containing the current cell coordinates.

Arguments
None.

Attributes
Name Type g/s Description
mode int Traversal mode (default = 0 (horizontal))
0 = horizontal traversal
1 = vertical traversal

Information for box attributes common to all objects

Examples

See Also
Name Description
iter Break a list into individual messages
jit.fill Fill a matrix with a list
jit.matrix The Jitter Matrix!
jit.spill Unroll a matrix into a list
Tutorial 6: Adjust Color Levels Tutorial 6: Adjust Color Levels
Tutorial 11: Lists and Matrices Tutorial 11: Lists and Matrices
jit.keyscreen
Choke chromakey from 3 sources

Description
Takes three 4-plane char matrix and does an interchangeable choke chromakey between the three sources. Any of the three input
matrices can be designated as the key image (from which the image mask is created), the target image (which the mask is
overlaid onto), or the mask image (which is placed on top of the target in the shape of the key).

Matrix Operator
matrix inputs:3, matrix outputs:1
Name IOProc Planelink Typelink Dimlink Plane Dim Type
in2 resamp 1 1 1 4 1 char
in3 resamp 1 1 1 4 1 char
out n/a 1 1 1 4 1 char

Information for Jitter Matrix Operator (MOP) messages and attributes to this object

Attributes
Name Type g/s Description
alpha float The alpha (plane 0) value for the chroma key (default = 0.)
alphatol float The alpha tolerance level for the chroma key (default = 0.)
blue float The blue (plane 3) value for the chroma key (default = 0.)
bluetol float The blue tolerance level for the chroma key (default = 0.)
green float The green (plane 2) value for the chroma key (default = 0.)
greentol float The green tolerance level for the chroma key (default = 0.)
key int The inlet number for the key matrix (default = 1)
A matrix received in the key inlet is used to build the shape of mask image
mask int The inlet number for the mask matrix (default = 2)
A matrix received in the mask inlet is shaped by the key image and occludes the
target image
mode int Chomakeying mode (default = 0 (key entire cells))
0 = chroma key entire cells of the input matrices
1 = chroma key individual planes of the input matrices
'Wrap' = TEXT_HERE
'Clip' = TEXT_HERE
'Fold' = TEXT_HERE
red float The red (plane 1) value for the chroma key (default = 0.)
redtol float The red tolerance level for the chroma key (default = 0.)
target int The inlet number for the target matrix (default = 1)
A matrix received in the target inlet is placed behind the mask image

Information for box attributes common to all objects

Examples
See Also
Name Description
jit.alphablend Blend two images with an alpha channel image
jit.chromakey Key images based on chromatic distance
jit.lumakey Key based on distance from a luminance value
jit.op Apply binary or unary operators
jit.la.determinant
Calculate the determinant of a matrix

Description
jit.la.determinant calculates the determinant of a given input matrix, and send the result out the leftmost outlet. The input
matrices must be 1-plane or 2-plane matrices of the type float32 or float64. If a 2-plane matrix is used, it is assumed that the
data is from the set of complex numbers and the output product is a list of 2 floating point values. The first element is the real
component and the second element is the imaginary component.

Matrix Operator
matrix inputs:1, matrix outputs:0
Name IOProc Planelink Typelink Dimlink Plane Dim Type

Information for Jitter Matrix Operator (MOP) messages and attributes to this object

Attributes
Name Type g/s Description
thresh float The threshold value beneath which the absolute value of the result of internal
calculations are considered to be equal to zero (default = 0.000000001)

Information for box attributes common to all objects

Examples

See Also
Name Description
jit.la.diagproduct Calculate the product across the main diagonal
jit.la.inverse Calculate the inverse of a matrix
jit.la.mult True matrix multiplication
jit.la.trace Calculate the sum across the main diagonal
jit.la.uppertri Convert a matrix into an upper triangular matrix
jit.la.diagproduct
Calculate the product across the main diagonal

Description
jit.la.diagproduct calculates the product across the main diagonal of a given input matrix, and send the result out the leftmost
outlet. The input matrices must be 1-plane or 2-plane matrices of the type float32 or float64. If a 2-plane matrix is used, it is
assumed that the data is from the set of complex numbers and the output product is a list of 2 floating point values. The first
element is the real component and the second element is the imaginary component.

Matrix Operator
matrix inputs:1, matrix outputs:0
Name IOProc Planelink Typelink Dimlink Plane Dim Type

Information for Jitter Matrix Operator (MOP) messages and attributes to this object

Attributes
Name Type g/s Description

Information for box attributes common to all objects

Examples

See Also
Name Description
jit.la.determinant Calculate the determinant of a matrix
jit.la.inverse Calculate the inverse of a matrix
jit.la.mult True matrix multiplication
jit.la.trace Calculate the sum across the main diagonal
jit.la.uppertri Convert a matrix into an upper triangular matrix
jit.la.inverse
Calculate the inverse of a matrix

Description
jit.la.inverse calculates the inverse with respect to multiplication of a given input matrix. The input matrices must be 1-plane or
2-plane matrices of the type float32 or float64. If a 2-plane matrix is used, it is assumed that the data is from the set of complex
numbers.

Matrix Operator
matrix inputs:1, matrix outputs:1
Name IOProc Planelink Typelink Dimlink Plane Dim Type
out n/a 1 1 1 1 1 float32 float64

Information for Jitter Matrix Operator (MOP) messages and attributes to this object

Attributes
Name Type g/s Description
thresh float The threshold value beneath which the absolute value of the result of internal
calculations are considered to be equal to zero (default = 0.000000001)

Information for box attributes common to all objects

Examples

See Also
Name Description
jit.la.determinant Calculate the determinant of a matrix
jit.la.diagproduct Calculate the product across the main diagonal
Calculate the inverse of a matrix
jit.la.mult True matrix multiplication
jit.la.trace Calculate the sum across the main diagonal
jit.la.uppertri Convert a matrix into an upper triangular matrix
jit.la.mult
True matrix multiplication

Description
jit.la.mult calculates the matrix product of two input matrices (as opposed to multiplication performed by the jit.op object, which
is pointwise multiplication). The input matrices must be 1-plane or 2-plane matrices of the type float32 or float64. If a 2-plane
matrix is used, it is assumed that the data is from the set of complex numbers.

Matrix Operator
matrix inputs:2, matrix outputs:1
Name IOProc Planelink Typelink Dimlink Plane Dim Type
in2 adapt 1 1 0 1 1 float32 float64
out n/a 1 1 0 1 1 float32 float64

Information for Jitter Matrix Operator (MOP) messages and attributes to this object

Information for box attributes common to all objects

Examples

See Also
Name Description
jit.la.determinant Calculate the determinant of a matrix
jit.la.diagproduct Calculate the product across the main diagonal
jit.la.inverse Calculate the inverse of a matrix
jit.la.trace Calculate the sum across the main diagonal
jit.la.uppertri Convert a matrix into an upper triangular matrix
jit.op Apply binary or unary operators
jit.la.trace
Calculate the sum across the main diagonal

Description
jit.la.trace calculates the sum across the main diagonal of a given input matrix, and send the result out the leftmost outlet. The
input matrices must be 1 or 2-plane matrices of the type float32 or float64. If a 2-plane matrix is used, it is assumed that the
data is from the set of complex numbers and the output product is a list of 2 floating point values. The first element is the real
component and the second element is the imaginary component.

Matrix Operator
matrix inputs:1, matrix outputs:0
Name IOProc Planelink Typelink Dimlink Plane Dim Type

Information for Jitter Matrix Operator (MOP) messages and attributes to this object

Attributes
Name Type g/s Description

Information for box attributes common to all objects

Examples

See Also
Name Description
jit.la.determinant Calculate the determinant of a matrix
jit.la.diagproduct Calculate the product across the main diagonal
jit.la.inverse Calculate the inverse of a matrix
jit.la.mult True matrix multiplication
jit.la.uppertri Convert a matrix into an upper triangular matrix
jit.la.uppertri
Convert a matrix into an upper triangular matrix

Description
The jit.la.determinant object converts a given input matrix to an upper triangular matrix via Gaussian elimination. The input
matrices must be 1-plane or 2-plane matrices of the type float32 or float64. If a 2-plane matrix is used, it is assumed that the
data is from the set of complex numbers.

Matrix Operator
matrix inputs:1, matrix outputs:1
Name IOProc Planelink Typelink Dimlink Plane Dim Type
out n/a 1 1 1 1 1 float32 float64

Information for Jitter Matrix Operator (MOP) messages and attributes to this object

Attributes
Name Type g/s Description
swapcount int (get) The number of row swaps required to perform Gaussian elimination
thresh float The threshold value beneath which the absolute value of the result of internal
calculations are considered to be equal to zero (default = 0.000000001)

Information for box attributes common to all objects

Examples

See Also
Name Description
jit.la.determinant Calculate the determinant of a matrix
jit.la.diagproduct Calculate the product across the main diagonal
jit.la.inverse Calculate the inverse of a matrix
jit.la.mult True matrix multiplication
jit.la.trace Calculate the sum across the main diagonal
jit.lcd
QuickDraw wrapper

Description
The jit.lcd object is a wrapper for many QuickDraw commands.

Messages
bang Displays the current contents.
ascii character [int] Writes the ASCII character specified by the character argument at the current pen
location using the current font and textmode, then moves the pen position to the
right of that character. Numbers that exceed the 0-255 range are restricted to that
range with a modulus operation.
clear Erases the contents of jit.lcd.
brgb red [int] Sets the current background color. All values should be in the range 0-255.
green [int]
blue [int]
clearpicts The word clearpicts, followed by a symbol, deletes all of an lcd object's named
pictures from memory so that they can no longer be drawn. To remove the images
from the lcd object's display, the command should be followed by a clear message.
clearregions Deletes all of a jit.lcd object's named regions.
clipoval left [int] Clips drawing commands to the oval specified by left top right bottom The
top [int] arguments are specified in pixels, relative to the top left corner of the viewing area.
bottom [int]
right [int]
clippoly x/y int pairs [list] Clips drawing commands to the polygon specified by the up to 254 x/y-pairs
arguments. These integer pairs are specified in pixels, relative to the top left corner
of the viewing area.
cliprect left [int] Clips drawing commands to the rectangle specified by left , top , right , and
top [int] bottom arguments. These integer arguments are specified in pixels, relative to the
bottom [int] top left corner of the viewing area.
right [int]
cliprgn region-name [symbol] Clips drawing commands to the region specified by region-name argument.

cliproundrect left [int] Clips drawing commands to the rounded rectangle specified by left , top , right ,
top [int] bottom , horizontal-roundness , and vertical-roundness arguments. These integer
bottom [int] arguments are specified in pixels, relative to the top left corner of the viewing area.
right [int]
horizontal-roundness
[int]
vertical-roundness
[int]
color color-index [int] Sets the current pen color to the value specified by the color-index argument.
deletepict any symbol [list] The word deletepict, followed by a symbol, deletes the named the picture from
memory so that it can no longer be drawn. To remove the image from the lcd
object's display, the command should be followed by a clear message.
drawpict pict-name [symbol] Draws the named picture or matrix. A destination rectangle into which the picture
x-offset [int] is scaled and drawn may optionally be specified by the x-offset , y-offset , width ,
y-offset [int] and height integer arguments. A source rectangle that specifies the area of the
width [int] picture to use in the operation may also be optionally specified by the src-x-offset ,
height [int] src-y-offset , src-width , and src-height integer arguments. The position of the
src-x-offset [int] destination and source rectangles are relative to the top left corner of the jit.lcd
src-y-offset [int] object's display area. Unless otherwise specified, both rectangles are set to be the
src-width [int] same size as the picture. All arguments are optional and default to zero. The
src-height [int] current penmode will used as the transfer mode.
closeregion region-name [symbol] Turns off region definition and associates the defined region with the region-
name symbol argument. After the closeregion message, drawing commands
function normally again.
deleteregion region-name [symbol] Deletes the named region.

font mutex group Sets the current font name and size. Fonts can be specified by either their ID
font-id [int] number or name. Font size is specified in points.
font-name [symbol]
endmutex group
font-size () [int]
framearc left [int] Paints the outline of an arc. The left , top , right , and bottom arguments describe
top [int] the top and bottom extremities in pixels of an oval across which the arc will be
bottom [int] drawn, and the start-angle and arc-length arguments describe the position of the
right [int] arc with respect to the oval. The location of the oval/arc is relative to the top left
start-angle [int] corner of the jit.lcd object's display area. A color may also optionally be specified
arc-length [int] using a single number that selects a color from Max's color palette (similar to the
mutex group color message), or by using three additional numbers that describe an RGB value
color-index [int] (similar to the frgb message). The width of the line segment describing the arc is
red [int] set using the pensize message to the jit.lcd object.
green [int]
blue [int]
endmutex group
frameoval left [int] Draws the unfilled outline of an oval. The left , top , right , and bottom integer
top [int] arguments describe the top and bottom extremities in pixels of the oval. The
bottom [int] location of the oval is relative to the top left corner of the jit.lcd object's display
right [int] area. Optional additional arguments to specify the color of the border may also
mutex group follow. If a single integer argument is used, it specifies a color from Max's color
color-index [int] palette. Three integer arguments specify an RGB color. The width of the border of
red [int] the oval is set using the pensize message to the jit.lcd object.
green [int]
blue [int]
endmutex group
framepoly x/y int pairs [list] Draws the unfilled outline of a polygon specified by up to 254 integer x/y-pair
arguments. Each integer pair specifies a pixels relative to the top left corner of the
jit.lcd object's display area. A polygon is closed by specifying an x/y pair having
the same values as the first integer pair. The width of the border of the polygon is
set using the pensize message to the jit.lcd object.
framerect left [int] Draws the unfilled outline of a rectangle specified by the left , top , right , and
top [int] bottom integer arguments. The edge positions are specified as pixels relative to the
bottom [int] top left corner of the jit.lcd object's display area. Optional additional arguments to
right [int] specify the color of the border may also follow. If a single integer argument is used,
mutex group it specifies a color from Max's color palette. Three integer arguments specify an
color-index [int] RGB color. The width of the border of the rectangle is set using the pensize
red [int] message to the jit.lcd object.
green [int]
blue [int]
endmutex group
framergn region-name [symbol] Draws the unfilled outline of the region specified by the region-name argument.
An optional pair of integer arguments that specify a horizontal and vertical offset
x-offset [int] to which the region's coordinates will be relative can also be specified. Optional
y-offset [int] additional arguments to specify the color of the border may also follow. If a single
mutex group integer argument is used, it specifies a color from Max's color palette. Three
color-index [int] integer arguments specify an RGB color. The width of the border of the region is
red [int] set using the pensize message to the jit.lcd object.
green [int]
blue [int]
endmutex group
frameroundrect left [int] Draws the unfilled outline of a rounded rectangle. The left , top , right , and
top [int] bottom integer arguments describe the top and bottom extremities of the
bottom [int] rectangle, and the The horizontal-roundness and vertical-roundness] integer
right [int] arguments specify the amount of corner rounding in pixels. The location of the
horizontal-roundness rounded rectangle is relative to the top left corner of the jit.lcd object's display
[int] area. Optional additional arguments to specify the color of the border may also
vertical-roundness follow. If a single integer argument is used, it specifies a color from Max's color
[int] palette. Three integer arguments specify an RGB color. The width of the border of
mutex group the rectangle is set using the pensize message to the jit.lcd object.
color-index [int]
red [int]
green [int]
blue [int]
endmutex group
frgb red [int] Sets the current foreground color. All arguments should be in the range 0-255.
green [int]
blue [int]
getpenloc Sends the x and y coordinates of the current pen location out the right outlet of
the object as a list in the form penloc x-offset y-offset . The numbers represent
local coordinates relative to the top left corner of the jit.lcd object's display area.
The first number is the number of pixels to the right of that corner, and the second
number is the number of pixels down from that corner.
getpixel x-offset [int] Sends the color of the pixel specified by the x and y offset arguments and the
y-offset [int] coordinates out the object's right outlet as a list in the form pixel red green blue
x-offset y-offset . The three color values should be in the range 0-255. The pixel
location is specified relative to the top left corner of the jit.lcd object's display
area. If a pixel is out of range, the getpixel message will output pixel 0 0 0 x y,
where x and y are the out of range location specified.
move x-offset [int] Moves the pen position relative to its current location. The new location is
y-offset [int] specified by the two integer x-offset and x-offset arguments. Positive values for the
x-offset and x-offset arguments move the pen position to the right or down, and
negative arguments move it up or to the left.
line x-offset [int] Draws a line from the current pen position to the relative point specified by two
y-offset [int] integer x-offset and x-offset arguments. The endpoint of the line becomes the new
pen position. Positive values for the x-offset and x-offset arguments draw the line
to the right or down, and negative arguments draw up or to the left.
moveto x-offset [int] Sets the pen position at which the next graphic instruction will be drawn. The new
y-offset [int] location is specified by the two integer x-offset and x-offset arguments that are
relative to the top left corner of the jit.lcd object's display area.
lineto x-offset [int] Draws a line from the current pen position to the relative point specified by two
y-offset [int] integer x-offset and x-offset arguments. Positive values for the x-offset and x-offset
arguments draw the line to the right or down, and negative arguments draw up or
to the left.
linesegment x-start [int] Draws a line segment. The x-start , y-start , x-end , and y-end arguments specify
y-start [int] the start and end points of the line segment. The location of the start and end
x-end [int] points is relative to the top left corner of the jit.lcd object's display area. Optional
y-end [int] additional arguments to specify the color of the line segment may also follow. If a
mutex group single integer argument is used, it specifies a color from Max's color palette. Three
color-index [int] integer arguments specify an RGB color. The width of the line segment is set using
red [int] the pensize message to the jit.lcd object.
green [int]
blue [int]
endmutex group
oprgb red [int] Sets the current opcode color used in some of the jit.lcd object's transfermodes,
green [int] such as "blend". All arguments should be in the range 0-255.
blue [int]
noclip Removes any clipping area that may be in place.
paintarc left [int] Paints an arc. The left , top , right , and bottom integer arguments describe the top
top [int] and bottom extremities in pixels of an oval across which the arc will be drawn, and
bottom [int] the start-angle and arc-length arguments describe the position of the arc with
right [int] respect to the oval. The location of the oval/arc is relative to the top left corner of
start-angle [int] the jit.lcd object's display area. Optional additional arguments to specify the color
arc-length [int] of the arc may also follow. If a single integer argument is used, it specifies a color
mutex group from Max's color palette. Three integer arguments specify an RGB color.
color-index [int]
red [int]
green [int]
blue [int]
endmutex group
paintoval left [int] Paints an oval. The left , top , right , and bottom integer arguments describe the
top [int] top and bottom extremities in pixels of the oval. The location of the oval is relative
bottom [int] to the top left corner of the jit.lcd object's display area. Optional additional
right [int] arguments to specify the color of the oval may also follow. If a single integer
mutex group argument is used, it specifies a color from Max's color palette. Three integer
color-index [int] arguments specify an RGB color.
red [int]
green [int]
blue [int]
endmutex group
paintpoly x/y int pairs [list] Paints a polygon specified by up to 254 integer x/y-pair arguments. Each integer
pair specifies a pixel relative to the top left corner of the jit.lcd object's display
area. A polygon is closed by specifying an x/y pair having the same values as the
first integer pair.
paintrect left [int] Paints a rectangle specified by the left , top , right , and bottom integer arguments.
top [int] The edge positions are specified as pixels relative to the top left corner of the
bottom [int] jit.lcd object's display area. Optional additional arguments to specify the color of
right [int] the rectangle may also follow. If a single integer argument is used, it specifies a
mutex group color from Max's color palette. Three integer arguments specify an RGB color.
color-index [int]
red [int]
green [int]
blue [int]
endmutex group
paintrgn region-name [symbol] Paints or filled the regions specified by the region-name argument. An optional
pair of integer arguments that specify a horizontal and vertical offset to which the
x-offset [int] region's coordinates will be relative can also be specified. Optional additional
y-offset [int] arguments to specify the color of the region may also follow. If a single integer
mutex group argument is used, it specifies a color from Max's color palette. Three integer
color-index [int] arguments specify an RGB color.
red [int]
green [int]
blue [int]
endmutex group
paintroundrect left [int] Paints a rounded rectangle. The left , top , right , and bottom integer arguments
top [int] describe the top and bottom extremities of the rectangle, and the The horizontal-
bottom [int] roundness and vertical-roundness] integer arguments specify the amount of
right [int] corner rounding in pixels. The location of the rounded rectangle is relative to the
horizontal-roundness top left corner of the jit.lcd object's display area. Optional additional arguments to
[] specify the color of the rectangle may also follow. If a single integer argument is
vertical-roundness [] used, it specifies a color from Max's color palette. Three integer arguments specify
mutex group an RGB color.
color-index [int]
red [int]
green [int]
blue [int]
endmutex group
penmode penmode-index [int] Sets the transfer mode for subsequent drawing operations. The transfer mode is
set using an integer argument in the range 0-39. Supported transfer modes are:
0 = Copy
1 = Or
2 = Xor
3 = Bic
4 = NotCopy
5 = NotOr
6 = NotXor
7 = NotBic
32 = Blend
33 = AddPin
34 = AddOver
35 = SubPin
36 = Transparent
37 = AddMax
38 = SubOver
39 = AddMin
For more information on the effects of each drawing mode, refer to the
QuickDraw documentation in Inside Macintosh .
pensize number-of-pixels Sets the pen size to be used subsequent drawing operations. The pen size is set
[int] with a single integer argument.
readpict pict-name [symbol] Reads a picture file specified by the symbol pict-name from disk into RAM. This
named picture can then be drawn in lcd with the drawpict and tilepict messages.
recordregion Starts the recording of drawing commands which will be stored in a named region.
While recording, drawing commands will have no visible effect on the contents of
the jit.lcd object's display area.
reset Erases the contents of the jit.lcd object's display area and resets the object to its
default values. This message is equivalent to this series of messages to the jit.lcd
object:
clear
pensize 1
penmode 0
frgb 0 0 0 (black)
brgb 255 255 255 (white)
textface font-style [list] Sets the font style(s) to be used when rendering text. Font styles may be specified
individually with a single symbol argument, or as a list. Valid font styles are
normal, bold, italic, underline, outline, shadow, condense, and extend;
textmode mode-index [int] Sets the text rendering mode using an integer argument in the range 0-39.
Supported textmodes are:
0 = Copy
1 = Or
2 = Xor
3 = Bic
4 = NotCopy
5 = NotOr
6 = NotXor
7 = NotBic
32 = Blend
33 = AddPin
34 = AddOver
35 = SubPin
36 = Transparent
37 = AddMax
38 = SubOver
39 = AddMin
For more information on the effects of each rendering mode, refer to the
QuickDraw documentation in Inside Macintosh .
scrollrect left [int] Moves or "scrolls" a rectangle defined by the left , top , right , and bottom integer
top [int] arguments in the direction specified by the x-offset and y-offset integer arguments.
right [int] the first four arguments in the direction specified by the fifth and sixth ints within
bottom [int] the jit.lcd object's display area.
left [int]
x-offset [int]
y-offset [int]
setpixel x-offset [int] Sets the pixel located at the coordinates specified by the x-offset and y-offset
y-offset [int] coordinates to the RGB value specified by the red , green , and blue arguments.
red [int] The RGB values should be integers in the range 0-255. The pixel location is
green [int] specified relative to the top left corner of the jit.lcd object's display area.
blue [int]
tilepict pict-name [symbol] Fills a rectangle by tiling a picture. The name of a jit.matrix object can be used in
dst-left [int] place of the name of a PICT file, provided that the named jit.matrix object is a 4
dst-top [int] plane char data matrix.
dst-right [int]
dst-bottom [int] Four optional integers can be used to specify a destination rectangle in which the
src-left [int] picture is tiled and four integers that specify the area of the picture to use in the
src-top [int] operation can be added. Destination and source rectangles are specified by their
src-right [int] left, top, width, and height values in pixels. The destination and source rectangles
src-bottom [int] are specified relative to the top left corner of the matrix. If no destination rectangle
is specified, the destination is set to the size of the lcd matrix and the source is set
to be the same size as the picture.

write symbol [symbol] Writes the text specified by the symbol argument at the current pen location,
using the current font and textmode.
writepict filename [symbol] Writes the current contents of the jit.lcd object's display area to a PICT file. If no
filename argument is present, a Save As dialog will prompt you to choose a
filename and location to write the PICT file.

Information for box attributes common to all objects

Examples
See Also
Name Description
jit.gl.sketch Use drawing commands with OpenGL
lcd Draw graphics in a patcher window
Tutorial 29: Using the Alpha Tutorial 29: Using the Alpha Channel
Channel
jit.linden
Lindenmayer string expansion (L-systems)

Description
The jit.linden object interprets an incoming 1-dim, 1-plane char matrix as a Lindenmayer System (L-system).

Matrix Operator
matrix inputs:1, matrix outputs:1
Name IOProc Planelink Typelink Dimlink Plane Dim Type
out n/a 1 1 1 1 1 char

Information for Jitter Matrix Operator (MOP) messages and attributes to this object

Attributes
Name Type g/s Description
boundmode int The starting cell for production matching (0 or 1) (default = 1)
'Start at Cell 0' = TEXT_HERE
'Start at Cell 1' = TEXT_HERE
ignore symbol Characters to ignore during context matching
leftbranch int The character value to be interpreted as the start of a branch in the Lindenmayer
string (default = 91 (ascii '['))
production symbol A list of symbols in the format left_context strict_predecessor right_context
successor_string ... that defines the production rules of the L-system (default =
none)
rightbranch int The character value to be interpreted as the start of a branch in the Lindenmayer
string (default = 93 (ascii ']'))
wildcard int The character value to be interpreted as a wildcard in the Lindenmayer string
(default = 42 (ascii '*'))

Information for box attributes common to all objects

Examples
See Also
Name Description
jit.conway Play Conway's game of life
jit.turtle 2-d turtle graphics interpreter
jit.luma2ayuv
Converts monochrome (luminance) to AYUV

Description
The jit.luma2ayuv object converts a 1-plane monochrome (lumninance) matrix to a 4-plane char AYUV (alpha, luminance, signed
chroma blue, signed chroma red) matrix.

Matrix Operator
matrix inputs:1, matrix outputs:1
Name IOProc Planelink Typelink Dimlink Plane Dim Type
out n/a 0 1 0 4 1 char

Information for Jitter Matrix Operator (MOP) messages and attributes to this object

Information for box attributes common to all objects

Examples

See Also
Name Description
jit.ayuv2uyvy Convert AYUV to UYVY
Converts monochrome (luminance) to AYUV
jit.colorspace Convert between colorspaces
jit.traffic Multiply the planar vector by a matrix
jit.luma2uyvy
Converts monochrome (luminance) to UYVY

Description
The jit.luma2uyvy object converts a 1-plane monochrome (lumninance) matrix to a 4-plane char UYVY (signed chroma blue,
luminance left, signed chroma red, luminance right) matrix.

Matrix Operator
matrix inputs:1, matrix outputs:1
Name IOProc Planelink Typelink Dimlink Plane Dim Type
out n/a 0 1 0 4 1 char

Information for Jitter Matrix Operator (MOP) messages and attributes to this object

Information for box attributes common to all objects

Examples

See Also
Name Description
jit.ayuv2uyvy Convert AYUV to UYVY
jit.luma2ayuv Converts monochrome (luminance) to AYUV
jit.colorspace Convert between colorspaces
jit.traffic Multiply the planar vector by a matrix
jit.lumakey
Key based on distance from a luminance value

Description
The jit.lumakey object measures the chromatic distance of each of the left input's cells (pixels) with a reference luminance
calulated by the formula
lum = (ascale * alpha_value) + (rscale * r_value) + (gscale * g_value) + (bscale * b_value).

If the distance is less than or equal to a tolerated distance (tol) value, the right input cell is multiplied by a maximum keying
(maxkey) value.

If the distance is greater than the tolerated distance but less than the sum of the tolerated value and a set fade value (fade) an
interpolated value between the some value between minkey and maxkey values is applied.

For values whose distance is greater than the sum of the tolerated and fade values, the right input cell is multiplied by the minkey
value.

The left input is always multiplied by the additive inverse of the left input's multiplicand.

The jit.lumakey object has two modes of output; the first keys between the two input sources, and the second mode will output the
keying values (i.e., the left input multiplicands) rather than applying the keying -- the left input is ignored. This is useful for
outputting keying information for use with other Jitter objects. Keying can be inverted by swapping the minkey and maxkey
values.

Matrix Operator
matrix inputs:2, matrix outputs:1
Name IOProc Planelink Typelink Dimlink Plane Dim Type
in2 resamp 1 1 1 4 1 char long float32 float64
out n/a 1 1 1 4 1 char long float32 float64

Information for Jitter Matrix Operator (MOP) messages and attributes to this object

Attributes
Name Type g/s Description
ascale float The alpha scaling factor (default = 0.)
bscale float The blue scaling factor (default = 0.114)
fade float Amount of fade (default = 0.)
gscale float The green scaling factor (default = 0.587)
lum float The reference luminance (default = all 0.)
maxkey float The maximum keying (maxkey) value (default = 1.)
minkey float The minimum keying (minkey) value (default = 0.)
mode int Output mode (default = 0 (output keyed matrix))
0 = perform keying and output matrix
1 = output the key map for use elsewhere
2 = alpha contains key map, other planes are from left input
'Composite' = TEXT_HERE
'Key Map in All Channels' = TEXT_HERE
'Key Map in Alpha' = TEXT_HERE
rscale float The red scaling factor (default = 0.299)
tol float The tolerated distance (tol) -- the range of variance from which an input cell's
absolute value can diverge when calculating keying (default = 0.)

Information for box attributes common to all objects


Examples

See Also
Name Description
jit.alphablend Blend two images with an alpha channel image
jit.chromakey Key images based on chromatic distance
jit.keyscreen Choke chromakey from 3 sources
jit.rgb2luma Converts RGB to monochrome (luminance)
jit.map
Map input range to output range

Description
The jit.map object maps input range to output range as specified by map attribute settings that specify input and output value
ranges.

Matrix Operator
matrix inputs:1, matrix outputs:1
Name IOProc Planelink Typelink Dimlink Plane Dim Type
out n/a 1 1 1 1 1 char long float32 float64

Information for Jitter Matrix Operator (MOP) messages and attributes to this object

Attributes
Name Type g/s Description
clip int Clipping flag (default = 1) When the flag is set, any input whose mapped value falls
outside the range specified by the output_lo and output_hi values is set to the
lower or upper boundary value.
map float Input to output map input_lo input_hi output_lo output_hi (default = 0. 1. 0.
1.) The range specified by input_lo to input_hi is mapped to the range specified by
output_lo to output_hi.

Information for box attributes common to all objects

Examples

See Also
Name Description
jit.charmap Map 256-point input to output
jit.clip Limit data to a range
jit.op Apply binary or unary operators
jit.scalebias Multiply and add
jit.matrix
The Jitter Matrix!

Description
The jit.matrix object is a named matrix which may be used for data storage and retrieval, resampling, and matrix type and
planecount conversion operations.

Messages
bang Outputs the currently stored matrix.
int values [list] Sets all cells to the value specified by value(s) and output the data. Position is
specified of a list whose length is equal to the number of dimensions (dimcount).
float values [list] Sets all cells to the value specified by value(s) and output the data. Position is
specified of a list whose length is equal to the number of dimensions (dimcount).
list values [list] Sets all cells to the value specified by value(s) and output the data. Position is
specified of a list whose length is equal to the number of dimensions (dimcount).
clear Sets all matrix values to zero.
exportimage filename [symbol] Export the current frame as an image file with the name specified by the first
file-type [symbol] argument. The optional second argument sets the file type (default = png).
use-dialog [int] Available file types are png, bmp, jpeg, macpaint, photoshop, pict, qtimage,
sgi, tga and tiff. An optional use-dialog argument of 1 will open a file dialog to
allow you to enter the image file settings.
exportmovie filename [symbol] Exports a matrix as a QuickTime movie. The exportmovie message takes an
FPS [float] optional argument to specify a file name. If no filename is specified, a file dialog
codec [symbol] will open to let you choose a file.
quality [symbol]
timescale [int] The default FPS is 30. frames per second

The default codec is raw. Supported codecs are raw, cinepak, graphics, animation,
video, componentvideo, jpeg, mjpega, mjpegb, sgi, planarrgb, macpaint, gif,
photocd, qdgx, avrjpeg, opendmljpeg, bmp, winraw, vector, qd, h261, h263,
dvntsc, dvpal, dvprontsc, dvpropal, flc, targa, png, tiff, componentvideosigned,
componentvideounsigned, cmyk, microsoft, sorenson, indeo4, argb64, rgb48,
alphagrey32, grey16, mpegyuv420, yuv420, and sorensonyuv9.

The default quality is max. Supported quality settings are lossless, max, min, low,
normal, and high. Note that minimum quality is, in many cases, the codec's
default quality. Use "low" quality for consistent results.

The default timescale is 600 units per second.

exprfill plane [int] Evaluates expression to fill the matrix. If a plane argument is provided, the
expression [symbol] expression is applied to a single plane. Otherwise, it is applied to allphanes in the
matrix. See jit.expr for more information on expressions. Unlike the jit.expr
object, there is no support for providing multiple expressions to fill multiple
planes at once with different expressions. Call this method multiple times once for
each plane you wish to fill.
getcell position [list] Sends the value(s) in the cell specified by position out the right outlet of the object
as a list in the form cell cell-position0 ... cell-positionN val plane0-value ...
planeN-value .
fillplane plane [int] The word fillplane, followed by an integer that specifies a plane number and a
value [int] value, will fill the specified plane with the single value.
importmovie filename [symbol] Imports a QuickTime movie into the matrix. If no filename is specified, a file
time-offset [int] dialog will open to let you choose a file. The time-offset argument may be used to
set a time offset for the QuickTime movie being imported (the default is 0).
jit_gl_texture texture-name [symbol] Copies the texture specified by texture-name to the matrix.
op The word op, followed by the name of a jit.op object operator and a set of values,
is equivalent to including a jit.op object with the specified operator set as an
attribute and this jit.matrix object specified as the output matrix. The additional
value arguments may either be a matrix name or a constant. If only one value
argument is provided, this matrix is considered both the output and the left
operand. For example, "op + foo bar" is equivalent to the operation thismatrix =
foo + bar, and "op * 0.5" is equivalent to the operation thismatrix = thismatrix *
0.5.
read filename [symbol] Reads Jitter binary data files (.jxf) into a matrix set. If no filename is specified, a
file dialog will open to let you choose a file.
setall values [list] Sets all cells to the value specified by value(s). Position is specified of a list whose
length is equal to the number of dimensions (dimcount).
setcell position [list] Sets the cell specified by position to the value specified by value. Position is
group (optional) specified of a list whose length is equal to the number of dimensions (dimcount).
plane [literal] The optional arguments plane plane-number can be used to specify a plane. If a
plane-number [int] plane is specified, value should be a single number, otherwise it should be a list of
end group numbers of size planecount - 1.
val [literal]
values [list]
setcell1d The word setcell1d, followed by a number specifying an x coordinate and a list of
values, is similar to the setcell message but without the need to use a "val" token
to separate the coordinates from the value since the dimension count (1) is fixed.
setcell2d The word setcell2d, followed by a pair of numbers specifying x and y coordinates
and a list of values, is similar to the setcell message but without the need to use a
"val" token to separate the coordinates from the value since the dimension count
(2) is fixed.
setcell3d The word setcell3d, followed by three numbers specifying x , y , and z coordinates
and a list of values, is similar to the setcell message but without the need to use a
"val" token to separate the coordinates from the value since the dimension count
(3) is fixed.
setplane1d The word setplane1d, followed by a number specifying an x coordinate, a number
specifying a plane, and a value, is similar to the setcell message but without the
need to use a "val" token to separate the coordinates from the value since the
dimension count (1) is fixed, or use the "plane" token to specify which plane to set.
setplane2d The word setplane2d, followed by a pair of numbers specifying x and y
coordinates, a number specifying a plane, and a value, is similar to the setcell
message but without the need to use a "val" token to separate the coordinates
from the value since the dimension count (2) is fixed, or use the "plane" token to
specify which plane to set.
setplane3d The word setplane3d, followed by three numbers specifying x , y , and z
coordinates, a number specifying a plane, and a value, is similar to the setcell
message but without the need to use a "val" token to separate the coordinates
from the value since the dimension count (1) is fixed, or use the "plane" token to
specify which plane to set.
val values [list] Sets all cells to the value specified by value(s). Position is specified of a list whose
length is equal to the number of dimensions (dimcount) and outputs the data.
write filename [symbol] Writes matrix set as a Jitter binary data file (.jxf). If no filename is specified, a file
dialog will open to let you choose a file.

Attributes
Name Type g/s Description
name symbol The name of the matrix (default = UID)
adapt int Matrix adaptation flag (default = 0 if matrix arguments are present, otherwise 1)
When the flag is set, the jit.matrix object will adapt to the incoming matrix
planecount, type, and dimensions.
thru int Thru mode flag (default = 1) When the flag is set, a matrix is output when another
one is received.
interp int Matrix interpolation flag (default = 0) When the flag is set, the input matrix will
be interpolated when copied to the internal matrix.
planemap int Maps input places to output planes (default = 0 1 2 3 ...)
srcdimstart int The source dimension start position (default = all 0)
srcdimend int The source dimension end position (default = all dim values minus 1)
dstdimstart int The destination dimension start position (default = all 0)
dstdimend int The destination dimension end position (default = all dim values minus 1)
usesrcdim int Srcdim use flag (default = 0) When the flag is set, the source dimension's
attributes are used when copying an input matrix to an internal matrix.
usedstdim int Destdim use flag (default = 0) When the flag is set, the destination dimension's
attributes are used when copying an input matrix to an internal matrix.
dim int The dimensions of matrix data (default = 1 1)
dimstride int (get) The byte stride per dimension
planecount int The number of planes in matrix data (default = 4)
size int (get) Total byte size of matrix
type symbol The matrix data type (default = char)
'char' = Char data
'long' = Long data
'float32' = 32-bit floating-point data
'float64' = 64-bit floating-point data

Information for box attributes common to all objects

Examples

See Also
Name Description
jit.coerce Coerce a matrix into different types/planecount
jit.fill Fill a matrix with a list
jit.matrixset A set of matrices for storage/resequencing
jit.matrixinfo Report matrix planecount, type, dimensions
jit.peek~ Read matrix data as an audio signal
jit.poke~ Write an audio signal into a matrix
jit.spill Unroll a matrix into a list
jit.submatrix Reference a sub-region of a matrix
Tutorial 2: Create a Matrix Tutorial 2: Create a Matrix
Tutorial 11: Lists and Matrices Tutorial 11: Lists and Matrices
Tutorial 14: Matrix Positioning Tutorial 14: Matrix Positioning
Tutorial 16: Using Named Jitter Tutorial 16: Using Named Jitter Matrices
Matrices
Tutorial 18: Iterative Processes Tutorial 18: Iterative Processes and Matrix Re-Sampling
and Matrix Re-Sampling
Tutorial 20: Importing and Tutorial 20: Importing and Exporting Single Matrices
Exporting Single Matrices
Tutorial 31: Rendering Tutorial 31: Rendering Destinations
Destinations
Tutorial 39: Spatial Mapping Tutorial 39: Spatial Mapping
Tutorial 42: Slab: Data Processing Tutorial 42: Slab: Data Processing on the GPU
on the GPU
jit.matrixinfo
Report matrix planecount, type, dimensions

Description
jit.matrix reports a given matrix's planecount, type, and dim attributes in the form
planecount number-of-planes
type data-type
dim dimension0 ... dimensionN .

Arguments
None.

Information for box attributes common to all objects

Examples

See Also
Name Description
jit.matrix The Jitter Matrix!
jit.fpsgui Display fps, ms, and matrix attributes
jit.print Print a matrix in the Max window
jit.matrixset
A set of matrices for storage/resequencing

Description
The jit.matrixset object keeps a set of internal matrices which may be written to or read from. This may be useful for data storage
and/or matrix resequencing.

Arguments
None.

Messages
bang Sends a matrix out the left outlet.
clear Sets all values to zero.
exportmovie filename [symbol] Exports a matrix as a QuickTime movie. The exportmovie message takes an
FPS [float] optional argument to specify a file name. If no filename is specified, a file dialog
codec [symbol] will open to let you choose a file.
quality [symbol]
timescale [int] The default FPS is 30. frames per second

The default codec is raw. Supported codecs are raw, cinepak, graphics, animation,
video, componentvideo, jpeg, mjpega, mjpegb, sgi, planarrgb, macpaint, gif,
photocd, qdgx, avrjpeg, opendmljpeg, bmp, winraw, vector, qd, h261, h263,
dvntsc, dvpal, dvprontsc, dvpropal, flc, targa, png, tiff, componentvideosigned,
componentvideounsigned, cmyk, microsoft, sorenson, indeo4, argb64, rgb48,
alphagrey32, grey16, mpegyuv420, yuv420, and sorensonyuv9.

The default quality is max. Supported quality settings are lossless, max, min, low,
normal, and high. Note that minimum quality is, in many cases, the codec's
default quality. Use "low" quality for consistent results.

The default timescale is 600 units per second

importmovie filename [symbol] Imports a QuickTime movie into the matrix set. If no filename is specified, a file
time-offset [int] dialog will open to let you choose a file. The time-offset and index-offset
index-ffset [int] arguments may be used to set a time and index offset for the QuickTime movie
number-of-frames [int] being imported (the default is 0 for both arguments). The number-of-frames
argument specifies the number of frames to import (the default is set to the value
specified by the matrixcount attribute). Note that the importmovie message will
not resize the jit.matrixset.
read filename [symbol] Reads Jitter binary data files (.jxf) into a matrix set. If no filename is specified, a
file dialog will open to let you choose a file.
write filename [symbol] Writes matrix set as a Jitter binary data file (.jxf). If no filename is specified, a file
dialog will open to let you choose a file.

Attributes
Name Type g/s Description
index int The which of the matrices an incoming matrix will be written to (default = 0)
matrixcount int The number of matrices in the matrix set (default = 1)
planecount int The number of planes in matrix data (default = 4)
type symbol The type of matrix data (default = char) Supported data types are char, long,
float32, or float64.
dim int The dimensions of matrix data (default = 1 1)
thru int Thru mode flag (default = 1) When the flag is set, a matrix is output when another
one is received.
interp int Interpolation flag (default = 0) When the flag is set, an input matrix is
interpolated when copied to internal matrices.
planemap int Maps input planes to output planes (default = 0 1 2 3 ...)
srcdimstart int The source dimension start position (default = all 0)
srcdimend int The source dimension end position (default = all dim values minus 1)
dstdimstart int The source dimension start position (default = all 0)
dstdimend int The destination dimension end position (default = all dim values minus 1)
usesrcdim int Srcdim use flag (default = 0) When the flag is set, the source dimension's
attributes are used when copying an input matrix to an internal matrix.
usedstdim int Destdim use flag (default = 0) When the flag is set, the destination dimension's
attributes are used when copying an input matrix to an internal matrix.

Information for box attributes common to all objects

Examples

See Also
Name Description
jit.matrix The Jitter Matrix!
Tutorial 20: Importing and Tutorial 20: Importing and Exporting Single Matrices
Exporting Single Matrices
jit.mgraphics
2D Vector Graphics

Description
The jit.mgraphics object supports drawing 2D vector graphics with the MGraphics API.

Matrix Operator
matrix inputs:0, matrix outputs:1
Name IOProc Planelink Typelink Dimlink Plane Dim Type
out n/a 1 1 1 4 1 char

Information for Jitter Matrix Operator (MOP) messages and attributes to this object

Messages
append_path path [symbol] Add a path to a graphics context.

arc xc [float] Add a circular, clockwise, arc to the current path.


yc [float]
radius [float]
angle1 [float]

angle2 [float]

arc_negative xc [float] Add a circular, counter-clockwise, arc to the current path.


yc [float]
radius [float]
angle1 [float]

angle2 [float]

close_path Close the current path in a context.


curve_to x1 [float] Add a cubic Bezier spline to the current path.
y1 [float]
x2 [float]
y2 [float]
x3 [float]
y3 [float]
ellipse x [float] Add a closed elliptical path in the context.
y [float]
width [float]
height [float]
device_to_user x [float] Converts device coordinates to user coordinates. User coordinates are those
y [float] passed to drawing functions. Device coordinates are those of the display
device. The result is sent out the dumpout outlet with a device_to_user
prefix.
get_current_point Get the current location of the cursor in a graphics context. The result is sent
out the dumpout outlet with a get_current_point prefix.
font_extents Return the extents of the currently selected font. The result is 3 floating point
numbers of the form ascent, descent, height, and is sent out the dumpout
outlet with a font_extents prefix.
get_matrix Return the transform matrix. The result is 6 floating point numbers of the
form xx, yx, xy, yy, x0, y0, and is sent out the dumpout outlet with a
get_matrix prefix.
get_line_cap Return the current line cap style. The result is a symbol, and is sent out the
dumpout outlet with a get_line_cap prefix.
get_line_join Return the current line join style. The result is a symbol, and is sent out the
dumpout outlet with a get_line_join prefix.
get_line_width Return the current line width. The result is a floating point number, and is
sent out the dumpout outlet with a get_line_width prefix.
getfontlist Return the current font list. The result is a list of symbols, and is sent out the
dumpout outlet with a getfontlist prefix.
fill Fill the current path, discarding the path once filled.
fill_extents Return the current path's extents if filled. The result is 4 floating point
numbers of the form x1, y1, x2, y2, and is sent out the dumpout outlet with a
fill_extents prefix.
fill_preserve Fill the current path, preserving the path for further path operations.
fill_preserve_with_alpha alpha [float] Fill the current path, applying a global alpha, and preserving the path for
further path operations.
fill_with_alpha alpha [float] Fill the current path, applying a global alpha, and discarding the path once
filled.
identity_matrix Set the current transform to be the identity matrix.
image_surface_create name Create a named image surface, filling with the contents of specified source.
[symbol] Source can be a file name or a matrix name.
source
[symbol]
width [float]
height [float]
image_surface_destroy name Destroy a named image surface.
[symbol]
image_surface_draw source Draw an image surface. Supports zoom, but not rotations. Source can be a
[symbol] surface name, file name or a matrix name.
image_surface_draw_fast source Draw an image surface quickly. Does not support zoom or rotations. Source
[symbol] can be a surface name, file name or a matrix name.
image_surface_get_size name Return the size of an image surface. The result is sent out the dumpout outlet
[symbol] with a image_surface_get_size prefix.
in_fill x [float] Check if a point is in the current path's fill region. The result is sent out the
y [float] dumpout outlet with a in_fill prefix.
line_to x [float] Add a line segment to the current path.
y [float]
new_path Begin a new path.
move_to x [float] Move the cursor to a new point and begin a new subpath.
y [float]
paint Paint current source in entire current clip region.
paint_with_alpha Paint current source with alpha in entire current clip region.
path_roundcorners corner_radius Round out any corners in a path.
[float]
pattern_add_color_stop_rgba pattern_name Add a color stop to a gradient pattern.
[symbol]
offset [float]
red [float]
green [float]
blue [float]
alpha [float]
pattern_create_for_surface pattern_name Create a named image pattern, filling with the contents of specified source.
[symbol] Source can be an image surface name, a file name, or a matrix name.
source
[symbol]
pattern_create_linear pattern_name Create a named linear gradient pattern.
[symbol]
x0 [float]
y0 [float]
x1 [float]
y1 [float]
pattern_create_radial pattern_name Create a named radial gradient pattern.
[symbol]
cx0 [float]
cy0 [float]
radius0
[float]
cx1 [float]
cy1 [float]
radius1
[float]
pattern_create_rgba pattern_name Create a named solid color pattern.
[symbol]
red [float]
green [float]
blue [float]
alpha [float]
pattern_destroy pattern_name Destroy a named pattern.
[symbol]
pattern_get_extend pattern_name Get the pattern's extend mode. The result is sent out the dumpout outlet with
[symbol] a pattern_get_extend prefix.
pattern_get_matrix pattern_name Get the pattern's transform matrix. The result is sent out the dumpout outlet
[symbol] with a pattern_get_matrix prefix.
pattern_get_type pattern_name Get the pattern's type. The result is sent out the dumpout outlet with a
[symbol] pattern_get_type prefix.
pattern_identity_matrix pattern_name Set the pattern's transform matrix to the identity matrix.
[symbol]
pattern_rotate pattern_name Rotate the pattern's transform matrix.
[symbol]
radians
[float]
pattern_translate pattern_name Translate the pattern's transform matrix.
[symbol]
tx [float]
ty [float]
pattern_scale pattern_name Scale the pattern's transform matrix.
[symbol]
sx [float]
sy [float]
pattern_set_extend pattern_name Set a pattern's extend mode. Values can be: none, repeat, reflect, or pad.
[symbol] However, many of these are not implemented for various pattern types.
extend_mode
[symbol]
pattern_set_matrix pattern_name Set the pattern's transform matrix.
[symbol]
xx [float]
xy [float]
yx [float]
yy [float]
x0 [float]
y0 [float]
ovalarc xc [float] Add a non-circular arc to the current path.
yc [float]
radiusx
[float]
radiusy
[float]
angle1 [float]

angle2 [float]

pop_group_to_source Pops the current group to the current source pattern.


push_group Temporarily redirects drawing to an intermediate surface known as a group.
Use pop_group, pop_group_to_source, or pop_group_to_surface to use it.
scale_source_rgba redscale Set the source color transform's scale factor.
[float]
greenscale
[float]
bluescale
[float]
alphascale
[float]
set_line_join style Set the current line join style. Values can be: miter, round, or bevel.
[symbol]
set_line_width width [float] Set the current line width.
set_source source Set the current source to the named pattern or image surface.
[symbol]
set_source_surface source Set the current source to the named image surface or file name.
[symbol]
set_source_rgb red [float] Set the current source color.
green [float]
blue [float]
svg_create svg_name Create a named svg object, filling with the contents of specified source.
[symbol] Source can be a file name, or an XML svg string.
source
[symbol]
svg_destroy svg_name Destroy a named svg object.
[symbol]
svg_get_size svg_name Get a named svg object's size. The result is sent out the dumpout outlet with a
[symbol] svg_get_size prefix.
svg_render svg_name Render a named svg object.
[symbol]
rectangle x [float] Add a closed rectangle path in the context.
y [float]
width [float]
height [float]
rectangle_rounded x [float] Add a closed rounded-rectangle path in the context.
y [float]
width [float]
height [float]
ovalwidth
[float]
ovalheight
[float]
rel_curve_to x1 [float] Add a cubic Bezier spline to the current path, using coordinates relative to the
y1 [float] current point.
x2 [float]
y2 [float]
x3 [float]
y3 [float]
rel_line_to x [float] Add a line segment to the current path, using coordinates relative to the
y [float] current point.
rel_move_to x [float] Move the cursor to a new point and begin a new subpath, using coordinates
y [float] relative to the current point.
select_font_face fontfamily Specify a font for a graphics context. The slant may be normal or italic, and
[symbol] The weight may be normal or bold.
slant
[symbol]
weight
[symbol]
set_font_size size [float] Specify the font size.
show_text text [symbol] Display text at the current position.
rotate radians Rotate the transform matrix.
[float]
text_measure text [symbol] Return the height and width of a string given current graphics settings in a
context. The result is sent out the dumpout outlet with a text_measure
prefix.
text_path text [symbol] Add a path of text to the current path.
transform xx [float] Multiply the transform matrix by another matrix.
xy [float]
yx [float]
yy [float]
x0 [float]
y0 [float]
translate tx [float] Translate the transform matrix.
ty [float]
save Saves the current graphics settings to be restored later ("pushes" the graphics
state stack).
scale tx [float] Scale the transform matrix.
ty [float]
set_matrix xx [float] Set the transform matrix.
xy [float]
yx [float]
yy [float]
x0 [float]
y0 [float]
restore Restores the saved graphics settings ("pops" the graphics state stack).
set_source_rgba red [float] Set the current source color.
green [float]
blue [float]
alpha [float]
user_to_device x [float] Converts user coordinates to device coordinates. User coordinates are those
y [float] passed to drawing functions. Device coordinates are those of the display
device. The result is sent out the dumpout outlet with a user_to_device
prefix.
translate_source_rgba redoffset Set the source color transform's offset values.
[float]
greenoffset
[float]
blueoffset
[float]
alphaoffset
[float]
set_line_cap style Set the current line cap style. Values can be: butt, round, or square.
[symbol]
stroke Stroke the current path, discarding the path once filled.
stroke_preserve Stroke the current path, preserving the path for further path operations.
stroke_preserve_with_alpha alpha [float] Stroke the current path, applying a global alpha, and preserving the path for
further path operations.
stroke_with_alpha alpha [float] Stroke the current path, applying a global alpha, and discarding the path once
filled.

Attributes
Name Type g/s Description
autofill int Automatially fill paths when closed.
dim int Dimensions.
relative_coords int Use relative coordinates (0.-1. rather than pixels).

Information for box attributes common to all objects

Examples

See Also
Name Description
jit.lcd QuickDraw wrapper
jit.gl.sketch Use drawing commands with OpenGL
jsui Create user interfaces with Javascript
MGraphics Quick Start Guide MGraphics Quick Start Guide
jit.multiplex
Multiplex (interleave) two matrices into one matrix

Description
The jit.multiplex object takes two matrices as input, and derives a single output matrix from it by interleaving the input matrices
across a specified dimension.

Matrix Operator
matrix inputs:2, matrix outputs:1
Name IOProc Planelink Typelink Dimlink Plane Dim Type
in2 adapt 0 0 0 1 1 char long float32 float64
out n/a 0 0 0 1 1 char long float32 float64

Information for Jitter Matrix Operator (MOP) messages and attributes to this object

Attributes
Name Type g/s Description
autoclear int Matrix clear following output flag (default = 1)
mode int Matrix underflow mode (default = 0 (stop))
0 = stop: If one input matrix is exhausted before the other, do nothing
1 = wrap: If one input matrix is exhausted before the other, return to that matrix's
beginning and continue until the second matrix is also exhausted
2 = clip: If one input matrix is exhausted before the other, repeat that matrix's
final sample until the second matrix is also exhausted
multiplexdim int The dimension across which multiplexing occurs (default = 0). The most common
arguments specify horizontal (i.e., dim[0]) or vertical (dim[1]) multiplexing.
scan_a int The number of scanlines to sample from the left input matrix (default = 1)
scan_b int The number of scanlines to sample from the right input matrix (default = 1)
truncate int Input truncation flag (default = 1) When the flag is set, the right input's
dimensions are truncated to the left input's dimensions if the right dimensions are
greater than the left. Truncation is performed for all dimensions except the
multiplex dimension. Otherwise, no truncation occurs.

Information for box attributes common to all objects

Examples
See Also
Name Description
jit.concat Concatenate two matrices
jit.demultiplex Demultiplex (deinterleave) one matrix into two
jit.glue Glue many matrices into one
jit.matrix The Jitter Matrix!
jit.scissors Cut up a matrix into evenly spaced sub matrices
jit.split Split a matrix into two matrices
jit.mxform2d
Spatial transform using 3x3 matrix

Description
The jit.mxform2d object performs a 2-dimensional matrix transform on an input matrix. It can be used to perform scaling,
rotation, skewing, and perspective operations.

Matrix Operator
matrix inputs:1, matrix outputs:1
Name IOProc Planelink Typelink Dimlink Plane Dim Type
out n/a 1 1 1 1 1 char long float32 float64

Information for Jitter Matrix Operator (MOP) messages and attributes to this object

Attributes
Name Type g/s Description
boundmode int Boundary handling mode (default = 3 (clip))
0 = ignore: Values that exceed the limits are ignored.
1 = clear: Values that exceed the limits are set to 0.
2 = wrap: Values that exceed the limits are wrapped around to the opposite limit
with a modulo operation.
3 = clip: Values are limited not to exceed width or height.
4 = fold: Values that exceed the limits are folded back in the opposite direction.
interp int Interpolation flag (default = 0) If enabled, the object resamples the image and
then interpolates back to the original size.
mxform float A list of nine variables ( a b u c d v tx ty w ) used in the matrix transform
calculations (default 1. 0. 0. 0. 1. 0. 0. 0. 1.)
offset_x int The horizontal offset in pixels from the upper left corner for the displayed matrix
(default = 0). Positive values shift right, negative values shift left.
offset_y int The vertical offset in pixels from the upper left corner for the displayed matrix
(default = 0). Positive values shift down, negative values shift up.

Information for box attributes common to all objects

Examples
See Also
Name Description
jit.repos Reposition spatially
jit.rota Scale/rotate in 2D
jit.net.recv
Receive matrices from a jit.net.send object via TCP/IP

Description
Use jit.net.recv to output matrices and messages sent over a network connection by jit.net.send.

Matrix Operator
matrix inputs:0, matrix outputs:1
Name IOProc Planelink Typelink Dimlink Plane Dim Type
out n/a 1 1 1 1 1 char long float32 float64

Information for Jitter Matrix Operator (MOP) messages and attributes to this object

Messages
getmatrix Retrieves the next incoming matrix. This message is only useful when used in
conjunction with Javascript, Java, and C.
getmessage Retrieves the next incoming message. This message is only useful when used in
conjunction with Javascript, Java, and C.

Attributes
Name Type g/s Description
connected int Whether or not the object is currently connected to a jit.net.send client.
ip symbol The IP address to monitor for incoming connections (default = ANY)
port int The port to monitor for incoming connections (default = 7474)

Information for box attributes common to all objects

Examples

See Also
Name Description
jit.broadcast Broadcast video using RTSP
jit.net.send Send matrices to a jit.net.recv object via TCP/IP
jit.qt.broadcast Broadcast video using RTSP (Macintosh only)
Tutorial 52: Jitter Networking Tutorial 52: Jitter Networking
jit.net.send
Send matrices to a jit.net.recv object via TCP/IP

Description
Use jit.net.send to send matrices and messages over a network connection to an instance of jit.net.recv.

Matrix Operator
matrix inputs:1, matrix outputs:0
Name IOProc Planelink Typelink Dimlink Plane Dim Type

Information for Jitter Matrix Operator (MOP) messages and attributes to this object

Messages
int Any number sent in the object's right inlet is output by the middle outlet of the
connected jit.net.recv.
float Any number sent in the object's right inlet is output by the middle outlet of the
connected jit.net.recv.
anything matrix-name [symbol] Any message sent in the object's right inlet is output by the middle outlet of the
connected jit.net.recv.

Attributes
Name Type g/s Description
connected int Whether or not the object is currently connected to a jit.net.recv server.
host symbol The domain name to form a connection with (default = localhost)
ip symbol The IP address to form a connection with (default = 127.0.0.1, the local loopback)
latency float An estimate of the time between a matrix being input to the jit.net.send object
and being output from the corresponding jit.net.recv.
nagle int Toggles the use of Nagle's algorithm flag (default is 0/off). Improves network
efficiency for small packet sizes, though at the possible expense of latency.
port int The port to use when creating the connection (default = 7474)
report int Toggles the report connected flag (default is 1/on). When enabled, the jit.net.recv
object will report connection information out the dumpout outlet.

Information for box attributes common to all objects

Examples
See Also
Name Description
jit.broadcast Broadcast video using RTSP
jit.net.recv Receive matrices from a jit.net.send object via TCP/IP
jit.qt.broadcast Broadcast video using RTSP (Macintosh only)
Tutorial 52: Jitter Networking Tutorial 52: Jitter Networking
jit.noise
Generate white noise

Description
jit.noise generates matrices of random values.

Matrix Operator
matrix inputs:0, matrix outputs:1
Name IOProc Planelink Typelink Dimlink Plane Dim Type
out n/a 1 1 1 1 1 char long float32 float64

Information for Jitter Matrix Operator (MOP) messages and attributes to this object

Information for box attributes common to all objects

Examples

See Also
Name Description
drunk Output random numbers within a step range
jit.sprinkle Introduce spatial noise
random Generate a random number
Tutorial 17: Feedback Using Tutorial 17: Feedback Using Named Matrices
Named Matrices
jit.normalize
Normalizes a matrix.

Description
jit.normalize examines a jit.matrix and scales the minimum and maximum values to a normalized range.

Matrix Operator
matrix inputs:1, matrix outputs:1
Name IOProc Planelink Typelink Dimlink Plane Dim Type
out n/a 1 1 1 1 1 char long float32 float64

Information for Jitter Matrix Operator (MOP) messages and attributes to this object

Attributes
Name Type g/s Description
amp float The amplitude to scale the normalized range. (default = 1)
global int Flag to enable or disable global normalization across all planes. (default = 0)

Information for box attributes common to all objects

Examples

See Also
Name Description
jit.matrix The Jitter Matrix!
jit.bfg Evaluate a procedural basis function graph
Tutorial 50: Procedural Texturing Tutorial 50: Procedural Texturing & Modeling
& Modeling
jit.obref
Launch html object reference

Description
The jit.obref object takes one object-name argument. When double clicked, the jit.obref object will find the html object reference
file corresponding to the object specified by object-name and launch it in Max's Documentation Window. The html object
reference file must be located in the Max search path.

Arguments
None.

Messages
bang Equivalent to double clicking the object.
anything object-name [list] Sets the current object-name .
(mouse) When double clicked, the jit.obref object will find the html object reference file
corresponding to the object specified by object-name and launch it in Max's
Documentation Window. The html object reference file must be located in the Max
search path.

Information for box attributes common to all objects

Examples

See Also
Name Description
jit.uldl Internet upload/download
jit.op
Apply binary or unary operators

Description
The jit.op object applies either a binary operator to two input matrices, or a unary operator to the left input matrix. A different
operator may be specified for each plane, or a scalar may be specified via the val attribute as an alternate to using a second
matrix.

Matrix Operator
matrix inputs:2, matrix outputs:1
Name IOProc Planelink Typelink Dimlink Plane Dim Type
in2 resamp 1 1 1 1 1 char long float32 float64
out n/a 1 1 1 1 1 char long float32 float64

Information for Jitter Matrix Operator (MOP) messages and attributes to this object

Messages
int Sets a value to int.
float Sets a value to float.
list Sets value to list.

Attributes
Name Type g/s Description
val atom The value to use as right hand operand instead of a matrix (default = 0) If one
value is specified it applies to all planes. If multiple values are specified they are
applied on a plane by plane basis. IMPORTANT : If the incoming matrix data has
typechar, then integers in the range 0-255 are mapped to the floating point data
range 0.- .996 (A value of 1. (char 255) is not really 1. That value is not
representable in 8-bit fixed point, since it would be 256. Thus, floating point
values greater than 1. become 1.0 - 1/256.0, or 0.996).
op symbol The operator to be used (default = pass) If one operator is specified, it is applied to
all planes. If multiple operators are specified, they are applied on a plane by plane
basis.

Arithmetic Operators:
pass = pass left input, no operator
* = multiplication (also mult)
/ = division (also div)
+ = addition (also add)
- = subtraction (also sub)
+m = addition modulo (char only) (also addm)
-m = subtraction modulo (char only) (also subm)
% = modulo (also mod)
min = minimum
max = maximum
abs = absolute value (unary)
avg = average
absdiff = absolute value of difference
fold = folding/mirrored modulo (float only)
wrap = wrapping/positive modulo (float only)
!pass = pass right input, no operator
!/ = right input divided by left input (flipped)
!- = right input minus left input (flipped)
!% = right input modulo left input (flipped)
ignore = leave previous output value
Trigonometric Operators: (float32/float64 only, unary except atan2)
sin = sine
cos = cosine
tan = tangent
asin = arcsine
acos = arccosine
atan = arctangent
atan2 = arctangent (binary)
sinh = hyperbolic sine
cosh = hyperbolic cosine
tanh = hyperbolic tangent
asinh = hyperbolic arcsine
acosh = hyperbolic arccosine
atanh = hyperbolic arctangent

Bitwise Operators: (long/char only)


& = bitwise and
| = bitwise or
^ = bitwise xor
~ = bitwise compliment (unary)
>> = right shift
<< = left shift

Logical operators
&& = logical and
|| = logical or
! = logical not (unary)
> = greater than
< = less than
>= = greater than or equal to
<= = less than or equal to
== = equal
!= = not equal
>p = greater than (pass)
<p = less than (pass)
>=p = greater than or equal to (pass)
<=p = less than or equal to (pass)
==p = equal (pass)
!=p not equal (pass)

Exponential/Logarithmic/Other: (float32/float64 only, unary except hypot and


pow)
exp = e to the x
exp2 = 2 to the x
ln = log base e
log2 = log base 2
log10 = log base 10
hypot = hypotenuse (binary)
pow = x to the y (binary)
sqrt = square root
ceil = integer ceiling
floor = integer floor
round = round to nearest integer
trunc = truncate to integer

'*' = TEXT_HERE
'/' = TEXT_HERE
'+' = TEXT_HERE
'sub' = TEXT_HERE
'!/' = TEXT_HERE
'!-' = TEXT_HERE
'+m' = TEXT_HERE
'-m' = TEXT_HERE
'%' = TEXT_HERE
'!%' = TEXT_HERE
'min' = TEXT_HERE
'max' = TEXT_HERE
'avg' = TEXT_HERE
'abs' = TEXT_HERE
'absdiff' = TEXT_HERE
'pass' = TEXT_HERE
'!pass' = TEXT_HERE
'fold' = TEXT_HERE
'wrap' = TEXT_HERE
'&' = TEXT_HERE
'|' = TEXT_HERE
'^' = TEXT_HERE
'~' = TEXT_HERE
'>>' = TEXT_HERE
'<<' = TEXT_HERE
'&&' = TEXT_HERE
'||' = TEXT_HERE
'!' = TEXT_HERE
'>' = TEXT_HERE
'<' = TEXT_HERE
'>=' = TEXT_HERE
'<=' = TEXT_HERE
'==' = TEXT_HERE
'!=' = TEXT_HERE
'>p' = TEXT_HERE
'<p' = TEXT_HERE
'>=p' = TEXT_HERE
'<=p' = TEXT_HERE
'==p' = TEXT_HERE
'!=p' = TEXT_HERE
'sin' = TEXT_HERE
'cos' = TEXT_HERE
'tan' = TEXT_HERE
'asin' = TEXT_HERE
'acos' = TEXT_HERE
'atan' = TEXT_HERE
'atan2' = TEXT_HERE
'sinh' = TEXT_HERE
'cosh' = TEXT_HERE
'tanh' = TEXT_HERE
'asinh' = TEXT_HERE
'acosh' = TEXT_HERE
'atanh' = TEXT_HERE
'exp' = TEXT_HERE
'exp2' = TEXT_HERE
'ln' = TEXT_HERE
'log' = TEXT_HERE
'log2' = TEXT_HERE
'log10' = TEXT_HERE
'hypot' = TEXT_HERE
'pow' = TEXT_HERE
'sqrt' = TEXT_HERE
'ceil' = TEXT_HERE
'floor' = TEXT_HERE
'round' = TEXT_HERE
'trunc' = TEXT_HERE
Information for box attributes common to all objects

Examples

See Also
Name Description
expr Evaluate a mathematical expression
jit.expr Evaluate an expression to fill a matrix
jit.dimop Downsample using operators across dimensions
jit.planeop Operator across planes
vexpr Evaluate a math expression for a list
Tutorial 3: Math Operations on a Tutorial 3: Math Operations on a Matrix
Matrix
Tutorial 5: ARGB Color Tutorial 5: ARGB Color
Tutorial 9: More Mixing Tutorial 9: More Mixing
Tutorial 18: Iterative Processes Tutorial 18: Iterative Processes and Matrix Re-Sampling
and Matrix Re-Sampling
Tutorial 45: Introduction to using Tutorial 45: Introduction to using Jitter within JavaScript
Jitter within JavaScript
jit.openexr
Read or write an OpenEXR image.

Description
Converts an OpenEXR image to and from a jit.matrix object for an arbitrary number of planes or color components.

Matrix Operator
matrix inputs:1, matrix outputs:1
Name IOProc Planelink Typelink Dimlink Plane Dim Type
out n/a 1 1 1 1 1 char long float32 float64

Information for Jitter Matrix Operator (MOP) messages and attributes to this object

Messages
read filename [symbol] Reads the given file into a jit.matrix using the indicated channels listed in the
channel attribute.
write filename [symbol] Writes the current jit.matrix to disk as an OpenEXR image file using the indicated
channels listed in the channel attribute.

Attributes
Name Type g/s Description
adjust int Flag to enable or disable adjusting the HDR image data through ILM's proposed
display mapping pipeline (default = 0). When enabled, the exposure, defog,
kneehigh, kneelow, and normalize attributes can be used to control the following
display mapping process:

1. Compensate for fogging by subtracting defog from the raw pixel values.
2. Multiply the defogged pixel values by 2(exposure + 2.47393).
3. Values, which are now 1.0, are called "middle gray." If defog and exposure are
both set to 0.0, then middle gray corresponds to a raw pixel value of 0.18. In step
6, middle gray values will be mapped to an intensity 3.5 f-stops below the display's
maximum intensity.
4. Apply a knee function. The knee function has two parameters, kneeLow and
kneeHigh. Pixel values below 2kneeLow are not changed by the knee function.
Pixel values above kneeLow are lowered according to a logarithmic curve, such
that the value 2kneeHigh is mapped to 23.5 (in step 6, this value will be mapped to
the display's maximum intensity).
5. Gamma-correct the pixel values.
6. Scale the values such that middle gray pixels are mapped to 84.66 (or 3.5 f-
stops below the display's maximum intensity).
7. If converting to 8 bit unsigned integer values (char), clamp the values to [0,
255].
channels symbol The list of channel names to use. When reading an OpenEXR file into a jit.matrix
object, these channels will be mapped to sequential planes. If a channel does not
exist it will be filled with zeros. When writing a jit.matrix object, the names listed
in this list will be used to name each plane as they are stored in the OpenEXR file.
(default = null)
defog float Value subtracted from pixel values to compensate for fogging due to stray light in
the recording device (default = 0.0).
exposure float Sets the apparent exposure of the image on the display. It lightens or darkens the
displayed image, allowing you to reveal detail in the high or low end. (default =
0.0)
gamma float Coefficient to use for gamma correcting the pixel values (default = 2.2)
kneehigh float Pixel values between kneeHigh and kneeLow set the white level of the displayed
image, determining which value is mapped to the maximum intensity of the
monitor (default = 3.5)
kneelow float Pixel values between kneehigh and kneelow set the white level of the displayed
image, determining which value is mapped to the maximum intensity of the
monitor (default = 0.0).
normalize int Flag to enable or disable normalization for rempping the floating point data into a
uniform range of 0-1. This operation will be performed before the display mapping
process. (default = 0)
verbose int Toggles the printing of information to Max Window.

Information for box attributes common to all objects

Examples

See Also
Name Description
jit.matrix The Jitter Matrix!
jit.bfg Evaluate a procedural basis function graph
jit.p.bounds
Limit particles to a region of space

Description
The jit.p.bounds object creates limits in a particle system. Limits may be applied to any of the qualities of the system (with the
exception of the reserved life and ID qualities).

Matrix Operator
matrix inputs:1, matrix outputs:1
Name IOProc Planelink Typelink Dimlink Plane Dim Type
out n/a 1 1 1 2 2 float32 float64

Information for Jitter Matrix Operator (MOP) messages and attributes to this object

Attributes
Name Type g/s Description
bounds_hi float The upper limit value, per plane, starting at plane 2 (planes 0 and 1 are reserved)
(default = 1.)
A symbol may be used to indicate that the bound is disabled.
bounds_lo float The lower limit, per plane, starting at plane 2 (default = -1.)
A symbol may be used to indicate that the bound is disabled.
mode int Boundary handling mode (default = 0 (bounce))
0 = bounce: Values are reflected back in the direction from which they came
1 = kill: Particle life is immediately set to 0
2 = wrap: Values reaching a bound value wrap to the other bound value
3 = clip: Values reaching a bound value stay at that value)
squish float The amount of "bounciness" of the bound (default = 1.)
squish_var float The amount of per-collision variance calculated for squish response (default = 0.)

Information for box attributes common to all objects

Examples
See Also
Name Description
jit.p.shiva Generate/eliminate particles
jit.p.vishnu Apply single force to particles
jit.p.shiva
Generate/eliminate particles

Description
The jit.p.shiva object generates Jitter matrices conforming to the Jitter particle system specification.

Matrix Operator
matrix inputs:1, matrix outputs:1
Name IOProc Planelink Typelink Dimlink Plane Dim Type
out n/a 1 1 1 2 2 float32 float64

Information for Jitter Matrix Operator (MOP) messages and attributes to this object

Attributes
Name Type g/s Description
emit int The maximum particles emitted per frame (default = 100)
emit_var int The amount of emit variance (default = 15)
init float The initial values, per-plane in mode 1 only (default = 0.)
init_var float The amount of init variance, per-plane (default = 0.)
life int The maximum particle life (default = 60)
life_var int The amount of life variance (default = 15)
mode int Use init attribute flag (default = 0)

Information for box attributes common to all objects

Examples

See Also
Name Description
jit.p.bounds Limit particles to a region of space
jit.p.vishnu Apply single force to particles
jit.p.vishnu
Apply single force to particles

Description
The jit.p.vishnu object takes a Jitter particle systems matrix as input, and applies a specific single force world model to it.

Matrix Operator
matrix inputs:1, matrix outputs:1
Name IOProc Planelink Typelink Dimlink Plane Dim Type
out n/a 1 1 1 2 2 float32 float64

Information for Jitter Matrix Operator (MOP) messages and attributes to this object

Attributes
Name Type g/s Description
force float The world force per-plane (default = 0. -0.001 0.)
mode int Generation mode flag (default = 0 (use pos attribute))
When the flag is set, any pre-existing values in the matrix are used as initial
positions. Otherwise, the pos attribute is used to generate an initial position for
new particles.
pitch float The initial angle of deviation from the horizontal plane (in radians) (default =
1.5708)
pitch_var float The amount of variance in pitch attribute output values (default = 0.6981)
pos float The initial position, per-plane (default = 0. -0.5 -0.5)
pos_var float The amount of variance in pos attribute output values (default = 0. 0. 0.)
speed float The initial speed (default = 0.05)
speed_var float The amount of variance in speed attribute output values (default = 0.01)
yaw float The initial angle of deviation from the vertical plane (in radians) (default = 0.)
yaw_var float The amount of variance in yaw attribute output values (default = 6.2832)

Information for box attributes common to all objects

Examples
See Also
Name Description
jit.p.bounds Limit particles to a region of space
jit.p.shiva Generate/eliminate particles
jit.pack
Make a multiplane matrix out of single plane matrices

Description
The jit.pack object merges N single-plane matrices to make one N-plane matrix. This is useful for combining separate alpha, red,
green, and blue matrices to make one ARGB matrix, and similar types of merging.

Matrix Operator
matrix inputs:-1, matrix outputs:1
Name IOProc Planelink Typelink Dimlink Plane Dim Type
out n/a 0 1 1 1 1 char long float32 float64

Information for Jitter Matrix Operator (MOP) messages and attributes to this object

Arguments
Name Units Type Opt Description
planecount int The number of planes in the input matrix and the number of single plane matrix
inlets for the jit.unpack object.

Attributes
Name Type g/s Description
index int Alias to the plane attribute for backwards compatibility. This attribute is only
useful from Javascript or Java, the Max object inlet sets this attribute
automatically.
jump int Number of planes to grab from input matrix (default = all ones)
offset int Plane offset into input matrix (default = all zero)
plane int Output matrix plane to which input is written. This attribute is only useful from
Javascript or Java, since the Max object inlet sets this attribute automatically.

Information for box attributes common to all objects

Examples
See Also
Name Description
jit.coerce Coerce a matrix into different types/planecount
jit.concat Concatenate two matrices
jit.split Split a matrix into two matrices
jit.unpack Make multiple single plane matrices out of a multiplane matrix
Tutorial 5: ARGB Color Tutorial 5: ARGB Color
jit.path
Evaluates a series of N-dim points as a path

Description
The jit.path object takes a series of N-dimensional points retrieves interpolated values based on an input parameter. It is useful
for creating user interfaces for parameter morphing.

Messages
bang Output the point matrix
append values [list] Append point values to the end of the path. If dim is 0, it is set to length of arg
list.
closepath Close the path by adding a point to the end equal to the first point.
eval parameter [float] Evaluate the path using parameter , (between 0. and 1.) and output the
interpolated values.
evallength length-parameter [float] Evaluate the path using the length-parameter (between 0 and pathlength) and
output the interpolated values.
evaltime time [float] Evaluate the path using time (between 0 and duration) and output the
interpolated values. The usetime attribute must be set to 1, causing the first dim
of the path to be treated as time values.
delete index [int] Delete the point at index
calchandles Calculate the path handles of each point in the path using the Catmull-Rom
method. This will overwrite any previously stored handles.
clear Remove all points from the path
edit index [int] Edit the point at index
values [list]
edithandle index [int] Edit the point handle at index
values [list]
gethandle index [int] Get handle values at index and output through dump outlet.
getpoint index [int] Get the point values at index and output through dump outlet. point .
insert index [int] Insert a new point at index
values [list]
outputeval Output a matrix from the second outlet, filled with the evaluated values of the
path. The matrix is 1D, the size is equal to the evalmatrixsize, and the planes are
equal to pathdim.
next Advance the path animation to the next point.
prev Rewind the path animation to the previous point
settime index [int] Set time at index . If necessary, the path will be resorted prior to evaluation.
sorttime Sort path based on time values
start Start path animation
stop Stop path animation

Attributes
Name Type g/s Description
autohandles int Enable the calculation of handle values every time the path is edited (default = 1).
closed int (get) Indicates the path is closed (first and last points are equal).
dim int Path dimension and number of planes in point and eval matrices (default = 0).
duration float (get) Path duration in seconds (default = 0.)
evalmatrixmode symbol Determines how the eval-matrix is evaluated (default = eval).
'eval' = Normalized by pointcount
'evallength' = Normalized by pathlength
evalmatrixsize int The size of the eval-matrix (default = 100).
grain int Time grain used when animating in milliseconds (default = 50).
interpmode symbol Path interpolation method (default = linear).
'linear' = Linear interpolation
'spline' = Hermite interpolation
length float (get) Path length (default = 0.)
loop int Path animation loop method (default = 1).
'off' = TEXT_HERE
'on' = TEXT_HERE
'palindrome' = TEXT_HERE
play int Enable path animation (default = 0).
pointcount int (get) Number of path points (default = 0).
rate float Animation rate value (default = 1.)
thru int Output point matrix receiving input matrix (default = 1).
time float Current path time value (default = 0.)
timemode symbol Determine how time values added to the path (default = relative).
'absolute' = Time value is set to argument
'relative' = Time value is set to argument plus previous time value
usetime int Determine if first path dim is used as time value (default = 0).

Information for box attributes common to all objects

Examples

Evaluates a series of N-dim points as a path

See Also
Name Description
jit.anim.path Evaluate a path of 3D transform points
jit.gl.path Generate and render a path in OpenGL
jit.peek~
Read matrix data as an audio signal

Description
jit.peek~ reads the value of one plane of a matrix cell at the position specified by the signal inputs. This value is output as a
signal. The object arguments are [matrix_name] [dim_inputcount] [plane] .

Arguments
Name Units Type Opt Description
matrix_name The named matrix to access (default = none)
dim_inputcount The number of dimensions in the matrix (default = 2)
plane The plane in a cell whose value is output (default = 0)

Messages
signal All inlets: Signal values arriving in these inlets specify the dimensional location of
the data to be stored for the plane specified. A signal inlet is provided for each
dimension specified by the dim_inputcount argument (i.e., jit.peek~ bigcube 3
has 3 inlets -- one for each of the 3 dimensions of the matrix).

Attributes
Name Type g/s Description
matrix_name symbol The named matrix to access (default = none)
plane int The plane in a cell whose value is output (default = 0)
interp int Interpolation flag (default = 0)
normalize int Normalizated input coordinates flag (default = 0)

Information for box attributes common to all objects

Examples

See Also
Name Description
jit.poke~ Write an audio signal into a matrix
peek~ Read and write sample values
poke~ Write sample values to a buffer by index
jit.buffer~ Access an MSP buffer~ in matrix form
jit.phys.6dof
A six degrees of freedom constraint in a physics world

Description
The jit.phys.6dof allows for linear and angular constraints of any of the three axes. Each axis can be either locked, free or limited.
If only a single body is bound, it is constrained to a point in world space.

Messages
reset Removes any current forces and returns the attached objects to their original
position.

Attributes
Name Type g/s Description
bias float Sets the magnitude of the limit's position correction (i.e. ow strictly the position
error is corrected). For most cases, this attribute value should not be greater than
1 (default = 0.3).
body1 symbol The name of the first jit.phys.body to constrain.
body2 symbol The name of the second jit.phys.body to constrain.
collisions int Enables collisions between attached bodies (default = 0).
enable int Enable this constraint in the physics simulation (default = 1).
lowerlimit_ang float The lower limits of allowed rotation in degrees (default = 1 1 1). If lowerlimit is
greater than upper limit, no limits are applied to the constraint axis.
lowerlimit_lin float The lower limits of allowed translation (default = 0 0 0). If lowerlimit is greater
than upper limit, no limits are applied to the constraint axis.
motorstrength float The maximum motor impulse (default 1.).
motorvelocity_ang float Maximum linear motor impulse (default 1.).
motorvelocity_lin float Enables motor and specifies velocity desired in degrees per second (default = 0).
position1 float The pivot point of body1 as a 3D vector relative to the body1 center of mass
(default = 0 0 0).
position2 float The pivot point of body2 as a 3D vector relative to the body2 center of mass
(default = 0 0 0). If body2 is blank, this is the worldspace position of the
constraint.
quat1 float The quaternion orientation of body1 relative to the constraint (default = 0 0 0 1).
quat2 float The quaternion orientation of body2 relative to the constraint (default = 0 0 0 1).
If body2 is blank, this is the worldspace orientation of the constraint.
relaxation float The rate at which velocity errors are corrected by limits, effectively the strength of
the limits (default = 1.0) . Lower values specify weaker limits. For most cases, the
relaxation value should not be greater than 1.
rotate1 float Rotation of body1 relative to the constraint (default = 0 0 0 1).
rotate2 float Rotation of body2 relative to the constraint (default = 0 0 0 1). If body2 is blank,
this is the worldspace orientation of the constraint.
rotatexyz1 float Euler rotation of body1 relative to the constraint (default = 0 0 0).
rotatexyz2 float Euler rotation of body2 relative to the constraint (default = 0 0 0). If body2 is
blank, this is the worldspace orientation of the constraint.
upperlimit_ang float The upper limits of allowed rotation in degrees (default = -1 -1 -1). If lowerlimit is
greater than upper limit, no limits are applied to the constraint axis.
upperlimit_lin float The upper limits of allowed translation (default = 0 0 0). If lowerlimit is greater
than upper limit, no limits are applied to the constraint axis.
worldname symbol The name of a jit.phys.world context this constraint is bound to.
Information for box attributes common to all objects

Examples

A six degrees of freedom constraint in a physics world

See Also
Name Description
jit.phys.world Collision detection and rigid body dynamics
jit.phys.body A rigid body and collision shape
jit.phys.barslide A bar constraint in a physics world
jit.phys.conetwist A conetwist constraint in a physics world
jit.phys.hinge A hinge constraint in a physics world
jit.phys.point2point A point to point constraint in a physics world
jit.phys.barslide
A bar constraint in a physics world

Description
The jit.phys.barslide object constrains attached jit.phys.body objects to rotate and translate around a single axis. Limits and
motor forces can be specified for both the linear translation and angular rotation around the constraint. If only a single body is
bound, it is constrained to a point in world space.

Messages
reset Removes any current forces and returns the attached objects to their original
position.

Attributes
Name Type g/s Description
body1 symbol The name of the first jit.phys.body to constrain.
body2 symbol The name of the second jit.phys.body to constrain.
collisions int Enables collisions between attached bodies (default = 0).
damping float Limit damping value (default = 0.7).
enable int Enable this constraint in the physics simulation (default = 1).
linearposition float (get) Position of constraint along translate axis (default = 0).
lowerlimit_ang float The lower limit of allowed rotation around the bar axis in degrees (default = 1). If
lowerlimit is greater than upper limit, no limits are applied to the constraint axis.
lowerlimit_lin float The lower limit of allowed translation along the bar axis (default = 0). If
lowerlimit is greater than upper limit, no limits are applied to the constraint axis.
motorstrength_ang float The maximum angular motor impulse (default 1.).
motorstrength_lin float The maximum linear motor impulse (default 1.).
motorvelocity_ang float Enables angular motor and specifies velocity desired in degrees per second
(default = 0).
motorvelocity_lin float Enables linear motor and specifies velocity desired in units per second (default =
0).
position1 float The pivot point of body1 as a 3D vector relative to the body1 center of mass
(default = 0 0 0).
position2 float The pivot point of body2 as a 3D vector relative to the body2 center of mass
(default = 0 0 0). If body2 is blank, this is the worldspace position of the
constraint.
quat1 float The quaternion orientation of body1 relative to the constraint (default = 0 0 0 1).
quat2 float The quaternion orientation of body2 relative to the constraint (default = 0 0 0 1).
If body2 is blank, this is the worldspace orientation of the constraint.
restitution float Limit restitution value (default = 1.0).
rotate1 float Rotation of body1 relative to the constraint (default = 0 0 0 1).
rotate2 float Rotation of body2 relative to the constraint (default = 0 0 0 1). If body2 is blank,
this is the worldspace orientation of the constraint.
rotatexyz1 float Euler rotation of body1 relative to the constraint (default = 0 0 0).
rotatexyz2 float Euler rotation of body2 relative to the constraint (default = 0 0 0). If body2 is
blank, this is the worldspace orientation of the constraint.
softness float Limit softness value (default = 1.0).
upperlimit_ang float The upper limit of allowed rotation in degrees around the bar axis (default = -1). If
lowerlimit is greater than upper limit, no limits are applied to the constraint axis.
upperlimit_lin float The upper limit of allowed translation along the bar axis (default = 0). If
lowerlimit is greater than upper limit, no limits are applied to the constraint axis.
worldname symbol The name of a jit.phys.world context this constraint is bound to.

Information for box attributes common to all objects

Examples

A bar constraint in a physics world

See Also
Name Description
jit.phys.world Collision detection and rigid body dynamics
jit.phys.body A rigid body and collision shape
jit.phys.conetwist A conetwist constraint in a physics world
jit.phys.hinge A hinge constraint in a physics world
jit.phys.point2point A point to point constraint in a physics world
jit.phys.6dof A six degrees of freedom constraint in a physics world
jit.phys.body
A rigid body and collision shape

Description
The jit.phys.body object represents a rigid body and collision shape in a physics simulation. The collision shape is either one of
several simple shapes, a compound shape (combination of simple shapes), or defined by a matrix of vertices.

Messages
bang Update the body forces and matrix inputs, and output position and quat values.
addchild shape [symbol] Add to a compound body a child shape . Optional args are position x/y/z,
x [float] quaternion x/y/z/w and scale x/y/z.
y [float]
z [float]
quat-x [float]
quat-y [float]
quat-z [float]
quat-w [float]
scale-x [float]
scale-y [float]
scale-z [float]
getchild_dict Send a dictionary description of the the child shapes of a compound body out the
dumpout.
impulse x [float] Apply an impulse (instantaneous force) to the rigid body using a worldspace vector
y [float] described by x , y , z . If forces_relative is enabled, the vector is converted to
z [float] object space. Optional args relative-x , relative-y , relative-z describe a relative
relative-x [float] position on the body where the force is applied, otherwise it's a central force.
relative-y [float]
relative-z [float]
removechild index [int] Remove the child shape at index from a compound body.
removechildren Remove all child shapes from a compound body.
reset Reset body properties position, and quat, and zero all forces.
setchild_position index [int] Set the position of child shape at index of a compound body.
x [float]
y [float]
z [float]
setchild_quat index [int] Set the quaternion of child shape at index of a compound body.
x [float]
y [float]
z [float]
w [float]
setchild_scale index [int] Set the scaling factor of child shape at index of a compound body.
x [float]
y [float]
z [float]
setchild_shape index [int] Set the shape of child at index of a compound body.
shape [symbol]
torque_impulse x [float] Apply a torque impulse (instantaneous angular force) to the rigid body using a
y [float] worldspace vector described by x , y , z . If forces_relative is enabled, the vector is
z [float] converted to object space.

Attributes
Name Type g/s Description
anim symbol The name of a jit.anim.node object to receive transform updates from.
damping float Set the linear and angular damping applied to a body in the range 0. to 1. (default
0.2 0.2). Damping can be used to simulate air resistance.
enable int Enable this body in the physics simulation (default = 1).
enable_sleep int Enable sleeping on this body, causing deactivation when linear and angular
velocity are 0 (default = 0).
filterclass symbol Set the name of this object's collision filter-class (default = default). Other objects
most specify the filterclass name in their filters list to enable collisions with this
object. Maximum allowed unique names is 10.
filters symbol Specify a list of filterclass names to enable collisions with (default = all). Possible
values include all and default . Additional values include any user-specified
filterclass names (maximum allowed = 10).
force float Apply a force to the rigid body using a 3D worldspace vector (default = 0 0 0). If
forces_relative is enabled, the vector is converted to object space.
forces_relative int Forces relative flag will cause all forces to be converted to object space before
applying (default = 0).
friction float The friction amount (opposite force) (default = 0.5). Applied when the body is in
contact with another body that has friction.
kinematic int Kinematic flag (default = 1). Use this mode to disable dynamics on the body,
enable collisions, and animate using position and quat attributes.
mass float Body mass (default = 1.). When set to 0. body dynamics are disabled, however
collisions remain active.
name symbol Specifies the name of the instance (default = UID).
position float Body position in worldspace in the form x y z (default = 0. 0. 0.).
quat float Body orientation as a quaternion in the form x y z w (default = 0. 0. 0. 1.).
reduce_hull int Enable automatic vertex reduction when body shape attribute is set to convexhull
(default = 1).
resetpos float Body reset position in the form x y z (default = 0. 0. 0.). This is the worldspace
position the body will return to upon receiving the reset message.
resetquat float Body reset orientation as a quaternion in the form x y z w (default = 0. 0. 0. 1.).
This is the orientation the body will return to upon receiving the reset message.
restitution float Restitution value, or bounciness (default = 0.1). The proportion of kinetic energy
preserved on impact with other rigid bodies.
rotate float Body orientation as angle-axis in the form angle(in degrees) x y z (default = 0. 0.
0. 1.).
rotatexyz float Body orientation as Euler angles (in degrees) in the form x y z (default = 0. 0. 0.).
scale float The body scaling factor in the form x y z (default = 1. 1. 1.). Cannot be applied to
concave shapes.
send_scale int Send scale flag (default = 1). When enabled, scale values will be sent to bound
objects.
shape symbol Collision shape type (default = sphere).
'sphere' = TEXT_HERE
'cube' = TEXT_HERE
'capsule' = TEXT_HERE
'cone' = TEXT_HERE
'cylinder' = TEXT_HERE
'convexhull' = Requires a matrix of vertices passed in
'concave' = Requires a matrix of vertices passed in
'compound' = Composite of simple shapes
'dynamicmesh' = TEXT_HERE
targetname symbol The name of a target object, either an OpenGL object or a jit.anim.node. This
object will receive position, quat, and possibly scale values.
torque float Apply a torque (angular force) to the rigid body using a 3D worldspace vector
(default = 0 0 0).
worldname symbol The name of a jit.phys.world context this body is bound to.

Information for box attributes common to all objects

Examples

A rigid body and collision shape

See Also
Name Description
jit.phys.world Collision detection and rigid body dynamics
jit.phys.multiple Uses matrices to simulate multiple rigid bodies
jit.phys.picker Constraint picking in a physics world
jit.gl.physdraw A physics opengl debug drawer
jit.gl.gridshape Generate simple geometric shapes as a grid
jit.phys.conetwist
A conetwist constraint in a physics world

Description
jit.phys.conetwist is a special point-to-point constraint that restricts the translation and allows limits on the rotation. The x-axis
serves as a twist axis. This can be useful to represent limbs of a body, such as arms and legs. Motor forces can be applied to the
constraint. If only a single body is bound, it is constrained to a point in world space.

Messages
reset Removes any current forces and returns the attached objects to their original
position.

Attributes
Name Type g/s Description
bias float Magnitude of the limit's position correction (default = 0.3). This attribute sets
how strictly the position error is corrected. For most cases, the value should not be
greater than 1.
body1 symbol The name of the first jit.phys.body to constrain.
body2 symbol The name of the second jit.phys.body to constrain.
collisions int Enables collisions between attached bodies (default = 0).
enable int Enable this constraint in the physics simulation (default = 1).
position1 float The pivot point of body1 as a 3D vector relative to the body1 center of mass
(default = 0 0 0).
position2 float The pivot point of body2 as a 3D vector relative to the body2 center of mass
(default = 0 0 0). If body2 is blank, this is the worldspace position of the
constraint.
quat1 float The quaternion orientation of body1 relative to the constraint (default = 0 0 0 1).
quat2 float The quaternion orientation of body2 relative to the constraint (default = 0 0 0 1).
If body2 is blank, this is the worldspace orientation of the constraint.
relaxation float The rate at which velocity errors are corrected by limits, effectively the strength of
the limits (default = 1.0) . Lower values specify weaker limits. For most cases, the
relaxation value should not be greater than 1.
rotate1 float Rotation of body1 relative to the constraint (default = 0 0 0 1).
rotate2 float Rotation of body2 relative to the constraint (default = 0 0 0 1). If body2 is blank,
this is the worldspace orientation of the constraint.
rotatexyz1 float Euler rotation of body1 relative to the constraint (default = 0 0 0).
rotatexyz2 float Euler rotation of body2 relative to the constraint (default = 0 0 0). If body2 is
blank, this is the worldspace orientation of the constraint.
swing1limit float The limit of allowed rotation in degrees in either direction around the swing 1 axis
(default = 180). With a limit of 180 degrees, rotation is unconstrainted around the
axis.
swing2limit float The limit of allowed rotation in degrees in either direction around the swing 2 axis
(default = 180). With a limit of 180 degrees, rotation is unconstrainted around the
axis.
twistlimit float The limit, in degrees, of allowed rotation in degrees in either direction around the
twist axis (default = 180). With a limit of 180 degrees, rotation is unconstrainted
around the axis.
worldname symbol The name of a jit.phys.world context this constraint is bound to.

Information for box attributes common to all objects


Examples

A conetwist constraint in a physics world

See Also
Name Description
jit.phys.world Collision detection and rigid body dynamics
jit.phys.body A rigid body and collision shape
jit.phys.barslide A bar constraint in a physics world
jit.phys.hinge A hinge constraint in a physics world
jit.phys.point2point A point to point constraint in a physics world
jit.phys.6dof A six degrees of freedom constraint in a physics world
jit.phys.ghost
A collision sensor and forcefield

Description
The jit.phys.ghost object represents a sensor area defined by a basic collision shape in a physics world. The collision shape is
either one of several simple shapes. Additionally a force field can be enabled to act on colliding objects. The direction vector of the
force field can be either in world coordinates, or relative to the jit.phys.ghost object.

Messages
bang Update ghost forces and output collision dict
central_impulse amount [float] Apply an impulse (instantaneous force) to the colliding rigid bodies using the
vector from the ghost object center to the rigid body center, scaled by amount . If
amount is positive, bodies shoot away from the ghost center, if negative they are
pulled into the ghost center. Impulse strength is inversely proportional to the
distance between objects.
impulse x [float] Apply an impulse (instantaneous force) to the colliding rigid bodies using a
y [float] worldspace vector described by x , y , z . Optional args relative-x , relative-y ,
z [float] relative-z describe a relative position on the body where the force is applied,
relative-x [float] otherwise it's a central force.
relative-y [float]
relative-z [float]
reset Clear all forces
torque_impulse x [float] Apply a torque impulse (instantaneous angular force) to the colliding rigid bodies
y [float] using a worldspace vector described by x , y , z .
z [float]

Attributes
Name Type g/s Description
central_force float Apply a central force
collisions int Enables and disables collision dictionary reporting out the first outlet.
enable int Enable this ghost object in the physics simulation (default = 1).
filters symbol The list of names that determine colliding objects for this ghost object; Valid
attributes are all and default . Additional valid attributes are defined by the
colliding objects' filterclass attribute.
force float Apply a force to the colliding rigid bodies using the vector from the ghost object
center to the rigid body center, scaled by amount . If amount is positive, bodies
shoot away from the ghost center, if negative they are pulled into the ghost center.
name symbol Specifies the name of the instance (default = UID).
position float Ghost object in worldspace in the form x y z (default = 0. 0. 0.).
quat float Ghost object orientation as a quaternion in the form x y z w (default = 0. 0. 0. 1.).
rotate float Ghost object orientation as angle-axis in the form angle(in degrees) x y z (default
= 0. 0. 0. 1.).
rotatexyz float Ghost object orientation as Euler angles (in degrees) in the form x y z (default = 0.
0. 0.).
scale float The Ghost object scaling factor in the form x y z (default = 1. 1. 1.). Cannot be
applied to concave shapes.
shape symbol Collision shape type (default = sphere).
'sphere' = TEXT_HERE
'cube' = TEXT_HERE
'capsule' = TEXT_HERE
'cone' = TEXT_HERE
'cylinder' = TEXT_HERE
torque float Apply a torque (angular force) to the colliding bodies using a 3D worldspace vector
(default = 0 0 0).
worldname symbol The name of a jit.phys.world context this ghost object is bound to.

Information for box attributes common to all objects

Examples

A collision sensor and forcefield

See Also
Name Description
jit.phys.world Collision detection and rigid body dynamics
jit.phys.body A rigid body and collision shape
jit.phys.multiple Uses matrices to simulate multiple rigid bodies
jit.phys.picker Constraint picking in a physics world
jit.gl.physdraw A physics opengl debug drawer
jit.phys.hinge
A hinge constraint in a physics world

Description
The jit.phys.hinge object restricts two additional angular degrees of freedom so an attached jit.phys.body object can only rotate
around the hinge axis. This can be useful to represent doors or wheels rotating around one axis. Limits and Motor forces can be
specified for the hinge. If only a single body is bound, it is constrained to a point in world space.

Messages
reset Removes any current forces and returns the attached objects to their original
position.

Attributes
Name Type g/s Description
bias float Magnitude of the limit's position correction (default = 0.3). This attribute sets
how strictly the position error is corrected. For most cases, the value should not be
greater than 1.
body1 symbol The name of the first jit.phys.body to constrain.
body2 symbol The name of the second jit.phys.body to constrain.
collisions int Enables collisions between attached bodies (default = 0.).
enable int Enable this constraint in the physics simulation (default = 1).
hingeangle float (get) The angle, in degrees, between constrained bodies around the hinge axis (default =
0).
lowerlimit float The lower limit, in degrees, of allowed rotation around the hinge axis (default = 1).
If lowerlimit is greater than upper limit, no limits are applied to the constraint.
motorstrength float The maximum motor impulse (default 1.).
motortarget float Angle around hinge axis, in degrees, the motor is targeting (default = 0).
motorvelocity float Enables motor and specifies velocity desired in degrees per second (default = 0).
position1 float The pivot point of body1 as a 3D vector relative to the body1 center of mass
(default = 0 0 0).
position2 float The pivot point of body2 as a 3D vector relative to the body2 center of mass
(default = 0 0 0). If body2 is blank, this is the worldspace position of the
constraint.
quat1 float The quaternion orientation of body1 relative to the hinge constraint (default = 0 0
0 1). Default value sets hinge axis to z axis.
quat2 float The quaternion orientation of body2 relative to the hinge constraint (default = 0 0
0 1). Default value sets hinge axis to z axis. If body2 is blank, this is the worldspace
orientation of the constraint.
relaxation float The rate at which velocity errors are corrected by limits, effectively the strength of
the limits (default = 1.0) . Lower values specify weaker limits. For most cases, the
relaxation value should not be greater than 1.
rotate1 float Rotation of body1 relative to the constraint (default = 0 0 0 1). Default value sets
hinge axis to z axis.
rotate2 float Rotation of body2 relative to the constraint (default = 0 0 0 1). Default value sets
hinge axis to z axis. If body2 is blank, this is the worldspace orientation of the
constraint.
rotatexyz1 float Euler rotation of body1 relative to the constraint (default = 0 0 0). Default value
sets hinge axis to z axis.
rotatexyz2 float Euler rotation of body2 relative to the constraint (default = 0 0 0). Default value
sets hinge axis to z axis. If body2 is blank, this is the worldspace orientation of the
constraint.
upperlimit float The upper limit, in degrees, of allowed rotation around the hinge axis (default = -
1). If lowerlimit is greater than upper limit, no limits are applied to the constraint.
worldname symbol The name of a jit.phys.world context this constraint is bound to.

Information for box attributes common to all objects

Examples

A hinge constraint in a physics world

See Also
Name Description
jit.phys.world Collision detection and rigid body dynamics
jit.phys.body A rigid body and collision shape
jit.phys.barslide A bar constraint in a physics world
jit.phys.conetwist A conetwist constraint in a physics world
jit.phys.point2point A point to point constraint in a physics world
jit.phys.6dof A six degrees of freedom constraint in a physics world
jit.phys.multiple
Uses matrices to simulate multiple rigid bodies

Description
The jit.phys.multiple object uses several jit.matrix objects to simulate rigid bodies in a physics world. The two outlets connect to
the position and rotate matrix inputs of a jit.gl.multiple object allowing for easy visualization of the rigid body shapes.

Messages
bang Update bodies and output matrices
damping_matrix matrix name A named matrix to use for the damping parameter if it's in the physparams list.
[symbol] Must be a 2-plane float32 matrix.
force_matrix matrix name A named matrix to use for the force parameter if it's in the physparams list. Must
[symbol] be a 3-plane float32 matrix.
friction_matrix matrix name A named matrix to use for the friction parameter if it's in the physparams list.
[symbol] Must be a 1-plane float32 matrix.
impulse x [float] Apply an impulse (instantaneous force) to the rigid bodies using a worldspace
y [float] vector described by x , y , z . Optional args relative-x , relative-y , relative-z
z [float] describe a relative position on the body where the force is applied, otherwise it's a
relative-x [float] central force.
relative-y [float]
relative-z [float]
mass_matrix matrix name A named matrix to use for the mass parameter if it's in the physparams list. Must
[symbol] be a 1-plane float32 matrix.
position_matrix matrix name A named matrix to use for the position parameter if it's in the physparams list.
[symbol] Must be a 3-plane float32 matrix.
restitution_matrix matrix name A named matrix to use for the restitution parameter if it's in the physparams list.
[symbol] Must be a 3-plane float32 matrix.
rotate_matrix matrix name A named matrix to use for the rotate parameter if it's in the physparams list. Must
[symbol] be a 4-plane float32 matrix.
rotatexyz_matrix matrix name A named matrix to use for the rotatexyz parameter if it's in the physparams list.
[symbol] Must be a 3-plane float32 matrix.
torque_impulse x [float] Apply a torque impulse (instantaneous angular force) to the rigid bodies using a
y [float] worldspace vector described by x , y , z .
z [float]
scale_matrix matrix name A named matrix to use for the scale parameter if it's in the physparams list. Must
[symbol] be a 3-plane float32 matrix.
torque_matrix matrix name A named matrix to use for the torque parameter if it's in the physparams list. Must
[symbol] be a 3-plane float32 matrix.

Attributes
Name Type g/s Description
damping float Set the linear and angular damping applied to a body in the range 0. to 1. (default
0.2 0.2). Damping can be used to simulate air resistance.
enable int Enable bodies in the physics simulation (default = 1).
enable_sleep int Enable sleeping on all bodies, causing deactivation when linear and angular
velocity are 0 (default = 0).
filterclass symbol Set the name of this object's collision filter-class (default = default). Other objects
most specify the filterclass name in their filters list to enable collisions with this
object. Maximum allowed unique names is 10.
filters symbol Specify a list of filterclass names to enable collisions with (default = all). Possible
values include all and default . Additional values include any user-specified
filterclass names (maximum allowed = 10).
force float Apply a force to the rigid bodies using a 3D worldspace vector (default = 0 0 0). If
forces_relative is enabled, the vector is converted to object space.
forces_relative int Forces relative flag will cause all forces to be converted to object space before
applying (default = 0).
friction float The friction amount (opposite force) (default = 0.5). Applied when the body is in
contact with another body that has friction.
kinematic int Kinematic flag (default = 1). Use this mode to disable dynamics on the bodies,
enable collisions, and animate using position and rotate matrices.
mass float Body mass (default = 1.). When set to 0. body dynamics are disabled, however
collisions remain active.
name symbol Specifies the name of the instance (default = UID).
physparams symbol The list of physics body attributes corresponding to object inlets that are
modifiable by passing in a matrix. Valid attributes are position, rotation,
rotatexyz, scale, mass, friction, restitution, damping, force, and torque.
restitution float Restitution value, or bounciness (default = 0.1). The proportion of kinetic energy
preserved on impact with other rigid bodies.
shape symbol Collision shape type (default = sphere).
'sphere' = TEXT_HERE
'cube' = TEXT_HERE
'capsule' = TEXT_HERE
'cone' = TEXT_HERE
'cylinder' = TEXT_HERE
shareshape int TEXT_HERE
torque float Apply a torque (angular force) to the rigid bodies using a 3D worldspace vector
(default = 0 0 0).
worldname symbol The name of a jit.phys.world context the rigid bodies are bound to.

Information for box attributes common to all objects

Examples

Uses matrices to simulate multiple rigid bodies

See Also
Name Description
jit.phys.world Collision detection and rigid body dynamics
jit.phys.body A rigid body and collision shape
jit.phys.ghost A collision sensor and forcefield
jit.phys.picker Constraint picking in a physics world
jit.gl.physdraw A physics opengl debug drawer
jit.gl.multiple Create multiple object instances
jit.gl.gridshape Generate simple geometric shapes as a grid
jit.phys.picker
Constraint picking in a physics world

Description
The jit.phys.picker object responds to mouse clicks and drags in the destination by creating a constraint on jit.phys.body objects
intersecting with the mouse. Multi-touch picking is facilitated by the touch message.

Messages
touch index [long] Update the multi-touch point at index (or create if doesn't exist). The constraint is
down [long] enabled if down is 1, and the position is set from screen-x and screen-y .
screen-x [long]
screen-y [long]

Attributes
Name Type g/s Description
body symbol (get) The name of the jit.phys.body currently intersecting with the mouse.
dynamics int Enable/disable dynamic constraint picking intersecting bodies (default = 1).
filterclass symbol Set the name of this object's collision filter-class (default = default). Other objects
most specify the filterclass name in their filters list to enable collisions with this
object. Maximum allowed unique names is 10.
filters symbol Specify a list of filterclass names to enable collisions with (default = all). Possible
values include all and default . Additional values include any user-specified
filterclass names (maximum allowed = 10).
hover int Enable/disable mouse hovering allowing for picking without the mouse button
down (default = 0).
pickmode symbol Determines how the constraint is applied to the intersecting body (default =
surface).
'center' = The constraint is applied to the bodies center of mass
'surface' = The constraint is applied to the intersecting surface point
position float (get) The current constraint picking position (default = 0 0 0).
worldname symbol The name of a jit.phys.world context this constraint picker is bound to.

Information for box attributes common to all objects

Examples
Constraint picking in a physics world

See Also
Name Description
jit.phys.world Collision detection and rigid body dynamics
jit.phys.body A rigid body and collision shape
jit.gl.picker Mouse picking in an opengl context
jit.phys.point2point
A point to point constraint in a physics world

Description
The jit.phys.point2point object limits the translation so that the local pivot points of 2 jit.phys.body objects match in
worldspace. If only a single body is bound, it is constrained to a point in world space.

Messages
reset Removes any current forces and returns the attached objects to their original
position.

Attributes
Name Type g/s Description
body1 symbol The name of the first jit.phys.body to constrain.
body2 symbol The name of the second jit.phys.body to constrain.
collisions int Enables collisions between attached bodies (default = 0.).
enable int TEXT_HERE
position1 float The pivot point of body1 as a 3D vector relative to the body1 center of mass
(default = 0 0 0).
position2 float The pivot point of body2 as a 3D vector relative to the body2 center of mass
(default = 0 0 0). If body2 is blank, this is the worldspace position of the
constraint.
worldname symbol The name of a jit.phys.world context this constraint is bound to.

Information for box attributes common to all objects

Examples

A point to point constraint in a physics world

See Also
Name Description
jit.phys.world Collision detection and rigid body dynamics
jit.phys.body A rigid body and collision shape
jit.phys.hinge A hinge constraint in a physics world
jit.phys.conetwist A conetwist constraint in a physics world
jit.phys.barslide A bar constraint in a physics world
jit.phys.6dof A six degrees of freedom constraint in a physics world
jit.phys.world
Collision detection and rigid body dynamics

Description
The jit.phys.world object encapsulates a physics simulation context to perform collision detection and rigid body dynamics on its
child objects. Other physics objects in the same patch as a jit.phys.world object are automatically added to the world. Multiple
contexts can be managed by explicitly setting the name attribute of the jit.phys.world object and the worldname attribute of the
child physics objects. Dynamics can be disabled, allowing the world to be used solely for collision detections.

Messages
bang Causes the world to perform a single step of the physics simulation, test and report
collisions, and update all child objects.
raytest x-from [float] Perform ray-testing on the rigid bodies using the passed in ray endpoints, and
y-from [float] report the first colliding object out the right-hand (dumpout) outlet of the object,
z-from [float] followed by the relative intersection position and world-space intersection.
x-to [float]
y-to [float]
z-to [float]
reset Reset the simulation and all child objects.
screenraytest screen-x [float] Perform ray-testing on the rigid bodies using the passed in screen coords. The ray
screen-y [float] start point is taken by converting the screen coords to world-space, and the end
point is generated by casting a ray from the camera position, through the start
point to the camera far clip plane. The first colliding object name is reported out
the right-hand (dumpout) outlet of the object, followed by the relative intersection
position and world-space intersection.

Attributes
Name Type g/s Description
automatic int Enables and disables automatic mode where update messages are received from
that target jit.gl.render object (default = 1).
collisions int Enables and disables collision reporting out the second (dumpout) outlet.
drawto symbol Assign to the named drawing context, allowing for updates to be received
automatically.
dynamics int Enables and disables rigid-body dynamics.
enable int Enable the physics simulation for all objects in this physics context (default = 1).
fixedtimestep int Fixed time step value (Hz) of physics simulation (default = 60). Increasing this
value increases the resolution of the simulation.
gravity float A 3D vector describes the force of gravity applied to all objects in the world
(default = 0, -9.8, 0).
maxsubsteps int Maximum number of internal simulation steps between updates (default = 1).
Increase this number if FPS is low in order to prevent the simulation from losing
time.
name symbol Specifies the name of the instance (default = UID).
numcollisions int (get) Specifies the number of collision points in the world.
remove_plane int Remove plane to enable 2D simulation (default = none).
'none' = TEXT_HERE
'x' = Constrain simulation to Y and Z planes
'y' = Constrain simulation to X and Z planes
'z' = Constrain simulation to X and Y planes
targetname symbol Specifies the name of a jit.gl.render object to receive update messages from.
ui_priority int TEXT_HERE
worldbox int Enables and disables the world bounds. (default = 1)
worldbox_scale float Changes the size and shape of the world bounds (default = 5, 5, 5).

Information for box attributes common to all objects

Examples

Collision detection and rigid body dynamics

See Also
Name Description
jit.phys.body A rigid body and collision shape
jit.phys.multiple Uses matrices to simulate multiple rigid bodies
jit.phys.ghost A collision sensor and forcefield
jit.phys.picker Constraint picking in a physics world
jit.gl.physdraw A physics opengl debug drawer
jit.pix
Generates Jitter mop pixel processing objects from a patcher.

Description
The jit.pix object generates new Jitter mop objects from a patcher specifically for pixel processing. The patcher describes how
each cell of a jit.matrix should be processed. jit.pix incorporates some of the same functionality as jit.expr with the additional
capability that it can sample input jit.matrix objects arbitrarily. jit.pix is exactly the same as jit.gl.pix except that all processing
happens on the CPU as with standard Jitter mop objets.

Matrix Operator
matrix inputs:-1, matrix outputs:1
Name IOProc Planelink Typelink Dimlink Plane Dim Type
out n/a 1 1 1 1 1 char long float32 float64

Information for Jitter Matrix Operator (MOP) messages and attributes to this object

Messages
anything TEXT_HERE
(drag) TEXT_HERE
(mouse) Open the Gen patcher
destroy Destroy the currently compiled Gen patcher
compile Compile the Gen patcher
jit.pix TEXT_HERE
open Open the Gen patcher
param Set a parameter of the gen patcher.
wclose Close the Gen patcher

Attributes
Name Type g/s Description
dirty int (get) Gen patcher dirty flag
gen symbol Gen patcher
def.:
precision symbol Gen patcher kernel precision
def.:auto 'auto' = Auto-choose precision
'fixed' = Fixed point precision
'float32' = Floating point precisions (32-bit)
'float64' = Floating point precisions (64-bit)
t symbol Gen patcher title
title symbol Gen patcher title

Information for box attributes common to all objects

Color
hsl2rgb: Convert HSL to RGB
rgb2hsl: Convert RGB to HSL

Comparison
!=, neq: Returns 1 if in1 does not equal in2, else returns zero.
!=p, neqp: Returns in1 if it does not equal in2, else returns zero.
<, lt: Returns 1 if in1 is lesser (in the positive direction) than in2, else returns zero.
<=, lte: Returns 1 if in1 is equal to or lesser (in the positive direction) than in2, else returns zero.
<=p, ltep: Returns in1 if in1 is equal to or lesser (in the positive direction) than in2, else returns zero.
<p, ltp: Returns in1 if in1 is lesser (in the positive direction) than in2, else returns zero.
==, eq: Returns 1 if in1 equals in2, else returns zero.
==p, eqp: Returns in1 if it equals in2, else returns zero.
>, gt: Returns 1 if in1 is greater (in the positive direction) than in2, else returns zero.
>=, gte: Returns 1 if in1 is equal to or greater (in the positive direction) than in2, else returns zero.
>=p, gtep: Returns in1 if in1 is equal to or greater (in the positive direction) than in2, else returns zero.
>p, gtp: Returns in1 if in1 is greater (in the positive direction) than in2, else returns zero.
max, maximum: The maximum of the inputs
min, minimum: The minimum of the inputs
step: Akin to the GLSL step operator: 0 is returned if in1 < in2, and 1 is returned otherwise.

Constant
constant: A constant value
degtorad, DEGTORAD: the constant pi/180
e, E: the constant e
f, float: A constant float value, or a conversion of the incoming value to float.
halfpi, HALFPI: the constant pi/2
i, int: A constant integer value, or a conversion of the incoming value to integer.
invpi, INVPI: the constant 1/pi
ln10, LN10: the constant ln10
ln2, LN2: the constant ln2
log10e, LOG10E: the constant log10e
log2e, LOG2E: the constant log2e
pi, PI: the constant pi
radtodeg, RADTODEG: the constant 180/pi
sqrt1_2, SQRT1_2: the constant 1/sqrt(2)
sqrt2, SQRT2: the constant sqrt(2)
twopi, TWOPI: the constant 2*pi

Coordinate
cell: Cell coordinates of input matrix [0, dim-1]
dim: Dimensions of input matrix
norm: Normalized coordinates of input matrix [0, 1]
snorm: Signed normalized coordinates of input matrix [-1, 1]

Declare
param, Param: Named parameters can be modified from the host object of the gen patcher. The first argument specifies the
name of the parameter, the second argument specifies the initial value.

Expression
expr: Evaluates GenExpr code. Standard mathematical operators (+, -, *, / etc.) and gen patcher operators can be used. See the
GenExpr documentation for more detail.

Input-output
in: Receive input into a gen patcher
out: Send output from a gen patcher

Logic
!, not: Zero input returns 1, any other value returns zero.
&&, and: Returns 1 if both in1 and in2 are nonzero.
^^, xor: Returns 1 if one of in1 and in2 are nonzero, but not both.
bool: Any nonzero value becomes 1, zero passes through.
or, ||: Returns 1 if either in1 and in2 are nonzero.

Math
!%, rmod: Reverse modulo (remainder of second input / first input)
!-, rsub: Reverse subtraction (subtract second input from first)
!/, rdiv: Reverse division (divide second input by first)
%, mod: Modulo inputs (remainder of first input / second input)
*, mul: Multiply inputs
+, add: Add inputs
-, sub: Subtract inputs
/, div: Divide inputs
absdiff: Compute the absolute difference between two inputs
cartopol: Convert Cartesian values to polar format. Angles are in radians.
neg: Negate input
poltocar: Convert polar values to Cartesian format. Angles are in radians.

Numeric
abs: Negative values will be converted to positive counterparts.
ceil: Round the value up to the next higher integer
floor, trunc: Round the value down to the next lower integer
fract: Return only the fractional component
sign: Positive input returns 1, negative input returns -1, zero returns itself.

Powers
exp: Raise the mathemtatical value e to a power
exp2: Raise 2 to a power
ln, log: The natural logarithm
log10: The logarithm base 10 of the input
log2: The logarithm base 2 of the input
pow: Raise in1 to the power of in2
sqrt: The square root of the input

Range
clamp, clip: Clamps the input value between specified min and max. Ranges are inclusive (both min and max values may be
output). If two arguments are given, they correspond to the min and max values respectively. If one argument is given, it is
assumed to correspond to the maximum value, while the minimum is set by the second inlet. If no arguments are given, min and
max are specified by the second and third inlets (defaulting to 0 and 1 respectively).
fold: Low and high values can be specified by arguments or by inlets. The default range is 0..1.
scale: Similar to the Max scale and MSP scale~ objects. Inputs are: 1) value to scale, 2) input lower bound, 3), input upper bound,
4) output lower bound, 5) output upper bound, 6) exponential curve. Default lower and upper bounds are zero and one; default
exponential curve is 1 (linear). No bound clamping is performed. The high and low values can be reversed for inverted mapping.
wrap: Low and high values can be specified by arguments or by inlets. The default range is 0..1.

Route
?, switch: Selects between the second and third inputs according to the Boolean value of the first: returns in2 if in1 is nonzero,
else returns in3. If one argument is given, it specifies the 'true' value (and the right inlet is the 'false' value). If two arguments are
given, they are the true and false values.
mix: Mixes (interpolates) between inputs a and b according to the value of the third input t, using linear interpolation. The factor
(t) should vary between 0 (for a) and 1 (for b). If one argument is given, it specifies the mix (interpolation) factor.
smoothstep: Smoothstep is a scalar interpolation function commonly used in computer graphics. The function interpolates
smoothly between two input values based on a third one that should be between the first two. The returned value is clamped
between 0 and 1. The slope (i.e. derivative) of the smoothstep function starts at 0 and ends at 0.

Sampling
nearest: Nearest neighbor sample a matrix at a given coordinate (normalized). Nearest has a boundmode attribute that can be
set to wrap, mirror or clamp.
sample: Sample a matrix at a given coordinate (normalized) with linear interpolation. Sample has a boundmode attribute that
can be set to wrap, mirror or clamp.

Surface
circle: Equation of a circle taking input coordinates ranging from [0, 1]
cone: Equation of a cone taking input coordinates ranging from [0, 1]
cylinder: Equation of a cylinder taking input coordinates ranging from [0, 1]
plane: Equation of a plane taking input coordinates ranging from [0, 1]
sphere: Equation of a sphere taking input coordinates ranging from [0, 1]
torus: Equation of a torus taking input coordinates ranging from [0, 1]

Trigonometry
acos: The arc cosine of the input (returns radians)
acosh: The inverse hyperbolic cosine of the input
asin: The arc sine of the input (returns radians)
asinh: The inverse hyperbolic sine of the input
atan: The arc tangent of the input (returns radians)
atan2: Returns the angle to the coordinate (in2, in1) in radians.
atanh: The inverse hyperbolic tangent of the input
cos: The cosine of the input (in radians)
cosh: The hyperbolic cosine of the input
degrees: convert radians to degrees
hypot: Returns the length of the vector to (in1, in2).
radians: convert degrees to radians
sin: The sine of the input (in radians)
sinh: The hyperbolic sine of the input
tan: The tangent of the input (in radians)
tanh: The hyperbolic tangent of the input

Vector
concat: Concatenate vector values into a larger vector
cross: Take the cross product of two vectors
dot: Take the dot product of two vectors
length: Get the length of a vector
normalize: Normalize of a vector to unit length
reflect: Reflect a vector off a surface defined by a normal
swiz: Unpack and remap vector components
vec: Pack scalar values into a vector

Examples
See Also
Name Description
jit.planeop
Operator across planes

Description
jit.planeop applies an operator to all the planar elements, converting multi-plane input to single-plane output.

Matrix Operator
matrix inputs:1, matrix outputs:1
Name IOProc Planelink Typelink Dimlink Plane Dim Type
out n/a 0 0 0 1 1 char long float32 float64

Information for Jitter Matrix Operator (MOP) messages and attributes to this object

Attributes
Name Type g/s Description
op symbol The operator to be applied across the plane (default = avg).

Supported Operators:
avg = average
* = multiplication (also mult)
+ = addition (also add)
min = minimum
max = maximum

Information for box attributes common to all objects

Examples

See Also
Name Description
jit.op Apply binary or unary operators
jit.dimop Downsample using operators across dimensions
jit.expr Evaluate an expression to fill a matrix
jit.plot
(x,y) plotting of a two-plane matrix

Description
Use jit.plot to render a cartesian plot of a two-plane matrix.

Matrix Operator
matrix inputs:1, matrix outputs:1
Name IOProc Planelink Typelink Dimlink Plane Dim Type
out n/a 1 1 1 4 2 char

Information for Jitter Matrix Operator (MOP) messages and attributes to this object

Attributes
Name Type g/s Description
brgb int Three chars represent the red, green and blue values of the background color to
render
clearit int If non-zero the cells of the matrix will be cleared to the brgb color before
rendering.
frgb int Four chars represent the alpha, red, green and blue values of the color to render
height int The height of the output matrix (default=240)
width int The width of the output matrix (default=240)
xmax float The floating point value to map to the right of the graph (default=1.0)
xmin float The floating point value to map to the left of the graph (default=-1.0)
ymax float The floating point value to map to the top of the graph (default=1.0)
ymin float The floating point value to map to the left of the graph (default=-1.0)

Information for box attributes common to all objects

Examples
See Also
Name Description
jit.buffer~ Access an MSP buffer~ in matrix form
jit.graph Perform floating-point data visualization
jit.peek~ Read matrix data as an audio signal
jit.poke~ Write an audio signal into a matrix
jit.release~ Transforms matrix data into signals
peek~ Read and write sample values
poke~ Write sample values to a buffer by index
jit.plume
Displace points based on luminance

Description
jit.plume takes two input matrices and uses an average value of all planes for each cell in a second input (control) matrix to
displace the corresponding cell of the first (input) matrix.

Matrix Operator
matrix inputs:2, matrix outputs:1
Name IOProc Planelink Typelink Dimlink Plane Dim Type
in2 resamp 1 1 1 1 1 char
out n/a 1 1 1 1 1 char

Information for Jitter Matrix Operator (MOP) messages and attributes to this object

Messages
planeselect plane-list [list] Chooses which planes on the second matrix (inlet 2) are averaged to offset the first
matrix. The planeselect message takes the following arguments:
-2 = Average all planes
-1 = Average all planes except plane 0 (default)
0-x = A single int argument specifies a single plane (no average)
A list of int arguments specifies a multiplane average of the planes listed (e.g., 0 2
3)

Attributes
Name Type g/s Description
intervalmode int Interval mode for x_interval only (default = 0 (entire frame))
0 = interval calculated over the entire frame
1 = new interval count for each scanline
wrap int Wrap mode (default = 0 (normal))
0 = normal: Cells displaced off the edge of the frame are disregarded
1 = wrap: Cells displaced off the edge of the frame wrap to the other edge
2 = reflect: Cells displaced off the edge of the frame are reflected
3 = clip: Cells are clipped to the edge of the frame
x_interval int The frequency of displacement calculation along the horizontal axis (default = 1)
xamount int The horizontal amount of displacement (multiplied by luminance) (default = 0)
xinterval int The frequency of displacement calculation along the horizontal axis (default = 1)
xoffset int The horizontal offset of displacement (default = 0)
y_interval int The frequency of displacement calculation along the vertical axis (default = 1)
yamount int The vertical amount of displacement (multiplied by luminance) (default = 0)
yinterval int The frequency of displacement calculation along the vertical axis (default = 1)
yoffset int The vertical offset of displacement (default = 0)

Information for box attributes common to all objects

Examples
See Also
Name Description
jit.repos Reposition spatially
jit.plur
Peace Love Unity Rave

Description
Use the jit.plur object to performs linear interpolation on incoming matrix frames. This object resamples an image and then
interpolates back to the original size.

Matrix Operator
matrix inputs:1, matrix outputs:1
Name IOProc Planelink Typelink Dimlink Plane Dim Type
out n/a 1 1 1 1 1 char long float32 float64

Information for Jitter Matrix Operator (MOP) messages and attributes to this object

Attributes
Name Type g/s Description
colormode int Color wrapping mode (default = 0 (wrap))
0 = wrap: Values that exceed the limits are wrapped around to the opposite limit
with a modulo operation. (256 wraps to 0, 257 wraps to 1, and -1 wraps to 255, -2
wraps to 254, etc.)
1 = clip: Values are limited not to exceed min or max. (E.g. numbers greater than
255 are set to 255, and numbers less than 0 are set to 0.)
2 = bounce: Values that exceed the limits are folded back in the opposite direction.
(256 is folded back to 254, 257 is folded back to 253, and -1 is folded back to 1, -2
to 2, etc.)
gang int Range value flag (default = 1) When the flag is set, the x_range and y_range
values are used. Otherwise, the x_step and y_step values are used instead.
hi float The upper output range limit (default = 1.)
lo float The lower output range limit (default = 0.)
mode int Interpolation mode (default = 0 (linear))
0 = linear interpolation
1 - 15 = interpolation variations (Try 'em and see!)
scale int The amount of bit shift before output (default = 8)
x_range int The horizontal distance between corner points used for interpolation (default = 2)
x_step int The horizontal distance between resampled corner points (default = 2)
y_range int The vertical distance between corner points used for interpolation (default = 2)
y_step int The vertical distance between resampled corner points (default = 2)

Information for box attributes common to all objects

Examples
See Also
Name Description
jit.ameba Downsample/upsample with non-obvious results
jit.poke~
Write an audio signal into a matrix

Description
jit.poke~ writes the value specified by the leftmost signal input into one plane of a matrix cell at the position specified by the
signal inputs (following the leftmost input). The object arguments are [matrix_name] [dim_inputcount] [plane] .

Arguments
Name Units Type Opt Description
matrix_name The name of the matrix to access (default = none)
dim_inputcount The number of dimensions in the matrix (default = 2)
plane The plane in a cell whose value is replaced by leftmost input (default = 0)

Messages
signal In left inlet: Signal values arriving in this inlet will be stored at the dimensional
locations specified by the signal inputs to the remaining inlets of the jit.poke~
object. The number of dimensional inlets will vary, depending on the value of the
[dim_inputcount] argument.

In other inlets: Signal values arriving in this inlet specify the dimensional location
of the data to be stored for the plane specified. A signal inlet is provided for each
dimension specified by the [dim_inputcount] attribute (i.e., jit.poke~ bigcube 3
has 4 inlets -- one for input data, and one for each of the 3 dimensions of the
matrix).

Attributes
Name Type g/s Description
matrix_name symbol The name of the matrix to access (default = none)
normalize int Normalized input coordinates flag (default = 0)

Information for box attributes common to all objects

Examples

See Also
Name Description
jit.peek~ Read matrix data as an audio signal
peek~ Read and write sample values
poke~ Write sample values to a buffer by index
jit.buffer~ Access an MSP buffer~ in matrix form
Tutorial 27: Using MSP Audio in a Tutorial 27: Using MSP Audio in a Jitter Matrix
Jitter Matrix
jit.print
Print a matrix in the Max window

Description
Use the jit.print object to print values for small matrices display and display them in the Max window. For larger matrices, use
jit.fprint which prints its contents to a file.

Matrix Operator
matrix inputs:1, matrix outputs:1
Name IOProc Planelink Typelink Dimlink Plane Dim Type
out n/a 1 1 1 1 1 char long float32 float64

Information for Jitter Matrix Operator (MOP) messages and attributes to this object

Attributes
Name Type g/s Description
coldelim symbol Column delimiter
fieldwidth int Number of characters to display per cell
info int Information mode (default = 0 (matrix, no info))
0 = display matrix contents, no info
1 = display matrix info and contents
2 = display matrix into only
mode int Character display mode (default = 0 (decimal))
0 = decimal
1 = hexadecimal (used for char and long matrices only)
2 = ascii (used for char matrices only)
planedelim symbol Plane delimiter
precision int Floating-point precision characters
rowdelim symbol Row delimiter
title symbol Matrix display title
zeropad int Zero padding flag (default = 0) When the flag is set, empty display spaces in a
matrix are filled with zeros.

Information for box attributes common to all objects

Examples

See Also
Name Description
jit.fpsgui Display fps, ms, and matrix attributes
jit.fprint Read/write a matrix as a text file
jit.matrixinfo Report matrix planecount, type, dimensions
Tutorial 2: Create a Matrix Tutorial 2: Create a Matrix
Tutorial 11: Lists and Matrices Tutorial 11: Lists and Matrices
jit.proxy
Proxy a Jitter object.

Description
jit.proxy proxies named Jitter objects. When an object is proxied, jit.proxy will forward any messages it receives to that object
and output messages that return values such as the attribute 'get' messages.

Arguments
None.

Messages
bang TEXT_HERE
int TEXT_HERE
float TEXT_HERE
list TEXT_HERE
anything Sends any message on to the proxied object. Attribute 'get' messages (e.g. getcolor,
etc.) will return values out the left-most outlet.

Attributes
Name Type g/s Description
name symbol The name of the object to be proxied.

Information for box attributes common to all objects

Examples

See Also
Name Description
jit.pwindow
Show data in a patcher

Description
Use jit.pwindow to draw pixels or graphics within a patcher - it displays jit.matrix data as well as OpenGL 3D graphics.

Arguments
None.

Messages
bang Output the currently stored matrix
jit_gl_texture texture-name [symbol] Draw the texture to screen by first reading back the texture into a matrix.
jit_matrix matrix-name [symbol] Draw the matrix to screen
(mouse) Mouse events

Attributes
Name Type g/s Description
border float Border Size
def.:0.
bordercolor float Sets the Border Color in RGBA format. The Draw border flag must be set for the
def.:0. 0. 0. 1. border to be visible.
colormode symbol Colormode
def.:argb 'argb' = ARGB color
'uyvy' = UYVY color
depthbuffer int Enable depth buffer
doublebuffer int Enable double buffering
dstrect int The matrix destination rectangle is given by coordinates left, top, bottom, right. All
def.:0 0 320 240 values are relative to the top left corner of the window.
fsaa int Full scene anti-aliasing enable
idlemouse int Idlemouse
def.:0
interp int Interpolate
def.:0
name symbol The name of the window. Jitter OpenGL objects attach to a rendering context
through the window's name.
onscreen int Onscreen
def.:1
pickray int Pickray
def.:0
planemap int The plane mapping from input matrix to output (default = 0 1 2 3).
def.:0 1 2 3
shared int TEXT_HERE
size int Window size
srcrect int The portion of the input matrix used when copying an input matrix to the internal
def.:0 0 320 240 matrix. (default = 0 0 (matrix width) (matrix height)) The proportions of the
rectangle are expressed in the form left top right bottom . All values are relative to
the top left corner of the viewing area of the input matrix.
stereo int Stereo buffer enable
sync int The vertical sync flag sets the window to update synchronous to the monitor's
refresh.
usedstrect int Use Destination Rect
def.:0
usesrcrect int Use Source Rect
def.:0

Information for box attributes common to all objects

Examples

See Also
Name Description
jit.gl.render Render Jitter OpenGL objects
jit.window Display data in a window
Tutorial 2: Create a Matrix Tutorial 2: Create a Matrix
Tutorial 31: Rendering Tutorial 31: Rendering Destinations
Destinations
Tutorial 38: Basic Performance Tutorial 38: Basic Performance Setup
Setup
Tutorial 39: Spatial Mapping Tutorial 39: Spatial Mapping
Tutorial 45: Introduction to using Tutorial 45: Introduction to using Jitter within JavaScript
Jitter within JavaScript
Tutorial 49: Colorspaces Tutorial 49: Colorspaces
jit.qball
Convert messages at scheduler time to low priority

Description
The jit.qball object places all messages received at scheduler time in the low priority queue, even if overdrive is turned off.

Arguments
None.

Messages
bang Any bang received at scheduler time will be placed in the low priority queue.
When the low priority queue services this message, it will be sent out the left
outlet. If the message received is being sent from the low priority queue it is
immediately sent out the leftmost outlet.

If mode= usurp, and the low priority queue has not yet serviced the last received
message, it will be replaced by the most recently received message.

If mode= defer, then the most recently received message will be placed in the low
priority queue without affecting previously received messages.

int Any number received at scheduler time will be placed in the low priority queue.
When the low priority queue services this message, it will be sent out the left
outlet. If the number received is being sent from the low priority queue it is
immediately sent out the leftmost outlet.

If mode= usurp, and the low priority queue has not yet serviced the last received
message, it will be replaced by the most recently received message.

If mode= defer, then the most recently received message will be placed in the low
priority queue without affecting previously received messages.

float Any number received at scheduler time will be placed in the low priority queue.
When the low priority queue services this message, it will be sent out the left
outlet. If the message received is being sent from the low priority queue it is
immediately sent out the leftmost outlet.

If mode= usurp, and the low priority queue has not yet serviced the last received
message, it will be replaced by the most recently received message.

If mode= defer, then the most recently received message will be placed in the low
priority queue without affecting previously received messages.

list Any list received at scheduler time will be placed in the low priority queue. When
the low priority queue services this message, it will be sent out the left outlet. If the
message received is being sent from the low priority queue it is immediately sent
out the leftmost outlet.

If mode= usurp, and the low priority queue has not yet serviced the last received
message, it will be replaced by the most recently received message.

If mode= defer, then the most recently received message will be placed in the low
priority queue without affecting previously received messages.

anything Any message received at scheduler time will be placed in the low priority queue.
When the low priority queue services this message, it will be sent out the left
outlet. If the message received is being sent from the low priority queue it is
immediately sent out the leftmost outlet.
If mode= usurp, and the low priority queue has not yet serviced the last received
message, it will be replaced by the most recently received message.

If mode= defer, then the most recently received message will be placed in the low
priority queue without affecting previously received messages.

defer For internal use only.


usurp For internal use only.

Attributes
Name Type g/s Description
mode symbol The means of handling multiple messages prior to being serviced by the low
priority queue (default = usurp)
usurp = multiple messages replace one another;
defer = multiple messages accumulate;

Information for box attributes common to all objects

Examples

See Also
Name Description
jit.qfaker Fake queue status
Tutorial 16: Using Named Jitter Tutorial 16: Using Named Jitter Matrices
Matrices
jit.qfaker
Fake queue status

Description
Use the jit.qfaker object to set the low priority queue status so that messages received at scheduler time can be executed at
scheduler time even in the instance that Max would normally place such events on the low priority queue.

Arguments
None.

Messages
bang the bang will be immediately sent out the leftmost outlet without modification.
However, the low priority queue state will be set to "on".
int The number will be immediately sent out the leftmost outlet without modification.
However, the low priority queue state will be set to "on".
float The number will be immediately sent out the leftmost outlet without modification.
However, the low priority queue state will be set to "on".
list The list will be immediately sent out the leftmost outlet without modification.
However, the low priority queue state will be set to "on".
anything Any message will be immediately sent out the leftmost outlet without modification.
However, the low priority queue state will be set to "on".

Information for box attributes common to all objects

Examples
See Also
Name Description
jit.qball Convert messages at scheduler time to low priority
jit.qt.broadcast
Broadcast video using RTSP (Macintosh only)

Description
Use the jit.qt.broadcast object as an RTSP server. It takes a 4 char matrix as input, compresses the data and streams it over a
network (local or internet) using the RTSP streaming standard.

WINDOWS USERS: This object is currently unsupported.

Matrix Operator
matrix inputs:1, matrix outputs:1
Name IOProc Planelink Typelink Dimlink Plane Dim Type
out n/a 1 1 1 4 1 char

Information for Jitter Matrix Operator (MOP) messages and attributes to this object

Messages
pause Pauses a running broadcast server. No effect if the server is idle.
start Starts the broadcast server.
stop Stops the broadcast server.
write filename [] Writes an SDP (session description protocol) file to disk. This file describes the
streaming parameters in a form suitable for distribution to clients. Every time a
broadcast parameter is modified (vcodec, for instance), a new SDP file must be
written, or clients will have trouble connecting to the broadcast stream.
In the absence of a filename argument, a Save dialog will be presented.

Attributes
Name Type g/s Description
acodec symbol The audio codec for streaming (default = qdesign2)
The available codec types are none, raw, big16, little16, float32, float64,
24bit, 32bit, little32, mace3, mace6, cdxa4, cdxa2, ima, ulaw, alaw, adpcm,
dviima, dvaudio, qdesign, qdesign2, qualcomm, mp3, vdva, mpeg4.
aenable int Audio enable flag (default = 0)
This flag is only active in mode 2 (Sequence Grabber source mode) and
determines whether sound will be streamed, as well as image.
aip symbol Audio IP address (default = variable)
In multicast mode (the default. See unicast, below), this IP address is
automatically assigned, and read-only, and refers to the special multicast address
client computers access to reach your broadcast.
In unicast mode, this IP address should be set to the IP address of the single client
computer.
aport int Audio broadcast port number (default = 8556)
The network port to be used by the audio portion of the broadcast stream.
bitrate int Audio bitrate (default = 16)
16 = 16-bit audio
8 = 8-bit audio
channels int Audio channel selection (default = 2)
1 = mono audio
2 = stereo audio
codec symbol The video codec for streaming (default = h263)
The following list of codecs is deprecated (retained for reference). See codeclist,
below, for the preferred method to list valid system codecs.
The available codec types are raw , cinepak, graphics, animation, video,
componentvideo , jpeg , mjpega, mjpegb, sgi , planarrgb , macpaint , gif,
photocd, qdgx , avrjpeg, opendmljpeg , bmp , winraw , vector, qd , h261, h263,
dvntsc , dvpal , dvprontsc, dvpropal , flc , targa, png , tiff ,
componentvideosigned , componentvideounsigned , cmyk , microsoft ,
sorenson, indeo4 , argb64 , rgb48 , alphagrey32 , grey16, mpegyuv420,
yuv420 , sorensonyuv9 and mpeg4.
codeclist symbol (get) The valid video codecs available on the system
Sending the message getcodeclist will cause a list of all valid codecs (that is, those
with a functioning compressor component) to be reported from the dumpout. This
list is guaranteed to contain only working codecs, and should be used in preference
to the old, static codec list.
datarate int Sets the data rate in frames/second.
dstrect int The rectangular portion of the streaming image to be drawn to, when an incoming
matrix is received. (default = 0 0 (image width) (image height))
The proportions of the rectangle are expressed in the form left top right bottom .
All values are relative to the top left corner of the viewing area of the streamed
image.
interp int Interpolation flag (default = 0)
ip symbol Video IP address (default = variable)
In multicast mode (the default. See unicast, below), this IP address is
automatically assigned, and read-only, and refers to the special multicast address
client computers access to reach your broadcast.
In unicast mode, this IP address should be set to the IP address of the single client
computer.
kframe int Keyframe rate (default = 50)
If set, the jit.qt.broadcast object will attempt to configure the video compressor
to use the specified keyframe rate. Keyframes (temporal compression) are not
available to all codecs.
mode int Streaming source mode (default = 0)
0 = matrix input
1 = Hinted Movie input (uses the movie attribute to choose a pre-hinted source
movie)
2 = Sequence Grabber input (uses an attached camera as the streaming source)
Modes 1 and 2 permit audio streaming, as well.
movie symbol Source movie for mode 1 (default = "")
If no movie is specified when setting this attribute, a File dialog will be presented.
Movies must be hinted, to be used with the jit.qt.broadcast object. See Tutorial
51: Broadcasting for more information.
preview int Matrix preview flag (default = 0)
If set, an incoming matrix will be copied to the object's output matrix (with
srcrect, interp or dstrect transformations) when the jit.qt.broadcast object is
streaming. Otherwise, the matrix is simply passed through the object. Only
functional in mode 0.
samplerate float Audio sample rate (default = 8000)
48000 = 48kHz
44100 = 44.1kHz
32000 = 32kHz
22050 = 22.050kHz
22254 = 22kHz
16000 = 16kHz
11127 = 11kHz
11025 = 11.025kHz
8000 = 8000 Hz
size int The dimensions of the broadcast (default = 160 120)
spatialquality symbol Codec spatial compression quality (default = 2 (normal))
0 or min = minimum
1 or low = low
2 or normal = normal
3 or high = high
4 or max = maximum
5 or lossless = lossless

Note that minimum quality is, in many cases, the codec's default quality. Use
"low" quality for consistent results.
srcrect int The rectangular section of the incoming matrix to compress and stream (default =
0 0 (movie width) (movie height))
streamname symbol Name of the broadcast stream, as displayed in the stream's URL (default =
"Jitter")
temporalquality symbol Codec temporal compression quality (default = 2 (normal))
0 or min = minimum
1 or low = low
2 or normal = normal
3 or high = high
4 or max = maximum
5 or lossless = lossless

Note that minimum quality is, in many cases, the codec's default quality. Use
"low" quality for consistent results.
ttl int Packet time to live (default = 255)
unicast int Unicast broadcast flag (default = 0)
If set, the jit.qt.broadcast object will broadcast in unicast mode. In this mode, the
vip (and aip, if used) refer to a single client computer, which will be able to receive
your broadcast. In multicast mode (the default), as many clients as your system's
bandwidth can support will be able to access the stream.
usedstrect int Destination rect flag (default = 0)
When the flag is set, the dstrect attributes are used when compressing an input
matrix for streaming.
usesrcrect int Source rect flag (default = 0)
When the flag is set, the srcrect attributes are used when compressing an input
matrix for streaming. The proportions of the rectangle are expressed in the form
left top right bottom . All values are relative to the top left corner of the viewing
area of the incoming matrix.
vcodec symbol The video codec for streaming (default = h263)
Synonym for codec, above.
venable int Video enable flag (default = 1)
This flag is currently ignored.
vip symbol Video IP address (default = variable)
Synonym for ip, above.
vport int Video broadcast port number (default = 8554)
The network port to be used by the video portion of the broadcast stream.

Information for box attributes common to all objects

Examples
See Also
Name Description
jit.net.recv Receive matrices from a jit.net.send object via TCP/IP
jit.net.send Send matrices to a jit.net.recv object via TCP/IP
jit.broadcast Broadcast video using RTSP
Tutorial 53: Jitter Networking Tutorial 53: Jitter Networking (part 2)
(part 2)
jit.qt.effect
QuickTime Effects for Jitter matrices

Description
The jit.qt.effect object provides a wrapper for the QuickTime Effects architecture within Jitter.

Matrix Operator
matrix inputs:2, matrix outputs:1
Name IOProc Planelink Typelink Dimlink Plane Dim Type
in2 resamp 1 1 1 4 1 char
out n/a 1 1 1 4 1 char

Information for Jitter Matrix Operator (MOP) messages and attributes to this object

Messages
dialog tween-enable [int] Opens the standard QuickTime Effects dialog box. With no argument (or a tween-
enable argument of 1), the dialog will open with the optionally-tweened
parameters tween-enabled. With a tween-enable argument of 0, optionally-
tweened params are tween-disabled.
geteffectlist Sends a list out the object's right outlet describing all available QuickTime effects,
one effect per line. The lists are in the form effectlist effect-number effect-name
effect-type-code .
getparamhead Sends the parameter header list out the object's right outlet. The list is in the form
paramhead effect-name effect-type-code no.-of-params no.-of-sources .
getparamlist Sends several lists out the object's right outlet describing the parameters for the
currently selected effect. The first list is in the form paramhead effect-name
effect-type-code no.-of-params no.-of-sources
The following list or lists (one list for each parameter) are in the form paramlist
param-number param-name param-type-code tween-flag data-type . Depending
on the effect, two additional messages may be used: min-value max-value .

The tween flag settings are: 0 = always tweened 1 = never tweened 2 = optionally
tweened

The data types and their expected input are: long = int fixed = float rgb = 3 floats,
from 0 to 1.0 double = float text = text, currently unsupported from Max, but
available from the dialog message enum = enumerated list (int) bool = boolean
(int) imag = image, currently unsupported from Max, but available from the dialog
message

Minimum value and maximum value are all reported in the data type of the
parameter, if they are supplied at all.

loadeffect mutex group Selects an available QuickTime Effect for use. The effect may be specified by its
effect-number [int] index number or by its type code.
effect-type-code
[symbol]
endmutex group
qfx_read Load and enable the parameters specified by a QuickTime Effects .qxf-formatted
file. These files may also be read from the dialog box.
qfx_write Write the current effect and parameters to a QuickTime Effects .qxf-formatted file.
These files may also be written from the dialog box. The jit.qt.movie object can
read these files to generate QuickTime Effects tracks embedded within movies.

Attributes
Name Type g/s Description
fx symbol The currently loaded effect
numeffects int (get) The number of available effects
numparams int (get) The number of parameters available to the currently loaded effect
param int (set) The parameter value for tweenable parameters
param_a int (set) The start value for tweenable parameters
param_b int (set) The end value for tweenable parameters
paramclip int Parameter clipping flag (default = 1) When the flag is set, parameter values are
clipped to the effect's recommended range (default = 1)
steps int The number of steps between param_a and param_b for tweenable parameters

Information for box attributes common to all objects

Examples

See Also
Name Description
jit.qt.grab Digitize video from an external source
jit.qt.movie Play or edit a QuickTime movie
jit.qt.record Record a QuickTime movie
jit.qt.videoout Output video to QuickTime video output component
Tutorial 24: QuickTime Effects Tutorial 24: QuickTime Effects
jit.qt.grab
Digitize video from an external source

Description
Use the jit.qt.grab object to digitize video from any QuickTime-compatible video digitizer and decompress the signal into a Jitter
matrix.

Matrix Operator
matrix inputs:1, matrix outputs:1
Name IOProc Planelink Typelink Dimlink Plane Dim Type
out n/a 1 1 1 4 1 char

Information for Jitter Matrix Operator (MOP) messages and attributes to this object

Messages
defaults Restores digitizer image control defaults.
close Closes an open sequence grab component. The component is automatically closed
when the object is freed.
exportimage filename [symbol] Export the current frame as an image file with the name specified by the first
file-type [symbol] argument. The second argument sets the file type (default = png). Available file
use-dialog [int] types are png, bmp, jpeg, macpaint, photoshop, pict, qtimage, sgi, tga and
tiff. An optional use-dialog argument of 1 will open a File dialog to allow you to
enter the image file settings.
You can use the Max Preferences to specify a default image resolution.
getiidc_caps feature name [symbol] MAC OSX ONLY, requires open IIDC device. Reports a list of capabilities for a
specific IIDC feature (see the getiidclist message for information on getting IIDC
features) from the jit.qt.grab object's dump outlet. These capabilities are used to
set the state of the IIDC feature. Since every IIDC device might support different
features, and each feature might support different capabilities, the capabilities list
provides a means of knowing which symbols are valid to set the state (using the
iidc_state message) for any particular feature of a specific device. The capabilities
list typically is formatted as follows: iidc_state feature-name variable capabilities
data .
getiidc_csr offset [int] MAC OSX ONLY, requires open IIDC device. Reports the current value of an IIDC
0/1 [int] register from the jit.qt.grab object's dump outlet, preceded by the symbol
iidc_csr. The offset argument specifies the byte offset to read from. The second
argument, if present and 1, specifies that the byte offset is relative to the initial
unit space (FFFF Fxxx xxxx). Otherwise, the byte offset is relative to the initial
register space (FFFF F000 0000).
getiidc_state feature name [symbol] MAC OSX ONLY, requires open IIDC device. Reports the current state of a specific
IIDC feature (see the getiidclist message for information on getting IIDC
features) from the jit.qt.grab object's dump outlet. The state list typically is
formatted as follows: iidc_state feature-name val feature-value variable
additional data .
getiidclist MAC OSX ONLY, requires open IIDC device. Reports a list of available IIDC
features for the open IIDC component from the jit.qt.grab object's dump outlet,
preceded by the symbol iidclist.
getinputlist Reports the list of available inputs to the video digitizer from the object's right
outlet, preceded by the word inputlist. Note that the digitizer must be open in
order for this method to function.
getsnddevlist Reports the list of available sound digitizers from the object's right outlet,
preceded by the word snddevlist.
getsndinputlist Reports the list of available inputs for the current sound digitizer from the object's
right outlet, preceded by the word sndinputlist. Note that the digitizer must be
open in order for this method to function.
getvdevlist Reports the list of available video digitizers from the object's right outlet, preceded
by the word vdevlist.
iidc_csr data [int] MAC OSX ONLY, requires open IIDC device. Directly sets the state of an IIDC
offset [int] register. The data argument specifies the new value for the register. The offset
0/1 [int] argument, if present, specifies the byte offset to set (if absent, the byte offset is
assumed to be 0). The third argument, if present and 1, specifies that the byte
offset is relative to the initial unit space (FFFF Fxxx xxxx). Otherwise, the byte
offset is relative to the initial register space (FFFF F000 0000).
iidc_state feature name [symbol] MAC OSX ONLY, requires open IIDC device. Sets the current state of a specific
feature-specific data IIDC feature (see the getiidclist message for information on getting IIDC
[list] features). Typically, to set the numeric value of a particular feature, the symbol val
followed by a number is used. For other data (on/off, auto/manual, etc.), valid
symbols used to set the state can be acquired using the getiidc_caps message.
open Opens a sequence grab component. A component must be explicitly opened before
the jit.qt.grab object will began digitizing.
settings Opens the standard video digitizer settings dialog box.
snd_settings Opens the standard sound digitizer settings dialog box.
stop Stops grabbing to disk.
write videofilename [symbol]
Starts grabbing to disk. If the write_split attribute is disabled, only one filename
audiofilename [symbol] argument is required; Otherwise, the video and audio filenames are required. If no
filename arguments are supplied, a file dialog box will open.
FPS [float]
codec [symbol] The default FPS is 30. frames/sec.
spatialquality [symbol] The default codec is raw. The following list of codecs is deprecated (retained for
temporalquality reference). See codeclist for the preferred method to list valid system codecs.
[symbol] Supported codecs are raw, cinepak, graphics, animation, video, componentvideo,
keyframes [symbol] jpeg, mjpega, mjpegb, sgi, planarrgb, macpaint, gif, photocd, qdgx, avrjpeg,
opendmljpeg, bmp, winraw, vector, qd, h261, h263, dvntsc, dvpal, dvpropal, flc,
targa, png, tiff, componentvideosigned, componentvideounsigned, cmyk,
microsoft, sorenson, indeo4, argb64, rgb48, alphagrey32, grey16, mpegyuv420,
yuv420, sorensonyuv9 and mpeg4.

The default spatialquality and temporalquality values are max. Supported quality
settings are lossless, max, min, low, normal, and high. Note that minimum quality
is, in many cases, the codec's default quality. Use "low" quality for consistent
results.

The default keyframes is 0, which will cause keyframes to be inserted


automatically, as necessary.

Attributes
Name Type g/s Description
bitrate int The sound digitizer bit depth (default = digitizer-specific)
8 = digitize sound at 8-bit resolution
16 = digitize sound at 16-bit resolution
blacklevel float The video digitizer black level (default = digitizer-specific)
brightness float The video digitizer brightness level (default = digitizer-specific)
channels int The sound digitizer channel selection (default = digitizer-specific)
1 = digitize sound in mono
2 = digitize sound in stereo
codeclist symbol (get) The valid video codecs available on the system
Sending the message getcodeclist will cause a list of all valid codecs (that is, those
with a functioning compressor component) to be reported from the dumpout. This
list is guaranteed to contain only working codecs, and should be used in preference
to the old, static codec list.
codecquality symbol The video digitizer codec quality. This is only active in vmode 2 (default = 4/max)
0 or min = minimum
1 or low = low
2 or normal = normal
3 or high = high
4 or max = maximum
5 or lossless = lossless

Note that minimum quality is, in many cases, the codec's default quality. Use
"low" quality for consistent results.
colormode symbol The output matrix's color encoding (default = argb)
'argb' = ARGB (alpha, red, green, blue) colormode
'uyvy' = UYVY (YUV 4:2:2 packed) colormode
colorspace int The video digitizer colorspace mode (default = digitizer-specific)
0 = grayscale
1 = color
contrast float The video digitizer contrast level (default = digitizer-specific)
dfg_colormode int TEXT_HERE
dfg_offset int TEXT_HERE
dropreport int Dropped frames reporting flag (default = 0 (disabled))
When this flag is set, the message dropped will be sent from the rightmost outlet
of the jit.qt.grab object, followed by the number of dropped frames, whenever
frame-dropping is detected.
dstrect int The portion of the output matrix used for decompressing media to the internal
matrix. (default = 0 0 (matrix width) (matrix height))
The proportions of the rectangle are expressed in the form left top right bottom .
All values are relative to the top left corner of the viewing area of the output
matrix.
field int The video digitizer field selection (default = digitizer-specific)
0 = digitizer determines field selection
1 = digitizer uses odd field
2 = digitizer uses even field MAC OSX ONLY WITH DFG/1394-1 digitizer (using
ASC-s driver, version 2 or higher) 128 = digitizer uses both fields, alternating 129
= digitizer uses both fields, stacked (upper half is odd, lower half is even)
framerate float The video digitizer frame rate (default = digitizer-specific).
The digitizer has to be closed and re-opened before changes to framerate take
effect.
framereport int Frame reporting flag (default = 0)
When enabled, the message framecalc will be sent from the rightmost outlet of
the jit.qt.grab object as each frame is processed, followed by the number of
milliseconds spent doing so.
gain float The sound digitizer gain (default = digitizer-specific)
gamma float The video digitizer gamma (default = digitizer-specific)
hue float The video digitizer hue adjustment (default = digitizer-specific)
input int The current video digitizer input (default = digitizer-specific)
interp int Image interpolation flag (default = 0)
maxfps float (get) The video digitizer's maximum frame rate (default = digitizer-specific)
playthru int Sound digitizer playthrough flag (default = digitizer-specific)
pll int The phase locked loop (PLL) type (default = digitizer-specific)
0 = broadcast mode
1 = VTR mode
samplerate int Sound digitizer sample rate (default = digitizer-specific)
48000 = 48kHz
44100 = 44.1kHz
32000 = 32kHz
22050 = 22.050kHz
22254 = 22kHz
16000 = 16kHz
11127 = 11kHz
11025 = 11.025kHz
8000 = 8000 Hz
saturation float Video digitizer saturation level (default = digitizer-specific)
sharpness float Video digitizer sharpness level (default = digitizer-specific)
singlefield int Single field flag (default = 1 (enabled))
When the flag is set, an attempt is made to decompress one field of an interlaced
frame at high quality, and then scale the image to the frame size. If the digitizer
doesn't provide interlaced frames, this flag does nothing.
snd_active int (set) Sound digitizer enable flag (default = 0)
sndcodec symbol Sound digitizer codec mode (used for recording) (default = digitizer-specific)
none = no compression
raw = raw compression
big16 = 16-bit big endian
little16 = 16-bit little endian
float32 = 32-bit floating point
float64 = 64-bit floating point
24bit = 24-bit integer
32bit = 32-bit integer
little32 = 32-bit little endian
mace3 = MACE 3:1
mace6 = MACE 6:1
cdxa4 = CD/XA 4:1
cdxa2 = CD/XA 2:1
ima = IMA 4:1
ulaw = uLaw 2:1
alaw = aLaw 2:1
adpcm = Microsoft ADPCM (ACM code 2)
dviima = DVI/Intel IMA ADPCM (ACM code 17)
dvaudio = DV Audio
qdesign = QDesign music
qdesign2 = QDesign2 music
qualcomm = Qualcomm PureVoice
mp3 = MPEG Layer 3 (CBR or VBR)
snddevice int The current sound digitizer (default = 0)
sndinput int The current sound input for the selected sound digitizer (default = 0)
srcrect int Source rect from digitizer frame (default = 0 0 (matrix width) (matrix height))
standard symbol (set) The video digitizer standard selection (default = digitizer-specific)
ntsc = NTSC
pal = PAL
secam = SECAM
unique int Unique frame filter flag (default = 0 (disabled))
When the flag is set, only new frames from the digitizer are output when the
object receives a bang. If no new frame has been received from the digitizer, the
jit.qt.grab object will not respond to the bang.
uniqueid int (get) Unique camera ID
usedstrect int Destination rect flag (default = 0) When the flag is set, the dstrect attributes are
used when copying an input matrix to the internal matrix.
usesrcrect int Source rect flag (default = 0) When the flag is set, the srcrect attributes are used
when copying an input matrix to the internal matrix.
vdevice int The current video digitizer (default = 0)
vmode int The video digitizer mode (default = 0 (sequence grab))
0 = sequence grab mode
1 = vdig mode (necessary/desirable for some digitizers)
2 = DV high quality mode
volume float The sound digitizer volume (default = digitizer-specific)
whitelevel float The video digitizer white level (default = digitizer-specific)
window symbol Window name (default = none) If this attribute is set, the jit.qt.grab object will
render directly into the named jit.window object, thus able to use hardware
decompression and interpolation as permitted by QuickTime. The window must
have noaccel set to 1 in order for this to work.
If no symbol argument is given, the jit.qt.grab object's default behaviour of
rendering to and outputting a matrix is used.

write_audio int Audio track write flag (default = 0) When the flag is set, an audio track is written
when grabbing images to disc.
write_length int The length (in frames) to limit write operations to (default = 0 (inactive)) When
non-zero, limits the disk grab to the specified number of frames. The write
operation will stop automatically. If you are grabbing sound only, write_length
has no effect.
write_preview int Image preview flag (default = 0) When the flag is set, images can be previewed
when grabbing images to disc.
write_split int Split file write flag (default = 0) When the flag is set, separate disk files for audio
and video are written when grabbing images to disc. Otherwise, a single file
containing both is written.
write_video int Video track write flag (default = 1) When the flag is set, a video track is written
when grabbing images to disc.

Information for box attributes common to all objects

Examples

See Also
Name Description
jit.qt.effect QuickTime Effects for Jitter matrices
jit.dx.grab Digitize video using DirectX (Windows)
jit.qt.movie Play or edit a QuickTime movie
jit.qt.record Record a QuickTime movie
jit.dx.videoout Output video to DirectX (Windows)
jit.qt.videoout Output video to QuickTime video output component
Tutorial 21: Working With Live Tutorial 21: Working With Live Video and Audio Input
Video and Audio Input
jit.qt.movie
Play or edit a QuickTime movie

Description
Use the jit.qt.movie for working with QuickTime movies - playback, editing, import, export, effect generation and direct-to-
video-output-component streaming.

Matrix Operator
matrix inputs:0, matrix outputs:1
Name IOProc Planelink Typelink Dimlink Plane Dim Type
out n/a 1 1 1 4 1 char

Information for Jitter Matrix Operator (MOP) messages and attributes to this object

Messages
addbgtrack red [int] Adds a background color track. Three arguments in the range 0-255 specify the
green [int] RGB components of the track.
blue [int]
addfxtrack filename [symbol] Adds a QuickTime Effect track or track group. The filename refers to a qtfx file
generated by jit.qt.effect. Using the symbol dialog in place of the filename
offset [int] argument opens a file selection dialog, which permits you to you choose a file
duration [int] name. The message requires a time offset , a time duration and a reference to
src1-track- existing tracks in the current movie to use as sources. The precise number of
number [int] source tracks used will vary depending on the specific QuickTime effect.
src2-track-
number [int]
addtrack track-type Adds a track and associated media to the movie, as specified by the track-type .
[symbol] Supported track types are video, sound, text, base, mpeg, music, timecode,
sprite, flash, movie, tween, and 3d.
(drag) Load a QuickTime-compatible media file
append src-name Appends a portion of movie or track media to the current movie or track. To
[symbol] specify the entire movie as the source (and target), omit the source argument. If
group (optional) the symbol dialog is used for the src-name argument, a file selection dialog will be
track [int] presented to choose a file. If the symbol scrap is used for the src-name argument,
src-track- the jit.qt.movie object will attempt to read the source from the clipboard.
number [int] To specify a track, use track track-number in the source and destination fields,
end group where track-number is a valid track number (e.g., append mayhem.mov track 3
time-start [int] 0 10000 track 2). A target track value of -1 creates a new track. You can also
time-end [int] specify an entire movie by using track 0.
group (optional)
track [int]
dst-track-
number [int]
end group
asyncimport filename [symbol] Reads non-movie formats recognized by QuickTime, such as CD tracks,
asynchronously, if possible. The filename argument specifies a source file, or you
show-import- can use the word dialog to open a file selection dialog. The converted-filename
dialog [int] argument specifies a destination file for the imported/converted file, or you can
converted- use the word dialog to open a file selection dialog. If you don't explicitly provide a
filename [symbol] filename for the converted file, a temporary file will be created and later destroyed
when you unload or close the movie. The show-import-dialog flag, if set to 1,
opens the appropriate import settings dialog for the type of file being imported.
Settings persist, so you should only have to set them up once, if you are importing
a batch of similar files.
asyncread src-name Asynchronously reads a movie from a disk file, if possible. If no argument is
[symbol] present, or if the symbol dialog is used for the src-name argument, a file selection
dialog will be presented to choose a file. Any argument is assumed to be a local file
name. At this time, asynchronous reading is not supported for URL- or clipboard-
based movies; the normal read behavior will be used instead.
deletetrack track-number Delete a specified track number
[int]
dispose Close the currently loaded movie
cancelframedump Stops the frame dump process. See framedump.
copy src-name Copies an entire movie or track to the current movie. To specify the entire movie
[symbol] as the source (and target), omit the source arguments. If the symbol dialog is used
group (optional) for the src-name argument, a file selection dialog will be presented to choose a
track [int] file. If the symbol scrap is used for the src-name argument, the jit.qt.movie
src-track- object will attempt to read the source from the clipboard. To specify a track, use
number [int] track track-number in the source and target fields. A target track value of -1
end group creates a new track. You can also specify an entire movie by using track 0.
group (optional)
track [int]
dst-track-
number [int]
end group
cut group (optional) Deletes a selected portion of a track or movie. To specify the entire movie for the
track [int] operation, omit the track arguments. To specify a track, use track track-number .
track-number Specifying the noshift argument will replace the deleted portions of the file or
[int] track with empty time.
end group
start-time [int]
end-time [int]
noshift [int]
deletebgtrack Delete a previously created background color track
flash_var variable path Passes a value to a Flash ActionScript variable specified by the variable path
[symbol] argument to the method. This path should conform to the ActionScript path spec (
data [list] path/to.variable ) for the variable in question. At this time, only simple
ActionScript variables are supported (no arrays).
frame frame-number Jump to a frame number (fast method)
[int]
frame_true frame-number Jump to a frame number (slower, more accurate method)
[int]
export filename [symbol] Saves movies in non-native QuickTime formats (including still image formats).
Using the symbol dialog in place of the filename argument opens a Save dialog,
file-type which lets you choose a file name. Using the symbol fulldialog in place of the
[symbol] filename argument will show you an exporter-specific Export dialog box before the
show- movie is exported. Setting the optional final argument to 1 will show you a
configuration- configuration dialog box before the movie is exported.
dialog [int]
exportaudio Exports the movie audio using the current spigot~ settings. Mostly for internal
use, this message can be used to batch-export movie audio for later use with
spigot~.
exportfile filename [symbol] Saves movies in non-native QuickTime formats (including still image formats).
Using the symbol dialog in place of the filename argument opens a Save dialog,
file-type which lets you choose a file name. Using the symbol fulldialog in place of the
[symbol] filename argument will show you an exporter-specific Export dialog box before the
show- movie is exported. Setting the optional final argument to 1 will show you a
configuration- configuration dialog box before the movie is exported.
dialog [int]
exportimagesettings Opens the settings dialog box for image export. Any changes made are applied to
subsequent exportimage operations.
exportsettings Opens the settings dialog box for the currently chosen exporter component. Any
changes made are applied to subsequent export operations performed with the
same exporter.
deletefxtrack Deletes a previously created QuickTime Effects track or track group. QuickTime
Effects tracks are identified using special reserved names such as ___effect_track
or ___effect_src1. This message will delete any and all tracks having such reserved
names.
flatten filename [symbol] Creates a "flattened" movie with no unresolved data references (i.e., the movie is
self-contained). If a filename is not specified, the Save dialog will be shown, unless
inplace [symbol] the inplace argument is present (see below). The flatten message can take a
compress number of optional symbol arguments, which may appear in any order:
[symbol] inplace = a new file will not be created. the movie will be flattened in place
faststart [symbol] compress = compress the movie resource
faststart = places the movie resource before the data in the file
activeonly activeonly = flatten and copy active tracks only
[symbol]
exportimage src-name Exports the current movie frame as an image file. If no src-name is specified, an
[symbol] optional final argument of 1 will open a file dialog. Available file types are png,
file-type bmp, jpeg, macpaint, photoshop, pict, qtimage, sgi, tga and tiff. If no file
[symbol] type is specified, the file type specified for the last image export will be used. If no
show-file-dialog images have been exported, the png filetype will be used as the default.
[int] You can use the Max Preferences to specify a default image resolution.
getexporterlist Reports available export components
getflash_var variable path Retrieves the value of a Flash ActionScript variable specified by the variable path
[symbol] argument to the method. This path should conform to the ActionScript path spec (
path/to.variable ) for the variable in question. At this time, only simple
ActionScript variables are supported (no arrays).
getgmode src-name Reports a track's graphics mode from the object's right outlet, using the format
[symbol] trackgmode track-number graphic-mode red green blue . An optional src-name
track-number argument can be used to used to specify a source other than the current movie.
[int] Using the symbol dialog rather than specifying a source will open a file selection
dialog. If no track number is specified, separate line listings for each track are sent
out the right outlet.
gettrackclip src-name Reports a track's clipping region from the object's right outlet, using the format
[symbol] trackclip track-number clip-left clip-top clip-right clip-bottom . An optional src-
track-number name argument can be used to used to specify a source other than the current
[int] movie. Using the symbol dialog rather than specifying a source will open a file
selection dialog. If no track number is specified, separate line listings for each
track are sent out the right outlet.
gettrackcount src-name Reports the number of tracks in a movie from the object's right outlet, preceded by
[symbol] the word trackcount. An optional src-name argument can be used to used to
specify a source other than the current movie. Using the symbol dialog rather
than specifying a source will open a file selection dialog.
gettrackbass src-name Reports a track's bass EQ level from the object's right outlet, using the format
[symbol] trackbass track-number sound bass level . Values can be between -1. and 1. An
track-number optional src-name argument can be used to used to specify a source other than the
[int] current movie. Using the symbol dialog rather than specifying a source will open a
file selection dialog. If no track number is specified, separate line listings for each
track are sent out the right outlet.
gettrackdim src-name Reports a track's dimensions from the object's right outlet, using the format
[symbol] trackdim track-number width height . An optional src-name argument can be
track-number used to used to specify a source other than the current movie. Using the symbol
[int] dialog rather than specifying a source will open a file selection dialog. If no track
number is specified, separate line listings for each track are sent out the right
outlet.
gettrackenabled src-name Reports a track's enabled status from the object's right outlet, using the format
[symbol] trackenabled track-number enabled-status . An optional src-name argument can
track-number be used to used to specify a source other than the current movie. Using the symbol
[int] dialog rather than specifying a source will open a file selection dialog. If no track
number is specified, separate line listings for each track are sent out the right
outlet.
gettrackduration src-name Reports a track's duration from the object's right outlet, using the format
[symbol] trackduration track-number duration . An optional src-name argument can be
track-number used to used to specify a source other than the current movie. Using the symbol
[int] dialog rather than specifying a source will open a file selection dialog. If no track
number is specified, separate line listings for each track are sent out the right
outlet.
gettrackcodec src-name Reports a track's codec from the object's right outlet, using the format trackcodec
[symbol] track-number codec-number codec-name out the object's right outlet. An optional
track-number src-name argument can be used to used to specify a source other than the current
[int] movie. Using the symbol dialog rather than specifying a source will open a file
selection dialog. If no track number is specified, separate line listings for each
track are sent out the right outlet.
gettrackgmode src-name Reports a track's graphics mode from the object's right outlet, using the format
[symbol] trackgmode track-number graphic-mode red green blue . An optional src-name
track-number argument can be used to used to specify a source other than the current movie.
[int] Using the symbol dialog rather than specifying a source will open a file selection
dialog. If no track number is specified, separate line listings for each track are sent
out the right outlet.
gettrackinfo src-name Reports general information about a track from the object's right outlet, using the
[symbol] format trackinfo track-number track-type enabled-status layer-number . An
track-number optional src-name argument can be used to used to specify a source other than the
[int] current movie. Using the symbol dialog rather than specifying a source will open a
file selection dialog. If no track number is specified, separate line listings for each
track are sent out the right outlet.
gettracklayer src-name Reports a track's layer information from the object's right outlet, using the format
[symbol] tracklayer track-number visibility-number-layer .
track-number
[int]
gettrackname src-name Reports a track's name from the object's right outlet, using the format trackname
[symbol] track-number track-name . An optional src-name argument can be used to used
track-number to specify a source other than the current movie. Using the symbol dialog rather
[int] than specifying a source will open a file selection dialog. If no track number is
specified, separate line listings for each track are sent out the right outlet.
gettrackoffset src-name Reports a track's time offset from the object's right outlet, using the format
[symbol] trackoffset track-number time-offset . An optional src-name argument can be
track-number used to used to specify a source other than the current movie. Using the symbol
[int] dialog rather than specifying a source will open a file selection dialog. If no track
number is specified, separate line listings for each track are sent out the right
outlet.
gettracktimescale src-name Reports a track's timescale from the object's right outlet, using the format
[symbol] tracktimescale track-number track-timescale . An optional src-name argument
track-number can be used to used to specify a source other than the current movie. Using the
[int] symbol dialog rather than specifying a source will open a file selection dialog. If
no track number is specified, separate line listings for each track are sent out the
right outlet.
gettracktype src-name Reports a track's type from the object's right outlet, using the format tracktype
[symbol] track-number mediatype . An optional src-name argument can be used to used to
track-number specify a source other than the current movie. Using the symbol dialog rather
[int] than specifying a source will open a file selection dialog. If no track number is
specified, separate line listings for each track are sent out the right outlet.
gettracktypecode src-name Reports a track's typecode from the object's right outlet, using the format
[symbol] tracktypecode track-number track-typecode . An optional src-name argument
track-number can be used to used to specify a source other than the current movie. Using the
[int] symbol dialog rather than specifying a source will open a file selection dialog. If
no track number is specified, separate line listings for each track are sent out the
right outlet.
getvoclist Report available video output components
getvocmodes Report available video output component modes
getvrframes Report current VR node frame arrangement (columns by rows)
getvrnodelist Report available VR movie nodes
gmode track-number Reports a track's graphics mode from the object's right outlet, using the format
[int] trackgmode track-number graphic-mode red green blue . An optional src-name
mode [int] argument can be used to used to specify a source other than the current movie.
red [int] Using the symbol dialog rather than specifying a source will open a file selection
green [int] dialog. If no track number is specified, separate line listings for each track are sent
blue [int] out the right outlet.
framedump start-frame [int] Commences a framedump, in which the movie will start from a frame specified by
end-frame [int] start-frame (the default is 1) and automatically output frames in sequence (no
frame-skip [int] bang or outputmatrix message is necessary) up to the frame specified by end-
frame , skipping frame-skip frames between each frame. The default values are 1
for the start frame, and the total framecount of the movie for the end frame. The
default frame-skip value is 1.
During operation, the message framedump current_frame is sent out the right
outlet after each frame has been output. When finished, the message framedump
done is output.
gettrackpan src-name Reports a track's pan value from the object's right outlet, using the format
[symbol] trackpan track-number sound pan value . Values can be between -1. and 1. An
track-number optional src-name argument can be used to used to specify a source other than the
[int] current movie. Using the symbol dialog rather than specifying a source will open a
file selection dialog. If no track number is specified, separate line listings for each
track are sent out the right outlet.
gettracktreble src-name Reports a track's treble EQ level from the object's right outlet, using the format
[symbol] tracktreble track-number sound treble level . Values can be between -1. and 1. An
track-number optional src-name argument can be used to used to specify a source other than the
[int] current movie. Using the symbol dialog rather than specifying a source will open a
file selection dialog. If no track number is specified, separate line listings for each
track are sent out the right outlet.
gettrackvol src-name Reports a track's audio volume from the object's right outlet, using the format
[symbol] trackvol track-number sound amplitude level . Values can be between -1. and 1.
track-number (values below 0. aren't audible). An optional src-name argument can be used to
[int] used to specify a source other than the current movie. Using the symbol dialog
rather than specifying a source will open a file selection dialog. If no track number
is specified, separate line listings for each track are sent out the right outlet.
jump frame-offset [int] Jump to a relative movie frame (fast method)

jump_true frame-offset [int] Jump to a relative movie frame (slower, more accurate method)

insert src-name Inserts a portion of movie or track media into the current movie or track, shifting
[symbol] any existing data to make room. To specify the entire movie as the source (and
group (optional) target), omit the source argument. If the symbol dialog is used for the src-name
track [int] argument, a file selection dialog will be presented to choose a file. If the symbol
src-track- scrap is used for the src-name argument, the jit.qt.movie object will attempt to
number [int] read the source from the clipboard.
end group To specify a track, use track track-number in the source and destination fields,
time-start [int] where track-number is a valid track number (e.g., insert mayhem.mov track 3 0
time-end [int] 10000 track 2 0 10000). A target track value of -1 creates a new track. You can
group (optional) also specify an entire movie by using track 0.
track [int]
dst-track-
number [int]
end group
time-start [int]
time-end [int]
import filename [symbol] Reads non-movie formats recognized by QuickTime, such as CD tracks. The
filename argument specifies a source file, or you can use the word dialog to open
show-import- a file selection dialog. The converted-filename argument specifies a destination
dialog [int] file for the imported/converted file, or you can use the word dialog to open a file
converted- selection dialog. If you don't explicitly provide a filename for the converted file, a
filename [symbol] temporary file will be created and later destroyed when you unload or close the
movie. The show-import-dialog flag, if set to 1, opens the appropriate import
settings dialog for the type of file being imported. Settings persist, so you should
only have to set them up once, if you are importing a batch of similar files.
loadram track-number Loads a specified movie or track into RAM. Without arguments, loadram loads
[int] the entire movie. To specify an entire track, use a valid track number as a single
group (optional) argument.
time-start [int] Two additional arguments may be used to specify start and end times for the
time-end [int] loadram operation. So, loadram followed by 2 arguments will load a specified
end group portion of an entire movie, while loadram followed by 3 arguments will cause the
jit.qt.movie to load a portion of a single track into RAM.
keypress ASCII value [int] Passes the description of keyboard activity to a Flash movie. The argument format
key code [int] is identical to that output from the key object in response to keypresses.
modifiers [int]
kill Deletes the diskfile associated with the currently loaded movie. This command
does not offer a warning dialog, and cannot be undone.
newmovie width [int] Creates a new empty movie of the specified width and height (default 320 240)
height [int] and timescale (default 600) to fill as you desire.
timescale [int]
mouse x [int] Passes the description of a mouse movement or click to a Flash movie. The
y [int] argument format is identical to that output from the jit.window and jit.pwindow
button-flag [int] objects in response to mouse activity. The key modifiers flags are currently unused,
group (optional) although their presence has no adverse affects and simplifies patching.
cmd/ctrl-flag
[int]
shift-flag [int]
caps-flag [int]
opt/alt-flag [int]
Mac-ctrl-flag
[int]
end group
mxform track-number Sets up a movie or track geometrical matrix transformation using the same 3x3
[int] matrix used with the jit.mxform2d object. The matrix transform can be used to
a [float] perform scaling, rotation, skewing, and perspective operations on a movie or track
b [float] using a list of 9 floating point values for the 3x3 transformation matrix. (default 1.
u [float] 0. 0. 0. 1. 0. 0. 0. 1.) For more information on this transformation, see the
c [float] jit.mxform2d object reference page.
d [float]
v [float]
tx [float]
ty [float]
w [float]
opcolor track-number Sets a track's opcolor, used by some QuickTime gmodes. The message arguments
[int] specify a track number and three integers in the range 0-255 specify the RGB
red [int] value of the opcolor.
green [int]
blue [int]
paste src-name Pastes a portion of movie or track media into the current movie or track,
[symbol] overwriting any existing data. To specify the entire movie as the source (and
group (optional) target), omit the source argument. If the symbol dialog is used for the src-name
track [int] argument, a file selection dialog will be presented to choose a file. If the symbol
src-track- scrap is used for the src-name argument, the jit.qt.movie object will attempt to
number [int] read the source from the clipboard.
end group To specify a track, use track track-number in the source and destination fields,
time-start [int] where track-number is a valid track number (e.g., paste mayhem.mov track 3 0
time-end [int] 10000 track 2 0 10000). A target track value of -1 creates a new track. You can
group (optional) also specify an entire movie by using track 0.
track [int]
dst-track-
number [int]
end group
time-start [int]
time-end [int]
prepend src-name Prepends a portion of movie or track media to the current movie or track. To
[symbol] specify the entire movie as the source (and target), omit the source argument. If
group (optional) the symbol dialog is used for the src-name argument, a file selection dialog will be
track [int] presented to choose a file. If the symbol scrap is used for the src-name argument,
src-track- the jit.qt.movie object will attempt to read the source from the clipboard.
number [int] To specify a track, use track track-number in the source and destination fields,
end group where track-number is a valid track number (e.g., append mayhem.mov track 3
time-start [int] 0 10000 track 2). A target track value of -1 creates a new track. You can also
time-end [int] specify an entire movie by using track 0.
group (optional)
track [int]
dst-track-
number [int]
end group
start Starts movie playback at the current rate from the current QuickTime time value
specified by time.
stop Stops movie playback. rate is unaffected).
read src-name Reads a movie from a disk file, URL or the clipboard. If no argument is present, or
[symbol] if the symbol dialog is used for the src-name argument, a file selection dialog will
be presented to choose a file. If the argument scrap is used for the src-name
argument, the object will attempt to load a movie from the clipboard. If the
argument is parsable as an http://, ftp:///, file://, or rtsp:// URL, the object will
attempt to load a movie from that location. Otherwise, an argument is assumed to
be a local file name.
If autostart is enabled, the movie will begin playing at once.
unloadram Unloads any previously loaded portions of the current movie from RAM. Portions
of the movie may have been loaded into RAM through use of the loadram
message, or through the asyncread and preroll messages, which preroll sections
of the movie into RAM, as well.
tighten src-name Remove empty time from a movie or a track media
[symbol]
group (optional)
track [int]
track-number
[int]
end group
trackbass track-number Sets a track's bass EQ level. Valid input values are between -1. and 1.
[int]
bass-level [int]
trackdim track-number Set a track's dimensions
[int]
width [int]
height [int]
trackclip track-number Set a track's clipping region
[int]
left [int]
top [int]
right [int]
bottom [int]
trackenabled track-number Enable/disable a track
[int]
0/1 [int]
trackduration track-number Sets a track's duration. The track will be scaled to the new duration.
[int]
duration [int]
trackgmode track-number Sets a track's graphic mode. The arguments specify a track number, an integer
[int] which specifies the graphic mode, and three integers in the range 0-255 which
mode [int] specify the RGB value of the opcolor. Available graphic mode numbers are:
red [int] 0 = srcCopy
green [int] 1 = srcOr
blue [int] 2 = srcXor
3 = srcBic
4 = notSrcCopy
5 = notSrcOr
6 = notSrcXor
7 = notSrcBic
8 = patCopy
9 = patOr
10 = patXor
11 = patBic
12 = notPatCopy
13 = notPatOr
14 = notPatXor
15 = notPatBic
32 = blend
33 = addPin
34 = addOver
35 = subPin
36 = transparent
37 = addMax
38 = subOver
39 = adMin
49 = grayishTextOr
50 = highlighttransfermode
64 = ditherCopy
256 = graphicsModeStraightAlpha
257 = graphicsModePreWhiteAlpha
258 = graphicsModePreBlackAlpha
260 = graphicsModeStraightAlphaBlend
tracklayer track-number Sets a track's visibility layer. Valid visibility layer values are integers between -
[int] 32768 and 32767. Lower numbers are "on top".
layer-number
[int]
trackname Set a track's name
trackoffset track-number Set a track's time offset
[int]
offset-value [int]
trackopcolor track-number Sets a track's opcolor, used by some QuickTime gmodes. The message arguments
[int] specify a track number and three integers in the range 0-255 specify the RGB
red [int] value of the opcolor.
green [int]
blue [int]
trackpan track-number The track's panning. Valid input values are between -1. (left channel only) and 1.
[int] (right channel only).
pan [int]
tracktimescale track-number Adjusts a track's timescale. The default timescale is media dependent.
[int]
timescale [int]
tracktreble track-number Sets a track's treble EQ level. Valid input values are between -1. and 1.
[int]
treble-level [int]
trackvol track-number Set a track's amplitude level. Valid input values are between -1. and 1. (values
[int] below 0 are inaudible).
volume [int]
trim track-number Retains a selected portion of movie or track between the time points specified by
[int] the start and end arguments, deleting the rest. Setting the noshift argument to a
start [int] non-zero value will replace the deleted portions of the file or track with blank
end [int] space. Setting the scale argument to a non-zero value will scale the remaining
mutex group portion to the length of the original movie or track.
(optional)
noshift [int]
scale [int]
endmutex group
savemovie Saves the current movie to the currently referenced disk file. If there is no
currently referenced disk file (e.g. the movie was read from a URL or from the
clipboard), this message operates as savemovieas.
savemovieas filename [symbol] Saves the current movie under a new filename, and changes the movie's file
reference to the saved file. In the absence of a filename argument, or if dialog is
specified in place of a filename, the object will present a standard file selection
dialog.
savemoviecopy filename [symbol] Saves a copy of the current movie under a new filename, without changing the
movie's file reference to the saved file (subsequent saves continue to reference
whatever file (if any) was referred to previous to issuing the message). In the
absence of a filename argument, or if dialog is specified in place of a file name,
the object will present a standard file selection dialog.
scale group (optional) Temporally scales a portion of movie or track media. The media will be selected
track [int] between start and end and scaled to the range start to scaled end. To specify the
track-number entire movie for the operation, omit the track argument. To specify a track, use
[int] track track-number in the track number field, where track-number is a valid
end group track number.
start [int]
end [int]
scaled-end [int]
undo Revert the most recent editing operation
toscrap group (optional) Copies a movie or track (or portion thereof) to the clipboard. The message toscrap
track [int] with no arguments copies the entire movie. The message toscrap track track-
src-track- number copies a track to the clipboard. Additional optional arguments specify the
number [int] start and end times of the movie to copy.
end group
time-start [int]
time-end [int]

Attributes
Name Type g/s Description
acodec symbol Audio codec
adapt int Adapt output matrix dimensions to movie size flag
autosave int Autosave movie on close flag (default = 0)
autostart int Autoplay on movie open flag (default = 1)
codec symbol The visual codec, used by the export message
codecquality symbol The visual codec quality, used by the export message
colormode symbol The output matrix's color encoding
'argb' = ARGB (alpha, red, green, blue) colormode
'uyvy' = UYVY (YUV 4:2:2 packed) colormode
deinterlace int Deinterlace playback hint flag (default = movie-dependent). When enabled,
decompresses both fields of an interlaced movie at high quality, and then filters
the image to reduce interlacing artifacts. Notes: Requires QuickTime version 6.5 or
above, and the highquality attribute to be enabled. Playback hints are saved with
the movie, if any of the jit.qt.movie object's save methods are used.
dstrect int The portion of the output matrix used for decompressing media to the internal
matrix (default = 0 0 (matrix width) (matrix height))
The bounds of the rectangle are expressed in the form left top right bottom . All
values are relative to the top-left corner of the viewing area of the output matrix.
duration int The duration of the movie. When setting the duration, the entire movie will be
scaled to the new length, unless the additional argument noscale is used. In that
case, the movie length is changed without scaling. For more precise control of
scaling, use the scale message.
editduration int The duration of the movie, in the same units specified by editmode
editmode int Editing time-value mode (default = 0 (QuickTime time units)). Sets the expected
time units for certain editing operations. At the time of this writing, the following
operations support editmode: loadram, unloadram, insert, paste, trim, cut,
scale, prepend, append, looppoints, loopstart and loopend.
0 = QuickTime time units (TimeScale-based)
1 = Milliseconds
2 = Frames
3 = True frames
edittime int The current time in the movie, in the same units specified by editmode
exporter int The currently selected export component (referenced by position in the output list
from getexporterlist)
fps float (get) Internal FPS for the movie
framecount int (get) Number of frames in the movie
framereport int Frame reporting flag (default = 0). When enabled, the message framecalc will be
sent from the rightmost outlet of the jit.qt.movie object as each frame is
processed, followed by the number of milliseconds spent doing so.
highquality int High quality playback hint flag (default = movie-dependent). When enabled, the
movie renders at the highest possible quality, at the expense of time and memory.
Note: playback hints are saved with the movie, if any of the jit.qt.movie object's
save methods are used.
id3album symbol The album ID3 tag is used to tag MP3 file content.
id3artist symbol The artist ID3 tag is used to tag MP3 file content.
id3comment symbol The comment ID3 tag is used to tag MP3 file content.
id3date symbol The date ID3 tag is used to tag MP3 file content.
id3encoder symbol The encoder ID3 tag is used to tag MP3 file content.
id3name symbol The track name ID3 tag is used to tag MP3 file content.
id3track symbol The track number ID3 tag is used to tag MP3 file content.
id3url symbol The track URL ID3 tag is used to tag MP3 file content.
interp int Output interpolation flag
loop int Looping mode (default = 1 (start to end))
0 = no looping
1 = normal looping (start to end)
2 = palindrome looping (start to end to start to ....)
3 = no looping, but use looppoints to define playback limits
loopend int The movie loop point end. Time is specified as QuickTime time values.
looppoints int The movie loop points. Time is specified as QuickTime time values.
loopreport int Loop notification flag (default = 0). When enabled, the jit.qt.movie object will
send the message loopnotify when the playing movie passes the loop point. In
palindrome looping mode, the message will be sent at both the beginning and the
end of the movie.
loopstart int The movie loop point start. Time is specified as QuickTime time values.
movie_dim int (get) Native movie dimensions
moviedim int (get) Native movie dimensions
moviename symbol Movie file name
moviepath symbol (get) The movie's fully-specified path on disk (if the movie has a disk-file).
movierate float (get) The movie's actual rate (reflecting start/stop/palindrome looping).
poster int The movie's poster frame. An optional int argument specifies the time to use. Time
is specified as QuickTime time values. The default is to use the first frame.
preroll int Preroll movie on stop flag (default = 0). When enabled, the jit.qt.movie object
will attempt to asynchronously preroll the next section of the current movie for
fast, non-interrupting restart.
rate float Movie rate
singlefield int Single-field playback hint flag (default = movie-dependent). When enabled,
decompresses one field of an interlaced movie at high quality, and then scales the
image to the frame size. Notes: Requires the highquality attribute to be enabled.
Playback hints are saved with the movie, if any of the jit.qt.movie object's save
methods are used.
soc symbol Name of the spigot~ object associated with the movie
srcrect int The portion of the QuickTime movie to decompress into a matrix (default = 0 0
(movie width) (movie height)). The bounds of the rectangle are expressed in the
form left top right bottom . All values are relative to the top-left corner of the
viewing area of the movie.
time int The current time in the movie. Time is specified as QuickTime time values.
timecode symbol (get) The movie's timecode. If the current movie has a Timecode track, sends the list
timecode timecode-val . If the timecode is to be interpreted as a simple counter
(see timecodeinfo, below), the list has a single timecode-val : the counter. If the
timecode represents a timer value, the list has 4 elements, which represent hours ,
minutes , seconds , frames .
timecodeinfo symbol (get) The movie's timecode definition information. If the current movie has a Timecode
track, sends the list timecodeinfo [ drop/nondrop ] [ counter/time ] [ fps1 ] [ fps2
]. These represent:
drop/nondrop = whether timecode drops frames occasionally to stay in
synchronization (possible values: drop, nondrop).
counter/timer = whether timecode should be interpreted as a simple counter,
rather than as a time value (possible values: counter, timer).
fps1 = a frames-per-second calculation, based on the number of time units per
second, divided by the standard duration of a frame, as provided by the timecode
definition.
fps2 = frames-per-second, as provided by the timecode definition. If the timecode
is to be interpreted as a counter (see counter/timer , above, this is the number of
frames stored per timer "tick".
timecodevis int Timecode track visibility flag (default = 0). When enabled, any Timecode tracks in
the current movie are made visible (rendered in the frame).
timescale int (get) The timescale for the movie (default = 600, but movie-dependent)
unique int Unique frame filter flag (default = 0 (disabled)). When the flag is set, only new
frames from the movie are output when the object receives a bang. If no new
frame has been decompressed, the jit.qt.movie object will not respond to the
bang.
use_movie_loop int Internal looping mode flag (default = 0 (use object's loop attribute))
0 = use the object's loop attribute to determine looping status, ignoring any
internal looping information in the movie itself.
1 = the movie's internal looping status overrides the object's loop attribute.
usedstrect int Destination rect flag (default = 0). When the flag is set, the dstrect attributes are
used when copying an input matrix to the internal matrix.
usemovieloop int Internal looping mode flag (default = 0 (use object's loop attribute))
0 = use the object's loop attribute to determine looping status, ignoring any
internal looping information in the movie itself.
1 = the movie's internal looping status overrides the object's loop attribute.
usesrcrect int Source rect flag (default = 0). When the flag is set, the srcrect attributes are used
when copying an input matrix to the internal matrix.
voc int Video output component playback mode (default = -1)
-1 or no argument = video output component playback off
0 or above = video output component playback on (argument determines which
component to use, using an index derived from its position in the list generated by
the getvoclist message).
voc_sound_mode int VOC sound mode flag (default = 0). When the flag is set, movie sound is not
passed to the VOC when in video output component playback mode (see the voc
attribute for more information.)
vocmode int The video output component mode (e.g. for DV, this might be NTSC or PAL)
(default = component-specific)
vol float Movie sound volume
vrcorrection int The current VR node imaging correction (warping) (default = movie-specific), only
applies to panoramic nodes
0 = No warping
1 = 1-dimensional warping
2 = 2-dimensional warping
vrfov float The current VR movie field of view (default = movie-specific). Valid ranges are
typically in the range 8-145.
vrnode int The current VR node (default = movie-specific).
vrpan float The current VR movie pan (default = movie-specific).
vrquality int The current VR node quality (default = movie-specific), only applies to panoramic
nodes
0 = Minimum quality
1 = Low quality
2 = Normal quality
3 = High quality
4 = Maximum quality
vrtilt float The current VR movie tilt (default = movie-specific).
window symbol Window name (default = none). If this attribute is set, the jit.qt.movie object will
render directly into the named jit.window object, and will use hardware
decompression and interpolation as permitted by QuickTime. The window must
have noaccel set to 1 in order for this to work. If no symbol argument is given, the
jit.qt.movie object's default behaviour of rendering to and outputting a matrix is
used.

Information for box attributes common to all objects

Examples
See Also
Name Description
jit.dx.grab Digitize video using DirectX (Windows)
jit.qt.effect QuickTime Effects for Jitter matrices
jit.qt.grab Digitize video from an external source
jit.qt.record Record a QuickTime movie
jit.qt.videoout Output video to QuickTime video output component
Tutorial 1: Playing a QuickTime Tutorial 1: Playing a QuickTime Movie
Movie
Tutorial 4: Controlling Movie Tutorial 4: Controlling Movie Playback
Playback
Tutorial 19: Recording QuickTime Tutorial 19: Recording QuickTime movies
movies
Tutorial 24: QuickTime Effects Tutorial 24: QuickTime Effects
Tutorial 44: Flash Interactivity Tutorial 44: Flash Interactivity
Tutorial 49: Colorspaces Tutorial 49: Colorspaces
Appendix A: QuickTime Appendix A: QuickTime Confidential
Confidential
jit.qt.record
Record a QuickTime movie

Description
The jit.qt.record object take a sequence of Jitter matrices as input, saving the sequence to disk as a QuickTime movie.

Matrix Operator
matrix inputs:1, matrix outputs:1
Name IOProc Planelink Typelink Dimlink Plane Dim Type
out n/a 1 1 1 1 1 char long float32 float64

Information for Jitter Matrix Operator (MOP) messages and attributes to this object

Messages
stop Stop recording.
write movie-name [symbol] Writes the sequence of incoming Jitter matrices to a disk file as a QuickTime
FPS [float] movie. The default is to write a 30. fps raw codec max quality file with a timescale
codec [symbol] of 600.
quality [symbol]
timescale [int] The following list of codecs is deprecated (retained for reference). See codeclist for
the preferred method to list valid system codecs. The available codec types are raw,
cinepak, graphics, animation, video, componentvideo, jpeg, mjpega, mjpegb, sgi,
planarrgb, macpaint, gif, photocd, qdgx, avrjpeg, opendmljpeg, bmp, winraw,
vector, qd, h261, h263, dvntsc, dvpal, dvprontsc, dvpropal, flc, targa, png, tiff,
componentvideosigned, componentvideounsigned, cmyk, microsoft, sorenson,
indeo4, argb64, rgb48, alphagrey32, grey16, mpegyuv420, yuv420, sorensonyuv9
and mpeg4.

The available codec quality settings are lossless, max, min, low, normal, or high.
Note that minimum quality is, in many cases, the codec's default quality. Use
"low" quality for consistent results.

Attributes
Name Type g/s Description
codeclist symbol (get) The valid video codecs available on the system
Sending the message getcodeclist will cause a list of all valid codecs (that is, those
with a functioning compressor component) to be reported from the dumpout. This
list is guaranteed to contain only working codecs, and should be used in preference
to the old, static codec list.
colormode symbol The input matrix's color encoding (default = argb)
argb = ARGB (alpha, red, green, blue) colormode
uyvy = UYVY (YUV 4:2:2 packed) colormode
datarate int The maximum data rate of compressed video written to disk (default = codec-
dependent)
Note that not all codecs support data rate control (for instance, Photo-JPEG does
not).
dstrect int The portion of the output matrix written to by the input frame (default = 0 0
(matrix width) (matrix height)).
The proportions of the rectangle are expressed in the form left top right bottom .
All values are relative to the top left corner of the object's viewing area.
flatten int Flatten flag (default = 0)
When the flag is set, recorded files are flattened. Additional optional arguments
are available, and may appear in any order after the flag:
compress = compress the movie resource
faststart = places the movie resource before the data in the file
activeonly = flatten and copy active tracks only
frame int Frame number (default = -1 (disabled))
Typically, the jit.qt.record object passes input matrices directly to the outlet
without any processing. Setting frame to a number greater than or equal to zero
(0) during recording permits viewing of the compressed, previously recorded
frame specified by the frame attribute's value, while the object continues to record
new frames.
hint int Hint flag (default = 0)
When the flag is set, recorded files are saved as hinted movies.
interp int Interpolation flag (default = 0)
When the flag is set, the incoming matrix is interpolated when scaling to display.
kframe int Keyframe rate (default = 50)
If set, the jit.qt.record object will attempt to configure the compressor to use the
specified keyframe rate, when data is written to disk. Keyframes (temporal
compression) are not available to all codecs.
planemap int The plane mapping from input matrix to output movie (default = 0 1 2 3)
preview int Preview flag (default = 0 (off))
Typically, the jit.qt.record object passes input matrices directly to the outlet
without any processing. Enabling preview during recording permits viewing of the
compressed frames as they are recorded.
realtime int Realtime recording mode flag (default = 0 (off))
srcrect int The portion of the input matrix used when copying an input matrix to the internal
matrix. (default = 0 0 (matrix width) (matrix height)) The proportions of the
rectangle are expressed in the form left top right bottom . All values are relative to
the top left corner of the viewing area of the input matrix.
time int (get) The current duration, in QuickTime time units, of media written to disk (default =
operation-specific)
The time attribute only returns data during write operations.
usedstrect int Destination rect flag (default = 0)
When the flag is set, the dstrect attributes are used when copying an input matrix
to the internal matrix.
usesrcrect int Source rect flag (default = 0)
When the flag is set, the srcrect attributes are used when copying an input matrix
to the internal matrix.

Information for box attributes common to all objects

Examples
See Also
Name Description
jit.qt.effect QuickTime Effects for Jitter matrices
jit.qt.grab Digitize video from an external source
jit.qt.movie Play or edit a QuickTime movie
jit.qt.videoout Output video to QuickTime video output component
jit.vcr Record a QuickTime movie with MSP audio
Tutorial 19: Recording QuickTime Tutorial 19: Recording QuickTime movies
movies
Tutorial 21: Working With Live Tutorial 21: Working With Live Video and Audio Input
Video and Audio Input
jit.qt.videoout
Output video to QuickTime video output component

Description
jit.qt.videoout takes a matrix as input, compresses the data and sends it directly to a video output component (VOC).

Matrix Operator
matrix inputs:1, matrix outputs:1
Name IOProc Planelink Typelink Dimlink Plane Dim Type
out n/a 1 1 1 1 1 char long float32 float64

Information for Jitter Matrix Operator (MOP) messages and attributes to this object

Messages
close Closes the connection to an open video output component. The connection is
automatically closed when the object is freed.
getvoclist Sends a list of the available video output components out the object's right outlet.
getvocmodes Sends a list of the available video output component modes out the object's right
outlet. (e.g. the FireWire DV VOC offers NTSC and PAL modes)
open Opens a component connection for video output. You must open the connection
before the jit.qt.videoout object does anything.

Attributes
Name Type g/s Description
codecquality int Codec quality (default = 2 (normal))
0 = minimum
1 = low
2 = normal
3 = high
4 = maximum
5 = lossless

Note that minimum quality is, in many cases, the codec's default quality. Use
"low" quality for consistent results.
colormode symbol Sets the color mode (argb or uyvy).
voc int The currently selected video output component (default = 0)
vocmode int The current video output component (VOC) mode (default = component
dependent)

Information for box attributes common to all objects

Examples
See Also
Name Description
jit.qt.effect QuickTime Effects for Jitter matrices
jit.qt.grab Digitize video from an external source
jit.qt.movie Play or edit a QuickTime movie
jit.qt.record Record a QuickTime movie
Tutorial 22: Working With Video Tutorial 22: Working With Video Output Components
Output Components
jit.quat
Quaternion multiplication

Description
jit.quat will perform quaternion multiplication, with optional normalization of the input quaternions. In relation to 3D
transforms, quaternion multiplication is the concatenation of two orientations.

Messages
bang Perform the multiplication and output the resulting quaternion.
list x [float] In left inlet: A four element list of floating point numbers sets the first operand
y [float] and triggers the multiplication and output.
z [float]
w [float] In right inlet: A four element list of floating point numbers sets the second
operand.

Attributes
Name Type g/s Description
inverse float (get) The output quaternion's opposite rotation.
normalize int Determines whether or not the input quaternions are normalized before the
multiplication. (default = 0)
quat1 float Sets the first operand (default = 0 0 0 1)
quat2 float Sets the second operand (default = 0 0 0 1)
quatout float (get) The resulting quaternion after the multiplication
xaxis float the output quaternion's rotation matrix X axis.
yaxis float the output quaternion's rotation matrix Y axis.
zaxis float the output quaternion's rotation matrix Z axis.

Information for box attributes common to all objects

Examples

See Also
Name Description
jit.quat2axis Quaternion to angle-axis conversion
jit.axis2quat Convert angle-axis to quaternion
jit.quat2euler Quaternion to Euler conversion
jit.euler2quat Convert Euler angles to quaternion
jit.anim.node Perform hierarchical transformation
jit.quat2axis
Quaternion to angle-axis conversion

Description
Convert a quaternion (a four-dimensional vector) to an angle-axis representation.

Messages
bang Output the resulting angle-axis values.
list x [float] A four element list of floating point numbers interpreted as a quaternion, is
y [float] converted to angle-axis values and output.
z [float]
w [float]

Attributes
Name Type g/s Description
angleaxis float (get) The resulting angle-axis values after the conversion, in the form of angle (in
degrees) and an axis.
normalize int Normalize the quaternion before outputting (default = 0).
quat float The quaternion to be converted. (default = 0 0 0 1)

Information for box attributes common to all objects

Examples

See Also
Name Description
jit.quat Quaternion multiplication
jit.axis2quat Convert angle-axis to quaternion
jit.quat2euler Quaternion to Euler conversion
jit.euler2quat Convert Euler angles to quaternion
jit.anim.node Perform hierarchical transformation
jit.quat2euler
Quaternion to Euler conversion

Description
Convert a quaternion (a four-dimensional vector) to Euler X/Y/Z angles.

Messages
bang Output the resulting Euler angles.
list x [float] A four element list of floating point numbers interpreted as a quaternion, is
y [float] converted to Euler angles and output.
z [float]
w [float]

Attributes
Name Type g/s Description
euler float (get) The resulting Euler angles after the conversion.
normalize int Normalize the quaternion before outputting (default = 0).
quat float The quaternion to be converted. (default = 0 0 0 1)

Information for box attributes common to all objects

Examples

See Also
Name Description
jit.quat Quaternion multiplication
jit.euler2quat Convert Euler angles to quaternion
jit.axis2quat Convert angle-axis to quaternion
jit.quat2axis Quaternion to angle-axis conversion
jit.anim.node Perform hierarchical transformation
jit.release~
Transforms matrix data into signals

Description
jit.release~ takes floating-point jitter matrices as input and transforms the stream of jitter matrices into MSP signals.

Arguments
Name Units Type Opt Description
channels The number of output signals. An outlet will be created for each channel and the
input matrices should be composed of a separate plane for each channel.

Attributes
Name Type g/s Description
mode int Two different modes are possible: in mode 0, jit.release~ does no intepolation and
expects to receive one sample of input for every sample it needs to output. In
mode 1 the playback position within the internal buffer is smoothly adjusted based
on how much data has been made available to the object.
latency float The amount of signal data, in milliseconds, that the object should internally buffer
before starting playback. Low latency values will be more susceptible to clicking
due to temporal perturbations in the event-based jitter network.

Information for box attributes common to all objects

Examples

See Also
Name Description
jit.buffer~ Access an MSP buffer~ in matrix form
jit.peek~ Read matrix data as an audio signal
jit.poke~ Write an audio signal into a matrix
jit.catch~ Transform signal data into matrices
peek~ Read and write sample values
poke~ Write sample values to a buffer by index
Tutorial 48: Frames of MSP Tutorial 48: Frames of MSP signals
signals
jit.repos
Reposition spatially

Description
jit.repos performs cell positioning on an input matrix received in its left inlet using the input from a second input matrix received
in its right Inlet as a spatial map.

Matrix Operator
matrix inputs:2, matrix outputs:1
Name IOProc Planelink Typelink Dimlink Plane Dim Type
in2 resamp 0 0 1 2 1 long char
out n/a 1 1 1 1 1 char long float32 float64

Information for Jitter Matrix Operator (MOP) messages and attributes to this object

Attributes
Name Type g/s Description
boundmode int Boundary mode for values outside the range (0, width) (0, height) (default = 3
(clip))
0 = ignore: Values that exceed the limits are ignored.
1 = clear: Values that exceed the limits are set to 0.
2 = wrap: Values that exceed the limits are wrapped around to the opposite limit
with a modulo operation.
3 = clip: Values are limited not to exceed width or height.
4 = fold: Values that exceed the limits are folded back in the opposite direction
interpbits int The number of bits considered as fraction for spatial mapping values (default = 0)
mode int Offset mode flag (default = 0 (absolute offsets))
0 = spatial map values specified as absolute offsets
1 = spatial map specified as relative offsets
offset_x int The offset added to the x values in the spatial map matrix (default = 0)
offset_y int The offset added to the y values in the spatial map matrix (default = 0)

Information for box attributes common to all objects

Examples
See Also
Name Description
jit.mxform2d Spatial transform using 3x3 matrix
jit.plume Displace points based on luminance
jit.rota Scale/rotate in 2D
Tutorial 39: Spatial Mapping Tutorial 39: Spatial Mapping
jit.resamp
Resample spatially

Description
jit.resamp spatially resamples the input matrix. This can be used to scale (zoom in/out) and offset (move) an image horizontally,
vertically, or in both directions.

Matrix Operator
matrix inputs:1, matrix outputs:1
Name IOProc Planelink Typelink Dimlink Plane Dim Type
out n/a 1 1 1 4 1 char

Information for Jitter Matrix Operator (MOP) messages and attributes to this object

Attributes
Name Type g/s Description
interp_x int X value interpolation flag (default = 0) When the flag is set, values are
interpolated across the x (horizontal) dimension values.
interp_y int Y value interpolation flag (default = 0) When the flag is set, values are
interpolated across the y (vertical) dimension values.
wrap int Value wrap flag (default = 0) When the flag is set, values that exceed the limits are
wrapped around to the opposite limit with a modulo operation. (1.1 wraps to .1, 1.2
wraps to .2, and -1.1 wraps to .9, -1.2 wraps to .8, etc.)
xscale float The scaling factor for the x (horizontal) dimension (default = 1.)
xshift float The shift (offset) amount for x (horizontal) dimension values (default = 0.).
Positive values shift right, negative values shift left.
yscale float The scaling factor for the y (vertical) dimension (default = 1.)
yshift float The shift (offset) amount for the y (vertical) dimension values (default = 0.)
Positive values shift down, negative values shift up.

Information for box attributes common to all objects

Examples
See Also
Name Description
jit.matrix The Jitter Matrix!
jit.mxform2d Spatial transform using 3x3 matrix
jit.rota Scale/rotate in 2D
jit.reverse
Reverse output with respect to input

Description
jit.reverse reverses the sequential order of data coming in its inlets, relative to its outlets; a jit.reverse object with 5 inlets will
pass input sent to the left inlet to its rightmost outlet, pass inlet 2 data to outlet 4, and so on.

Arguments
None.

Messages
bang Any bang is passed to the corresponding outlet.
int Any integer value is passed to the corresponding outlet.
float Any floating point value is passed to the corresponding outlet.
list Any list is passed to the corresponding outlet.
anything Any input is passed to the corresponding outlet.
clear inlet-list [list] The clear message with no arguments initializes all inlets. Optional arguments
specify by number the inlets to initialize. Inlet numbering starts from 0.

When initialized, no output will occur for the inlet's corresponding outlet until
new input is received in that inlet.

Attributes
Name Type g/s Description
reverse int Reverse mapping flag (default = 1) When the flag is set, reverse mapping is
enabled. Otherwise, mapping passes inlet 1 to outlet 1, inlet 2 to outlet 2, etc.
immediate int Processing mode (default = 0 (left inlet only))
0 = output triggered by input to the left inlet only.
1 = input to any inlet is sent out the outlet associated with it immediately.

Information for box attributes common to all objects

Examples

See Also
Name Description
jit.cycle Cycle messages through outputs
swap Swap position of two numbers
jit.rgb2hsl
Convert HSL to RGB

Description
jit.hsl2rgb converts a 4 plane matrix of ARGB (alpha, red, green, blue) data to AHSL (alpha, hue, saturation, lightness) data. An
offset and a scaling factor can be applied to the hue, saturation, and lightness data individually.

Matrix Operator
matrix inputs:1, matrix outputs:1
Name IOProc Planelink Typelink Dimlink Plane Dim Type
out n/a 1 1 1 4 1 char float32 float64

Information for Jitter Matrix Operator (MOP) messages and attributes to this object

Attributes
Name Type g/s Description
hoffset float The hue offset (default = 0.)
hscale float The hue scaling (default = 1.) Hue scaling values above 1. wrap to 0.
loffset float The lightness offset (default = 0.)
lscale float The lightness scale (default = 1.) Lightness scaling values above 1. clip to 1.
soffset float The saturation offset (default = 0.)
sscale float The saturation scale (default = 1.) Saturation scaling values above 1. clip to 1.

Information for box attributes common to all objects

Examples
See Also
Name Description
jit.colorspace Convert between colorspaces
jit.hue Rotate hue
jit.hsl2rgb Convert HSL to RGB
jit.rgb2luma Converts RGB to monochrome (luminance)
jit.traffic Multiply the planar vector by a matrix
jit.rgb2luma
Converts RGB to monochrome (luminance)

Description
jit.rgb2luma converts a 4-plane char ARGB (alpha, red, green, blue) matrix into a 1-plane char monochrome matrix containing
the luminosity of the original matrix using the equation L = (.299 * R value) + (.587 * G value) + (.114 * B value).

Matrix Operator
matrix inputs:1, matrix outputs:1
Name IOProc Planelink Typelink Dimlink Plane Dim Type
out n/a 0 1 1 1 1 char

Information for Jitter Matrix Operator (MOP) messages and attributes to this object

Attributes
Name Type g/s Description
ascale float The alpha scaling factor (default = 0.)
bscale float The blue scaling factor (default = 0.114)
gscale float The green scaling factor (default = 0.587)
rscale float The red scaling factor (default = 0.299)

Information for box attributes common to all objects

Examples

See Also
Name Description
jit.colorspace Convert between colorspaces
jit.hue Rotate hue
jit.hsl2rgb Convert HSL to RGB
jit.rgb2hsl Convert HSL to RGB
jit.traffic Multiply the planar vector by a matrix
Tutorial 29: Using the Alpha Tutorial 29: Using the Alpha Channel
Channel
jit.robcross
Robert's Cross edge detection

Description
jit.robcross implements the Robert's Cross method of edge detection.

Matrix Operator
matrix inputs:1, matrix outputs:1
Name IOProc Planelink Typelink Dimlink Plane Dim Type
out n/a 1 1 1 1 1 char long float32 float64

Information for Jitter Matrix Operator (MOP) messages and attributes to this object

Attributes
Name Type g/s Description
thresh float Edge detection threshold (default 0.). Cell values below this threshold are set to 0.

Information for box attributes common to all objects

Examples

See Also
Name Description
jit.brass Emboss image
jit.qt.effect QuickTime Effects for Jitter matrices
jit.sobel Sobel and Prewitt gradient edge detector
Tutorial 45: Introduction to using Tutorial 45: Introduction to using Jitter within JavaScript
Jitter within JavaScript
jit.rota
Scale/rotate in 2D

Description
Use the jit.rota object for quick 2-dimemsional scaling and rotation of matrices.

Matrix Operator
matrix inputs:1, matrix outputs:1
Name IOProc Planelink Typelink Dimlink Plane Dim Type
out n/a 1 1 1 1 1 char long float32 float64

Information for Jitter Matrix Operator (MOP) messages and attributes to this object

Attributes
Name Type g/s Description
anchor_x int The horizontal anchor point for rotation (default = 0) The anchor point is
horizontally offset in pixels from the upper left corner of the display.
anchor_y int The vertical anchor point for rotation (default = 0) The anchor point is vertically
offset in pixels from the upper left corner of the display.
boundmode int Boundary handling mode (default = 0 (ignore))
0 = ignore: Values that exceed the limits are ignored.
1 = clear: Values that exceed the limits are set to 0.
2 = wrap: Values that exceed the limits are wrapped around to the opposite limit
with a modulo operation. (256 wraps to 0, 257 wraps to 1, and -1 wraps to 255, -2
wraps to 254, etc.)
3 = clip: Values are limited not to exceed min or max. (e.g. numbers greater than
255 are set to 255, and numbers less than 0 are set to 0.)
4 = fold: Values that exceed the limits are folded back in the opposite direction.
(256 is folded back to 254, 257 is folded back to 253, and -1 is folded back to 1, -2 to
2, etc.)
cosoffset_x float Horizontal cosine offset (default = 0.)
cosoffset_y float Vertical cosine offset (default = 0.)
cosscale_x float Horizontal cosine scale (default = 0.)
cosscale_y float Vertical cosine scale (default = 0.)
interp int Interpolation flag (default = 0) When the flag is set, the incoming matrix is
interpolated when scaling to display.
offset_x int The horizontal offset (default = 0) The horizontal offset is specified in pixels from
the upper left corner of the display.
offset_y int The vertical offset (default = 0) The vertical offset is specified in pixels from the
upper left corner of the display.
sinoffset_x float Horizontal sine offset (default = 0.)
sinoffset_y float Vertical sine offset (default = 0.)
sinscale_x float Horizontal sine scale (default = 0.)
sinscale_y float Vertical sine scale (default = 0.)
theta float The rotation angle in radians (default = 0.)
thetaoffsetcos_x float theta-dependent horizontal cosine offset (default = 0.)
thetaoffsetcos_y float theta-dependent vertical cosine offset (default = 0.)
thetaoffsetsin_x float theta-dependent horizontal sine offset (default = 0.)
thetaoffsetsin_y float theta-dependent vertical sine offset (default = 0.)
thetascalecos_x float theta-dependent horizontal cosine scale (default = 0.)
thetascalecos_y float theta-dependent vertical cosine scale (default = 0.)
thetascalesin_x float theta-dependent horizontal sine scale (default = 0.)
thetascalesin_y float theta-dependent vertical sine scale (default = 0.)
zoom_x float The horizontal image scaling (default = 1.)
zoom_y float The vertical image scaling (default = 1.)

Information for box attributes common to all objects

Examples

See Also
Name Description
jit.mxform2d Spatial transform using 3x3 matrix
jit.repos Reposition spatially
jit.resamp Resample spatially
Tutorial 15: Image Rotation Tutorial 15: Image Rotation
jit.roy
Convert image to halftone image

Description
jit.roy is a halftone screen emulator. It takes an input matrix and splits it into a grid. Each element in the grid is then replaced by
regions of a second matrix based on the mean value of each slot in the grid.

Matrix Operator
matrix inputs:2, matrix outputs:1
Name IOProc Planelink Typelink Dimlink Plane Dim Type
in2 adapt 0 0 0 1 1 char long float32 float64
out n/a 1 1 1 1 1 char long float32 float64

Information for Jitter Matrix Operator (MOP) messages and attributes to this object

Attributes
Name Type g/s Description
shades int The number of shades present in the halftone matrix (i.e. the number of regions to
split the matrix into as individual halftone images) (default = 11)
x int The width of each halftone screen (default = 8)
y int The height of each halftone screen (default = 8)

Information for box attributes common to all objects

Examples

See Also
Name Description
jit.eclipse Create images from images
jit.hatch Perform crosshatch filtering
jit.rubix
Reorder grid of rectangles

Description
jit.rubix segments a matrix into a grid of rectangular cells whose cells can be reordered, flipped both horizontally and vertically,
frozen, and filled with a single color value derived from a cell in the grid area (monochromatic).

Matrix Operator
matrix inputs:1, matrix outputs:1
Name IOProc Planelink Typelink Dimlink Plane Dim Type
out n/a 1 1 1 4 1 char

Information for Jitter Matrix Operator (MOP) messages and attributes to this object

Messages
colrot column [int] Rotates the column specified by column the number of cells specified by rotate-
number-of-cells [int] cells .
freeze column [int] Toggles the freeze flag for the cell specified by column row . If set, the cell's
row [int] contents will be frozen.
0/1 [int]
hflip column [int] Toggles the horizontal flip flag for the cell specified by column row . If set, the
row [int] cell's contents will be flipped horizontally.
0/1 [int]
mono column [int] Toggles the mono flag for the cell specified by column row . If set, the cell's
row [int] contents will be all the same value as the upper left most value in cell.
0/1 [int]
nomono column [int] Toggles the nomono flag for the cell specified by column row . If set, the cell's
row [int] contents will not be monochromatic even if probmono has a non-zero value.
0/1 [int]
reset Places all cells in their original position and orientation.
rowrot row [int] Rotates the row specified by row the number of cells specified by number-of-cells .
number-of-cells [int]
setcell output-column [int] Maps the input cell specified by input-column input-row to the output cell
output-row [int] specified by output-column and output-row .
input-column [int]
input-row [int]
vflip column [int] Toggles the vertical flip flag for the cell specified by column row . If set, the cell's
row [int] contents will be flipped vertically.
0/1 [int]

Attributes
Name Type g/s Description
cols int The number of columns (default = 1)
dots int Dot render flag (default = 0) When the flag is set, dot rendering is used.
prob float The probability that a rectangular section will update with new data (default = 1.)
probmono float The probability that a rectangular section will be monochromatic (default = 0.)
rows int The number of rows (default = 1)

Information for box attributes common to all objects

Examples
See Also
Name Description
jit.glue Glue many matrices into one
jit.resamp Resample spatially
jit.scissors Cut up a matrix into evenly spaced sub matrices
jit.tiffany Arbitrary rectangular resampling
jit.scalebias
Multiply and add

Description
jit.scalebias scales the values of a 4-plane input matrix of typechar (ARGB) and adds to an offset value (bias).

Matrix Operator
matrix inputs:1, matrix outputs:1
Name IOProc Planelink Typelink Dimlink Plane Dim Type
out n/a 1 1 1 4 1 char

Information for Jitter Matrix Operator (MOP) messages and attributes to this object

Attributes
Name Type g/s Description
abias float The alpha bias (offset) value (default = 0.)
ascale float The alpha scale value (default = 1.)
bbias float The blue bias (offset) value (default = 0.)
bias float (set) The bias (offset) value for all colors if channel summing is set using the mode 1
message (default = 0.)
bscale float The blue scale value (default = 1.)
gbias float The green bias (offset) value (default = 0.)
gscale float The green scale value (default = 1.)
mode int Channel summing mode (default = 0 (normal))
0 = normal
1 = sum all the channels together
rbias float The red bias (offset) value (default = 0.)
rscale float The red scale value (default = 1.)
scale float (set) The all scale value if channel summing is set using the mode 1 message (default =
0.)

Information for box attributes common to all objects

Examples
See Also
Name Description
jit.charmap Map 256-point input to output
jit.map Map input range to output range
jit.op Apply binary or unary operators
jit.rgb2luma Converts RGB to monochrome (luminance)
Tutorial 6: Adjust Color Levels Tutorial 6: Adjust Color Levels
Tutorial 9: More Mixing Tutorial 9: More Mixing
jit.scanoffset
Uses a 1-dimensional matrix to offset scanlines

Description
jit.scanoffset uses a 1-dimensional slice of one matrix as a map for the offset and scale of the scanlines of another matrix.

Matrix Operator
matrix inputs:2, matrix outputs:1
Name IOProc Planelink Typelink Dimlink Plane Dim Type
in2 adapt 0 0 0 1 1 float32
out n/a 1 1 1 1 1 char long float32 float64

Information for Jitter Matrix Operator (MOP) messages and attributes to this object

Attributes
Name Type g/s Description
displacement_map int The scanline, dimension, and plane of the matrix (in2_matrix) used as the
offset/scale map (default = 0 0 0)
interp int Interpolation flag (default = 0) When the flag is set, the incoming matrix is
interpolated when scaling to display.
mode int The axis of the in1_matrix along which to apply the offset. (default = 0
(horizontal))
0 = apply offset along the horizontal axis
1 = apply offset along the vertical axis
offset float The offset amount. (default = 0.)
scale float The scale amount. (default = 0.)

Information for box attributes common to all objects

Examples

See Also
Name Description
jit.repos Reposition spatially
jit.scanwrap Resample by scanline wrapping
jit.scanslide
Cellwise spatial envelope follower

Description
Use the jit.scanslide object to perform cellwise spatial envelope following across dimension 0 or 1.

Matrix Operator
matrix inputs:1, matrix outputs:1
Name IOProc Planelink Typelink Dimlink Plane Dim Type
out n/a 1 1 1 1 1 char long float32 float64

Information for Jitter Matrix Operator (MOP) messages and attributes to this object

Attributes
Name Type g/s Description
dimmode int The dimension across which the envelope following is performed (default = 0)
0 = horizontal
1 = vertical
mode int Filter mode (default = 0 (filter cells with greater than offset))
0 = filter cells with a position greater than the value of the offset attribute.
1 = filter cells with a position less than the value of the offset attribute.
2 = filter cells with a position both greater than and less than the value of the
offset attribute.
offset int The position offset along the dimension specified by the dimmode attribute.
(default = 0)
slide_down float The slide down factor (default = 1). Note that down does not refer not to change
along the y axis, but rather with respect to amplitude (e.g. brightness of color
channel for image data).
slide_up float The slide up factor (default = 1). Note that up does not refer not to change along
the y axis, but rather with respect to amplitude (e.g. brightness of color channel
for image data).

Information for box attributes common to all objects

Examples
See Also
Name Description
jit.op Apply binary or unary operators
jit.slide Cellwise temporal envelope follower
slide Smooth values logarithmically
slide~ Filter a signal logarithmically
jit.scanwrap
Resample by scanline wrapping

Description
The jit.scanwrap object rewraps an input matrix into an output matrix. Matrix output handling is specified by a mode attribute.

Matrix Operator
matrix inputs:1, matrix outputs:1
Name IOProc Planelink Typelink Dimlink Plane Dim Type
out n/a 1 1 1 1 1 char long float32 float64

Information for Jitter Matrix Operator (MOP) messages and attributes to this object

Messages
purge Sends the output matrix, regardless of its fill state (Note: In fill mode, the output
matrix is generally unavailable until it is full). If a matrix is purged, the message
purge 1 is sent out of the jit.scanwrap object's right outlet. If there is no matrix
to purge, the message purge 0 is sent. purge does not reset the object like the
reset message).
reset Sets the input/output scan back to the beginning and clears the output matrix.
(Note: In fill mode, the reset message will start filling the output matrix from the
top, abandoning any partial fill data that had already accumulated.)

Attributes
Name Type g/s Description
mode int Output mode (default = 0 (fill))
0 = fill: The object will not output a matrix until it has received enough data to fill
it. If the input matrix overflows the output, the excess data is truncated.
1 = dump: The object will output one matrix regardless of the amount of data
received. If the output matrix is not filled, the remaining cells are set to 0. If the
input matrix overflows the output, the excess data is truncated.
2 = spew: The object will output as many matrices as required to void itself of all
data. If the output matrix is not filled, it waits until it has received enough data
before it is output. If the input matrix overflows the output, the excess data is sent
to new matrices, which will be output as soon as they are filled.
3 = wrap: If the input underflows the output matrix, it is 'looped' until it fills it up.
Excess data is truncated.

Information for box attributes common to all objects

Examples
See Also
Name Description
jit.scanoffset Uses a 1-dimensional matrix to offset scanlines
jit.scissors
Cut up a matrix into evenly spaced sub matrices

Description
jit.scissors takes a single matrix and cuts it into uniform rectangular regions, outputting each one out a separate outlet as a new
matrix.

Matrix Operator
matrix inputs:1, matrix outputs:-1
Name IOProc Planelink Typelink Dimlink Plane Dim Type

Information for Jitter Matrix Operator (MOP) messages and attributes to this object

Messages
anything The jit.scissors object cuts a 2-dim matrix into a specified number of rows and
columns and outputs those regions as smaller matrices.

Attributes
Name Type g/s Description
columns int The number of columns to split the input matrix into (default = 1)
If you specify the columns attribute in the object box, The number of outlets will
be equal to the number of rows multiplied by the number of columns. If you
change the rows * columns attributes later, the size of the split regions will
change, but the number of inlets will not change.
rows int The number of rows to split the input matrix into (default = 1)
If you specify the columns attribute in the object box, The number of outlets will
be equal to the number of rows multiplied by the number of columns. If you
change the rows * columns attributes later, the size of the split regions will
change, but the number of inlets will not change.

Information for box attributes common to all objects

Examples
See Also
Name Description
jit.concat Concatenate two matrices
jit.demultiplex Demultiplex (deinterleave) one matrix into two
jit.glue Glue many matrices into one
jit.matrix The Jitter Matrix!
jit.multiplex Multiplex (interleave) two matrices into one matrix
jit.split Split a matrix into two matrices
Tutorial 13: Scissors and Glue Tutorial 13: Scissors and Glue
jit.scope
Visual matrix analysis tools

Description
jit.scope lets you visually inspecting matrix values and display them as waveform, vectorscope, histogram or parade visual data.

Arguments
None.

Messages
bang Outputs the current matrix.
jit_matrix window-size [list] Displays the input matrix by scaling to the window size.
(mouse) Clicking with the mouse will display a horizontal or vertical line trace and
numerical cursor.

Attributes
Name Type g/s Description
accum int Sets the amount of data, per pixel, to accumulate for display.
def.:25
accum_desat float When the jit.scope object is set to parade mode, this attribute sets the
def.:0.35 desaturation for the display (expressed as a float in the range 0. 1.0).
border float Window border flag (default = 1) When the flag is set, the window is displayed
def.:0. with a border.
colormode symbol Sets the color mode. The options are:
def.:argb
argb (the default)
uyvy
dstrect int Specifies the portion of the output matrix written to by the input frame (default =
0 0 (matrix width) (matrix height)) The proportions of the rectangle are expressed
in the form left top right bottom . All values are relative to the top left corner of
the object's viewing area.
graphcolor float Sets the Graph Color in RGBA format.
def.:0.8 0.3 0. 1.
graphmode symbol When the jit.scope object is set to histogram mode, this attribute sets the data to
def.:luminance be displayed. The options are:

luminance: displays a luminance (monochrome) display of histogram values


rgb: displays an overlaid set of histograms for R, G, and B values.
hgraphcolor float Sets the Graph Color displayed on hover in RGBA format.
def.:0.8 0.8 0. 1.
hpopupbackgcolor float Sets the Popup Highlight Background Color in RGBA format.
def.:0.2 0.2 0.2 1.
hpopupcolor float Sets the Popup Highlight Text Color in RGBA format.
def.:1. 1. 1. 1.
interp int Interpolation flag (default = 0) When the flag is set, the incoming matrix is
def.:0 interpolated when scaling to display.
mode symbol Sets the display mode of the jit.scope object. The modes are:
def.:waveform
waveform: signal values (y) plotted over time (x)
vectorscope: an x-y plot of two signals
histogram: a plot of the disbribution of values for an input signal
parade: a scrolling display of R, G, and B values shown on a single screen
planemap int Sets input plane to output plane mapping (default = 0 1 2 3 ...)
popupbackgcolor float Sets the Popup Background Color in RGBA format.
def.:0. 0. 0. 1.
popupcolor float Sets the Popup Text Color in RGBA format.
def.:0.9 0.9 0.9 1.
size int Sets the window size (width and height) (default = 320 240)
srcrect int Specifies Specifies the portion of the input matrix used when copying an input
matrix to the internal matrix. (default = 0 0 (matrix width) (matrix height)) The
proportions of the rectangle are expressed in the form left top right bottom . All
values are relative to the top left corner of the viewing area of the input matrix.

Information for box attributes common to all objects

Examples

See Also
Name Description
jit.dx.grab Digitize video using DirectX (Windows)
jit.histogram Calculate matrix histogram
jit.qt.grab Digitize video from an external source
jit.qt.movie Play or edit a QuickTime movie
jit.shade
Map-based crossfader

Description
jit.shade performs a linear crossfade between corresponding cells in two input matrices at a rate determined by the values of the
cells of a third "map" matrix. The crossfade rate is calculated in frames rather than units of time.

Matrix Operator
matrix inputs:3, matrix outputs:1
Name IOProc Planelink Typelink Dimlink Plane Dim Type
in2 resamp 1 1 1 1 1 char long float32 float64
in3 adapt 0 0 1 2 1 long
out n/a 1 1 1 1 1 char long float32 float64

Information for Jitter Matrix Operator (MOP) messages and attributes to this object

Messages
reset Zeroes the fade counter, causing the fade to start over from the beginning. The
fade counter is actually managed in the second plane of matrix 3. If initialization
values were provided in that plane, they are lost after a reset message is received.

Attributes
Name Type g/s Description
max int Maximum rate (default = 255)
min int Minimum rate (default = 0)
mode int Crossfade mode (default = 0 (start to end))
0 = start to end crossfade: Fades from start to end without looping and sends a
done message out the right outlet on completion.
1 = palindrome crossfade: Fades from start to end, then reverse direction.
2 = looped cellwise start to end crossfade: Once any cell has finished its fade, it
begins again.

Information for box attributes common to all objects

Examples
See Also
Name Description
jit.alphablend Blend two images with an alpha channel image
jit.op Apply binary or unary operators
jit.slide
Cellwise temporal envelope follower

Description
The jit.slide object performs cellwise temporal envelope following.`

Matrix Operator
matrix inputs:1, matrix outputs:1
Name IOProc Planelink Typelink Dimlink Plane Dim Type
out n/a 1 1 1 1 1 char long float32 float64

Information for Jitter Matrix Operator (MOP) messages and attributes to this object

Attributes
Name Type g/s Description
slide_down float The slide down factor (default = 1.) Note that down refers not to spatial change
along the y axis, but rather with respect to amplitude (e.g. brightness of color
channel for image data).
slide_up float The slide up factor (default = 1.) Note that up refers not to spatial change along the
y axis, but rather with respect to amplitude (e.g. brightness of color channel for
image data).

Information for box attributes common to all objects

Examples

See Also
Name Description
jit.scanslide Cellwise spatial envelope follower
slide Smooth values logarithmically
slide~ Filter a signal logarithmically
jit.sobel
Sobel and Prewitt gradient edge detector

Description
jit.sobel provides two different kinds of edge detection algorithms.

Matrix Operator
matrix inputs:1, matrix outputs:1
Name IOProc Planelink Typelink Dimlink Plane Dim Type
out n/a 1 1 1 1 1 char long float32 float64

Information for Jitter Matrix Operator (MOP) messages and attributes to this object

Attributes
Name Type g/s Description
mode int The detection mode. (default = 0 (Sobel))
0 = Sobel
1 = Prewitt
thresh float The threshold below which matrix values are set to 0. (default = 0.)

Information for box attributes common to all objects

Examples

See Also
Name Description
jit.brass Emboss image
jit.qt.effect QuickTime Effects for Jitter matrices
jit.robcross Robert's Cross edge detection
Tutorial 25: Tracking the Position Tutorial 25: Tracking the Position of a Color in a Movie
of a Color in a Movie
jit.spill
Unroll a matrix into a list

Description
jit.spill outputs matrix values as a Max list, starting from a specified offset. The object will only wrap around two dimensions.

Matrix Operator
matrix inputs:1, matrix outputs:0
Name IOProc Planelink Typelink Dimlink Plane Dim Type

Information for Jitter Matrix Operator (MOP) messages and attributes to this object

Attributes
Name Type g/s Description
listlength int The length of the output list (default = 128)
offset int The x and y offsets from the start of matrix (default = 0 0)
plane int The plane whose values will be reported (default = 0)

Information for box attributes common to all objects

Examples

See Also
Name Description
jit.fill Fill a matrix with a list
jit.iter Iterate a matrix as lists or values
jit.matrix The Jitter Matrix!
zl Process lists in many ways
Tutorial 11: Lists and Matrices Tutorial 11: Lists and Matrices
jit.split
Split a matrix into two matrices

Description
jit.split takes a single matrix, divides it along a specified dimension at a specified point, and outputs the two resulting matrices.

Matrix Operator
matrix inputs:1, matrix outputs:2
Name IOProc Planelink Typelink Dimlink Plane Dim Type
out n/a 0 0 0 1 1 char long float32 float64
out2 n/a 0 0 0 1 1 char long float32 float64

Information for Jitter Matrix Operator (MOP) messages and attributes to this object

Attributes
Name Type g/s Description
autoclear int Autoclear flag (default = 1) When the flag is set, the matrix is cleared following
output.
splitdim int The dimension across which splitting occurs. (default = 0)
splitpoint int The point along the dimension specified by the splitdim attribute where the split
occurs. (default = 1)

Information for box attributes common to all objects

Examples

See Also
Name Description
jit.concat Concatenate two matrices
jit.demultiplex Demultiplex (deinterleave) one matrix into two
jit.glue Glue many matrices into one
jit.matrix The Jitter Matrix!
jit.multiplex Multiplex (interleave) two matrices into one matrix
jit.scissors Cut up a matrix into evenly spaced sub matrices
jit.sprinkle
Introduce spatial noise

Description
jit.sprinkle probabilistically determines whether a matrix cell will be displaced by a random amount along the horizontal or
vertical axes to produce a "cloud" of data surrounding the original cell values.

Matrix Operator
matrix inputs:1, matrix outputs:1
Name IOProc Planelink Typelink Dimlink Plane Dim Type
out n/a 1 1 1 1 1 char long float32 float64

Information for Jitter Matrix Operator (MOP) messages and attributes to this object

Attributes
Name Type g/s Description
prob float The probability that any given cell will be displaced (default = 0.)
x_range int The displacement range along the horizontal axis (default = 0)
y_range int The displacement range along the vertical axis (default = 0)

Information for box attributes common to all objects

Examples

See Also
Name Description
jit.noise Generate white noise
jit.repos Reposition spatially
jit.streak Probability lines
jit.str.fromsymbol
Convert Max symbol to Jitter string matrix

Description
Use the jit.str.tosymbol object to convert Max symbols into string matrices.

Matrix Operator
matrix inputs:0, matrix outputs:1
Name IOProc Planelink Typelink Dimlink Plane Dim Type
out n/a 1 1 1 1 1 char

Information for Jitter Matrix Operator (MOP) messages and attributes to this object

Messages
int Any int sent to the jit.str.fromsymbol object is converted to a string matrix and
sent out the left outlet.
float Any float sent to the jit.str.fromsymbol object is converted to a string matrix and
sent out the left outlet.
list Any list sent to the jit.str.fromsymbol object is converted to a string matrix and
sent out the left outlet.
anything Any symbol input to the jit.str.fromsymbol object is converted to a string matrix
and sent out the left outlet.

Information for box attributes common to all objects

Examples

See Also
Name Description
jit.str.op Apply common string operations
jit.str.tosymbol Convert Jitter string matrix to Max symbol
jit.str.regexp Use PERL-compatible regular expressions on Jitter matrices
jit.textfile Read and write a matrix as an ASCII text file
Tutorial 20: Importing and Tutorial 20: Importing and Exporting Single Matrices
Exporting Single Matrices
jit.str.op
Apply common string operations

Description
Use the jit.str.op object to perform common string operations on string matrices.

Matrix Operator
matrix inputs:2, matrix outputs:1
Name IOProc Planelink Typelink Dimlink Plane Dim Type
in2 adapt 0 0 0 1 1 char
out n/a 1 1 1 1 1 char

Information for Jitter Matrix Operator (MOP) messages and attributes to this object

Attributes
Name Type g/s Description
end int The end of the slice when in slice mode (default = 0)
multiline_in int Enables the jit.str.op object to work with 2D matrices, with each row interpreted
as a CR-terminated string. If disabled, only the first row of an incoming 2D matrix
is used. (default = 1)
multiline_out int Causes the jit.str.op object to convert any CR to the start of a new row in a 2D
output matrix and output an 'expanded' 2D matrix. If disabled, a 'collapsed',
single-row matrix is output. (default = 0)
op symbol String operation mode (default = strcat) Available modes are:
strcat = Concatenate two strings
strrev = Reverse a string
slice = Output an arbitrary substring as a zero-terminated string
strcmp = Compare two strings lexicographically, returning the difference between
the two characters at the point that the strings become dissimilar, as well as the
index of that point
strlen = Report the length of a string
toupper = Convert to uppercase
tolower = Convert to lowercase
thru = Properly truncate (if necessary) and terminate string matrix
start int The start of the slice when in slice mode (default = 0)

Information for box attributes common to all objects

Examples

See Also
Name Description
jit.op Apply binary or unary operators
jit.str.fromsymbol Convert Max symbol to Jitter string matrix
jit.str.tosymbol Convert Jitter string matrix to Max symbol
jit.str.regexp Use PERL-compatible regular expressions on Jitter matrices
jit.textfile Read and write a matrix as an ASCII text file
jit.str.regexp
Use PERL-compatible regular expressions on Jitter matrices

Description
jit.str.regexp performs regular expression analysis to Jitter matrices with optional substitution.

Matrix Operator
matrix inputs:1, matrix outputs:4
Name IOProc Planelink Typelink Dimlink Plane Dim Type
out n/a 1 1 1 1 1 char
out2 n/a 1 1 1 1 1 char
out3 n/a 1 1 1 1 1 char
out4 n/a 1 1 1 1 1 char

Information for Jitter Matrix Operator (MOP) messages and attributes to this object

Attributes
Name Type g/s Description
descriptor int Output descriptor matrix flag (default = 0)
re symbol The PERL-compatible regular expression to be used by jit.str.regexp for analysis
of the incoming matrix.
substitute symbol A substitution string.

Information for box attributes common to all objects

Examples

See Also
Name Description
jit.op Apply binary or unary operators
jit.str.fromsymbol Convert Max symbol to Jitter string matrix
jit.str.tosymbol Convert Jitter string matrix to Max symbol
jit.textfile Read and write a matrix as an ASCII text file
regexp Use regular expressions to process input
jit.str.tosymbol
Convert Jitter string matrix to Max symbol

Description
Use the jit.str.tosymbol object to convert a string matrix into a Max symbol.

Matrix Operator
matrix inputs:1, matrix outputs:0
Name IOProc Planelink Typelink Dimlink Plane Dim Type

Information for Jitter Matrix Operator (MOP) messages and attributes to this object

Attributes
Name Type g/s Description

Information for box attributes common to all objects

Examples

See Also
Name Description
jit.str.fromsymbol Convert Max symbol to Jitter string matrix
jit.str.op Apply common string operations
jit.str.regexp Use PERL-compatible regular expressions on Jitter matrices
jit.textfile Read and write a matrix as an ASCII text file
tosymbol Convert messages, numbers, or lists to a single symbol
Tutorial 20: Importing and Tutorial 20: Importing and Exporting Single Matrices
Exporting Single Matrices
jit.streak
Probability lines

Description
The jit.streak object uses a specified probability to determine the chance that a given matrix cell's value will be extended to
subsequent cells (with an optional scaling factor). The result is a streaky good time.

Matrix Operator
matrix inputs:1, matrix outputs:1
Name IOProc Planelink Typelink Dimlink Plane Dim Type
out n/a 1 1 1 1 1 char long float32 float64

Information for Jitter Matrix Operator (MOP) messages and attributes to this object

Attributes
Name Type g/s Description
direction int Streaking direction (default = 0 (left))
0 = left
1 = down
2 = right
3 = up
mode int Scanline wrapping mode (default = 0 (wrap))
0 = streaking wraps from scanline to scanline
1 = streaking begins anew at each scanline
prob float The probability that any given cell will be extended (streaked) (default = 0.)
scale float The scaling factor applied to extended (streaked) cells (default = 0.75)

Information for box attributes common to all objects

Examples

See Also
Name Description
jit.noise Generate white noise
jit.repos Reposition spatially
jit.sprinkle Introduce spatial noise
Tutorial 18: Iterative Processes Tutorial 18: Iterative Processes and Matrix Re-Sampling
and Matrix Re-Sampling
jit.submatrix
Reference a sub-region of a matrix

Description
Use the jit.submatrix object when you want to reference a sub region of an input matrix without copying data.

Matrix Operator
matrix inputs:1, matrix outputs:1
Name IOProc Planelink Typelink Dimlink Plane Dim Type
out n/a 0 0 0 1 1 char long float32 float64

Information for Jitter Matrix Operator (MOP) messages and attributes to this object

Attributes
Name Type g/s Description
offset int Dimension offset into input matrix (default = 0 for all dimensions)

Information for box attributes common to all objects

Examples

See Also
Name Description
jit.coerce Coerce a matrix into different types/planecount
jit.matrix The Jitter Matrix!
jit.scissors Cut up a matrix into evenly spaced sub matrices
jit.textfile
Read and write a matrix as an ASCII text file

Description
The jit.textfile object maintains a text buffer, into which a text file or char matrix can be imported. The buffer can also be edited
directly by double-clicking on the object to open an editor window. A bang to the object causes the text buffer to be sent out the
left outlet as a matrix.

Matrix Operator
matrix inputs:1, matrix outputs:2
Name IOProc Planelink Typelink Dimlink Plane Dim Type
out n/a 1 1 1 1 1 char
out2 n/a 1 1 1 1 1 char

Information for Jitter Matrix Operator (MOP) messages and attributes to this object

Messages
(mouse) Double-clicking on the object opens a text editor window with the current
contents of the text buffer.
erase Clear the object's text buffer.
line line-number [int] Sends the line specified by the argument out the middle outlet of the object as a
string matrix (1 dimensional char matrix, 0 terminated) that can be used by the
jit.str. set of objects. Line numbering starts at 1.
open Opens the text editor window. Sending this message is equivalent to double-
clicking on the object.
outputline Sends the matrix out the middle outlet. This is equivalent to the outputmatrix
message, but uses to the middle outlet rather than the left outlet. (For this object,
the outputmatrix message refers only to the left outlet).
read filename [symbol] Reads a text file from disk if a filename is specified. Otherwise, an file dialog box
will appear so that a text file can be specified.
wclose Closes the editor window, if open.
write filename [symbol] Writes the object's text buffer to a disk file. The optional argument specifies a file
name.

Attributes
Name Type g/s Description
defaultdir symbol The default directory for writing files (default = default path)
title symbol Sets the title for the text editor window
convert int Convert line breaks flag (default = 1) When the flag is set, UNIX/DOS line breaks
are converted to Macintosh format when reading a file from disk.
autoclear int Matrix clear following output flag (default = 1)

Information for box attributes common to all objects

Examples
See Also
Name Description
jit.fprint Read/write a matrix as a text file
jit.matrix The Jitter Matrix!
text Format messages as a text file
Tutorial 20: Importing and Tutorial 20: Importing and Exporting Single Matrices
Exporting Single Matrices
jit.thin
Remove redundant dimensions of size 1

Description
The jit.thin object removes redundant dimensions of size 1.

Matrix Operator
matrix inputs:1, matrix outputs:1
Name IOProc Planelink Typelink Dimlink Plane Dim Type
out n/a 0 0 0 1 1 char long float32 float64

Information for Jitter Matrix Operator (MOP) messages and attributes to this object

Information for box attributes common to all objects

Examples

See Also
Name Description
jit.concat Concatenate two matrices
jit.dimmap Remap and/or invert matrix dimensions
jit.matrix The Jitter Matrix!
jit.split Split a matrix into two matrices
jit.tiffany
Arbitrary rectangular resampling

Description
The jit.tiffany object performs an arbitrary rectangular resampling of a matrix.

Matrix Operator
matrix inputs:1, matrix outputs:1
Name IOProc Planelink Typelink Dimlink Plane Dim Type
out n/a 1 1 1 1 1 char long float32 float64

Information for Jitter Matrix Operator (MOP) messages and attributes to this object

Messages
x facet-width [float] Generates new values for the widths of all facets. New values can be specified by
... [literal] an optional float or list of floats, which represent percentages of the jit.tiffany
object's display area, or they will be randomly generated within the ranges limited
by the xrange attribute.
y facet-height [float] Generates new values for the height of all facets. New values can be specified by an
... [literal] optional float or list of floats, which represent percentages of the jit.tiffany
object's display area, or they will be randomly generated within the ranges limited
by the yrange attribute.
xy group (optional) Generates new values for the heights and widths of all facets. New values can be
facet-size [float] specified by an optional float or list of floats, which represent percentages of the
end group jit.tiffany object's display area, or they will be randomly generated within the
... [literal] ranges limited by the xrange and yrange attributes.

Attributes
Name Type g/s Description
bgcolor float The background color (default = 0. 0. 0. 0.)
grid int Grid border flag (default = 1) When the flag is set, a border is drawn for each facet
in the grid.
xrange float The upward limit for width of a facet as a percentage of the total matrix size
(default = 0.2)
xskip int The number of columns to 'skip' when rendering an output matrix (default = 0)
yrange float The upward limit for height of a facet as a percentage of the total matrix size
(default = 0.2)
yskip int The number of rows to 'skip' when rendering an output matrix (default = 0)

Information for box attributes common to all objects

Examples
See Also
Name Description
jit.resamp Resample spatially
jit.rubix Reorder grid of rectangles
jit.traffic
Multiply the planar vector by a matrix

Description
The jit.traffic object takes an input matrix and multiplies its cells using an N x N+1 float32 matrix (where N is the planecount of
the input matrix). The left input matrix can be of any type.

Matrix Operator
matrix inputs:2, matrix outputs:1
Name IOProc Planelink Typelink Dimlink Plane Dim Type
in2 adapt 0 0 0 1 1 char long float32 float64
out n/a 1 1 1 1 1 char long float32 float64

Information for Jitter Matrix Operator (MOP) messages and attributes to this object

Information for box attributes common to all objects

Examples

See Also
Name Description
jit.colorspace Convert between colorspaces
jit.hsl2rgb Convert HSL to RGB
jit.rgb2luma Converts RGB to monochrome (luminance)
jit.rgb2hsl Convert HSL to RGB
jit.transpose
Calculate the transpose of a matrix

Description
Use the jit.transpose object to calculate the transpose of a matrix: rows become columns, and vice versa.

Matrix Operator
matrix inputs:1, matrix outputs:1
Name IOProc Planelink Typelink Dimlink Plane Dim Type
out n/a 1 1 1 1 1 char long float32 float64

Information for Jitter Matrix Operator (MOP) messages and attributes to this object

Information for box attributes common to all objects

Examples

See Also
Name Description
jit.dimmap Remap and/or invert matrix dimensions
jit.matrix The Jitter Matrix!
jit.rota Scale/rotate in 2D
jit.turtle
2-d turtle graphics interpreter

Description
The jit.turtle object emulates simple LOGO-style graphics. It interprets single char values in its inlet as ASCII letters that describe
turtle graphics commands. A valid ASCII input will generate appropriate drawing commands for use with either the Max lcd
object or the jit.lcd object.

Arguments
None.

Messages
int ASCII character commands for the turtle
Valid numbers are 35 ( # ), 33 (! ), 70 ( F ), 102 ( f ), 91 ( [ ), 93 ( ] ), 43 ( + ), 45 (-
), and 124 ( | ).
reset Resets the turtle to the position specified by the origin attribute. If the clearmode
attribute is set, the clear message will be sent out the right outlet.

Attributes
Name Type g/s Description
origin int The point in Cartesian coordinates for the turtle to begin drawing from after a
reset (default = 80 120)
angle int The number of degrees in each turn the turtle makes (default = 30)
scale int The size of a step (in pixels) that the turtle takes with each forward movement
(default = 10)
clearmode int Clear on reset flag (default = 1) When the flag is set, a clear message is sent in
response to a reset command.

Information for box attributes common to all objects

Examples

See Also
Name Description
jit.lcd QuickDraw wrapper
jit.linden Lindenmayer string expansion (L-systems)
jit.uldl
Internet upload/download

Description
The jit.uldl object provides asynchronous file upload and download. Download is possible from http:// , https:// , ftp:// , and
file:/// URLs. Upload is only possible to ftp:// URLs.

Matrix Operator
matrix inputs:0, matrix outputs:1
Name IOProc Planelink Typelink Dimlink Plane Dim Type
out n/a 1 1 1 1 1 char

Information for Jitter Matrix Operator (MOP) messages and attributes to this object

Messages
abort Aborts a download or upload operation in progress.
download URL [symbol] Begins a download operation from the URL specified in the argument. Any data is
downloaded to the default path or the directory specified by the defaultdir
attribute. If no argument is given, download begins from the URL specified by the
url_dl attribute. If the argument matrix is given, data will be downloaded to a
Jitter matrix, and output via the jit.uldl object's left (matrix) outlet.
upload local-file [symbol] Begins an upload operation from the local file specified by the first argument, to
URL [symbol] the URL specified in the second argument. If no second argument is given, upload
is to the URL specified by the url_ul attribute.

Attributes
Name Type g/s Description
report int The upload/download status report flag (default = 0)
When the flag is set, periodic status data is sent out the right outlet during data
transfer operations.
url_ul symbol The upload URL (default = [none])
urlul symbol The upload URL (default = [none])
url_dl symbol The download URL (default = [none])
urldl symbol The download URL (default = [none])
username symbol The username, if needed for upload and download (default = [none])
password symbol The password, if required
defaultdir symbol The default download directory (default = default path)
convert int When the flag is set (the default), the jit.uldl object will convert the line breaks in
downloaded data (DOS or Unix-style) to Macintosh-style line breaks.
percent int Upload/download percent report flag (default = 0)
When the flag is set, the periodic indications of a download operation's progress
(as a floating point number between 0 and 1) are reported from the right outlet.
dir_list int List remote directories flag (FTP-only, default = 0)
When the flag is set, the jit.uldl object will attempt to list the contents of a remote
directory, if the URL specifies one. This feature is only available for FTP URLs.

WINDOWS USERS: This functionality is not currently available.


dirlist int List remote directories flag (FTP-only, default = 0)
Duplicates the functionality of the dir_list attribute.
passive int When the flag is set (the default) FTP connections will be made using passive
mode.
Information for box attributes common to all objects

Examples

See Also
Name Description
jit.qt.movie Play or edit a QuickTime movie
jit.textfile Read and write a matrix as an ASCII text file
jit.unpack
Make multiple single plane matrices out of a multiplane matrix

Description
The jit.unpack object splits one N-plane matrix into N single-plane matrices. This is useful for splitting one ARGB matrix into
separate alpha, red, green, and blue matrices, and similar types of splitting.

Matrix Operator
matrix inputs:1, matrix outputs:-1
Name IOProc Planelink Typelink Dimlink Plane Dim Type

Information for Jitter Matrix Operator (MOP) messages and attributes to this object

Arguments
Name Units Type Opt Description
planecount int The number of planes in the input matrix and the number of single plane matrix
outlets for the jit.unpack object (default = 4).

Messages
anything TEXT_HERE

Attributes
Name Type g/s Description
jump int Number of planes to grab from input matrix (default = all ones)
offset int Offset into input matrix (default = 0 1 2 ... 31)

Information for box attributes common to all objects

Examples

See Also
Name Description
jit.coerce Coerce a matrix into different types/planecount
jit.concat Concatenate two matrices
jit.pack Make a multiplane matrix out of single plane matrices
jit.split Split a matrix into two matrices
Tutorial 5: ARGB Color Tutorial 5: ARGB Color
jit.uyvy2argb
Converts UYVY to ARGB

Description
The jit.uyvy2argb object converts a 4-plane char UYVY (signed chroma blue, luminance left, signed chroma red, luminance right)
matrix into a 4-plane char ARGB (alpha, red, green, blue) matrix.

Matrix Operator
matrix inputs:1, matrix outputs:1
Name IOProc Planelink Typelink Dimlink Plane Dim Type
out n/a 1 1 0 3 1 char

Information for Jitter Matrix Operator (MOP) messages and attributes to this object

Attributes
Name Type g/s Description
noalpha int Disable alpha channel flag. If this flag is set, a three-plane RGB matrix will be
output instead of a four-plane ARGB matrix.

Information for box attributes common to all objects

Examples

See Also
Name Description
jit.argb2uyvy Convert ARGB to UYVY
jit.colorspace Convert between colorspaces
jit.traffic Multiply the planar vector by a matrix
jit.uyvy2ayuv Converts UYVY to AYUV
jit.uyvy2luma Converts UYVY to monochrome (luminance)
jit.uyvy2ayuv
Converts UYVY to AYUV

Description
The jit.uyvy2ayuv object converts a 4-plane char UYVY (signed chroma blue, luminance left, signed chroma red, luminance right)
matrix into a 4-plane char AYUV (alpha, luminance, signed chroma blue, signed chroma red) matrix.

Matrix Operator
matrix inputs:1, matrix outputs:1
Name IOProc Planelink Typelink Dimlink Plane Dim Type
out n/a 1 1 0 3 1 char

Information for Jitter Matrix Operator (MOP) messages and attributes to this object

Attributes
Name Type g/s Description
noalpha int Disable alpha channel flag. If this flag is set, a three-plane YUV matrix will be
output instead of a four-plane AYUV matrix.

Information for box attributes common to all objects

Examples

See Also
Name Description
jit.ayuv2uyvy Convert AYUV to UYVY
jit.colorspace Convert between colorspaces
jit.traffic Multiply the planar vector by a matrix
jit.uyvy2argb Converts UYVY to ARGB
jit.uyvy2luma Converts UYVY to monochrome (luminance)
jit.uyvy2luma
Converts UYVY to monochrome (luminance)

Description
The jit.uyvy2luma object converts a 4-plane char UYVY (signed chroma blue, luminance left, signed chroma red, luminance
right) matrix into a 1-plane char monochrome (luma) matrix.

Matrix Operator
matrix inputs:1, matrix outputs:1
Name IOProc Planelink Typelink Dimlink Plane Dim Type
out n/a 0 1 0 1 1 char

Information for Jitter Matrix Operator (MOP) messages and attributes to this object

Information for box attributes common to all objects

Examples

See Also
Name Description
jit.colorspace Convert between colorspaces
jit.luma2uyvy Converts monochrome (luminance) to UYVY
jit.traffic Multiply the planar vector by a matrix
jit.uyvy2ayuv Converts UYVY to AYUV
jit.uyvy2argb Converts UYVY to ARGB
jit.vcr
Record a QuickTime movie with MSP audio

Description
Use the jit.vcr object combine a sequence of Jitter matrices and MSP audio and save the sequence to disk as a synchronized
QuickTime movie. The two left inlets accept MSP audio signals (if only 1 inlet is used, the movie's audio will be monophonic). The
right inlet accepts a Jitter matrix.

Matrix Operator
matrix inputs:1, matrix outputs:1
Name IOProc Planelink Typelink Dimlink Plane Dim Type
out n/a 1 1 1 1 1 char long float32 float64

Information for Jitter Matrix Operator (MOP) messages and attributes to this object

Messages
signal The jit.vcr records incoming MSP signals as audio in its output file.
stop Stop recording.
write movie-name [symbol] Writes the sequence of incoming Jitter matrices to a disk file as a QuickTime
FPS [float] movie. The default is to write a 30. fps raw codec max quality file with a timescale
codec [symbol] of 600.
quality [symbol]
timescale [int] The following list of codecs is deprecated (retained for reference). See codeclist for
the preferred method to list valid system codecs. The available codec types are raw,
cinepak, graphics, animation, video, componentvideo, jpeg, mjpega, mjpegb, sgi,
planarrgb, macpaint, gif, photocd, qdgx, avrjpeg, opendmljpeg, bmp, winraw,
vector, qd, h261, h263, dvntsc, dvpal, dvprontsc, dvpropal, flc, targa, png, tiff,
componentvideosigned, componentvideounsigned, cmyk, microsoft, sorenson,
indeo4, argb64, rgb48, alphagrey32, grey16, mpegyuv420, yuv420, sorensonyuv9
and mpeg4.

The available codec quality settings are lossless, max, min, low, normal, or high.
Note that minimum quality is, in many cases, the codec's default quality. Use
"low" quality for consistent results.

Attributes
Name Type g/s Description
codeclist symbol (get) Sending the message getcodeclist will cause a list of all valid codecs (that is, those
with a functioning compressor component) to be reported from the dumpout. This
list is guaranteed to contain only working codecs, and should be used in preference
to the old, static codec list.
colormode symbol The input matrix's color encoding (default = argb)
argb = ARGB (alpha, red, green, blue) colormode
uyvy = UYVY (YUV 4:2:2 packed) colormode
datarate int The maximum data rate of compressed video written to disk (default = codec-
dependent). Note that not all codecs support data rate control (for instance,
Photo-JPEG does not).
dstrect int The portion of the output matrix written to by the input frame (default = 0 0
(matrix width) (matrix height)).
The proportions of the rectangle are expressed in the form left top right bottom .
All values are relative to the top left corner of the object's viewing area.
flatten int Flatten flag (default = 0)
When the flag is set, recorded files are flattened. Additional optional arguments
are available, and may appear in any order after the flag:
compress = compress the movie resource
faststart = places the movie resource before the data in the file
activeonly = flatten and copy active tracks only
frame int Frame number (default = -1 (disabled))
Typically, the jit.vcr object passes input matrices directly to the outlet without any
processing. Setting frame to a number greater than or equal to zero (0) during
recording permits viewing of the compressed, previously recorded frame specified
by the frame attribute's value, while the object continues to record new frames.
hint int Hint flag (default = 0)
When the flag is set, recorded files are saved as hinted movies.
interp int Interpolation flag (default = 0)
When the flag is set, the incoming matrix is interpolated when scaling to display.
kframe int Keyframe rate (default = 50)
If set, the jit.vcr object will attempt to configure the compressor to use the
specified keyframe rate, when data is written to disk. Keyframes (temporal
compression) are not available to all codecs.
planemap int The plane mapping from input matrix to output movie (default = 0 1 2 3)
preview int Preview flag (default = 0 (off))
Typically, the jit.vcr object passes input matrices directly to the outlet without any
processing. Enabling preview during recording permits viewing of the compressed
frames as they are recorded.
srcrect int The portion of the input matrix used when copying an input matrix to the internal
matrix. (default = 0 0 (matrix width) (matrix height)) The proportions of the
rectangle are expressed in the form left top right bottom . All values are relative to
the top left corner of the viewing area of the input matrix.
time int (get) The current duration, in QuickTime time units, of media written to disk (default =
operation-specific)
The time attribute only returns data during write operations.
usedstrect int Destination rect flag (default = 0)
When the flag is set, the dstrect attributes are used when copying an input matrix
to the internal matrix.
usesrcrect int Source rect flag (default = 0)
When the flag is set, the srcrect attributes are used when copying an input matrix
to the internal matrix.

Information for box attributes common to all objects

Examples

See Also
Name Description
jit.qt.effect QuickTime Effects for Jitter matrices
jit.qt.grab Digitize video from an external source
jit.qt.movie Play or edit a QuickTime movie
jit.qt.record Record a QuickTime movie
jit.qt.videoout Output video to QuickTime video output component
jit.wake
Feedback with convolution stage

Description
Use the jit.wake object to perform video feedback with a convolution stage.

Matrix Operator
matrix inputs:1, matrix outputs:1
Name IOProc Planelink Typelink Dimlink Plane Dim Type
out n/a 1 1 1 4 1 char

Information for Jitter Matrix Operator (MOP) messages and attributes to this object

Attributes
Name Type g/s Description
bdownbleed float The lower convolution kernel value for the blue plane (default = 0.)
bfb float The feedback level for blue plane values (default = 0.)
bff float The feed forward level for blue plane values (default = 1.)
bgain float The gain level for blue plane values (default = 1.)
bleed float (set) The all upper, lower, left, and right convolution kernel values
bleftbleed float The blue left convolution kernel value (default = 0.)
brightbleed float The blue right convolution kernel value (default = 0.)
bupbleed float The blue upper convolution kernel value (default = 0.)
fb float (set) The feedback level for all plane values (default = 0.)
ff float (set) The feed forward level for all plane values (default = 1.)
gain float (set) The gain level for all colors (default = 1.)
gdownbleed float The lower convolution kernel value for the green plane (default = 0.)
gfb float The feedback level for green plane values (default = 0.)
gff float The feed forward level for green plane values (default = 1.)
ggain float The gain level for green plane values (default = 1.)
gleftbleed float The left convolution kernel value for the green plane (default = 0.)
grightbleed float The right convolution kernel value for the green plane (default = 0.)
gupbleed float The upper convolution kernel value for the green plane (default = 0.)
normalize int Normalization flag (default = 0)
rdownbleed float The lower convolution kernel value for the red plane (default = 0.)
rfb float The feedback level for red plane values (default = 0.)
rff float The feed forward level for red plane values (default = 1.)
rgain float The gain level for red plane values (default = 1.)
rleftbleed float The left convolution kernel value for the red plane (default = 0.)
rrightbleed float The right convolution kernel value for the red plane (default = 0.)
rupbleed float The upper convolution kernel value for the red plane (default = 0.)

Information for box attributes common to all objects

Examples
See Also
Name Description
jit.convolve Convolve two matrices
jit.glop Produce feedback with gain staging
jit.op Apply binary or unary operators
Tutorial 45: Introduction to using Tutorial 45: Introduction to using Jitter within JavaScript
Jitter within JavaScript
jit.window
Display data in a window

Description
Use the jit.window object to draw pixels or graphics to a window. jit.window displays jit.matrix data as well as OpenGL 3D
graphics.

Messages
(mouse) Double-click to bring the jit.window to front
front Bring the window to front
sendtexture name [symbol] Send a message to the internal texture
message [symbol]
values [list]

Attributes
Name Type g/s Description
border int Show window border
clamp int Clamp matrix values
colormode symbol Matrix color mode
'argb' = Use ARGB color
'uyvy' = Use UYVY color
depthbuffer int Enable depth buffer
doublebuffer int Enable back buffer
dstrect int TEXT_HERE
floating int Enable floating window style
fsaa int Enable full scene anti-aliasing
fsmenubar int Enable menubar in fullscreen
fullscreen int Enable fullscreen
grow int Enable the mouse grow region for the window. When the flag is set, the window
can be resized by clicking and dragging in the lower right-hand corner.
idlemouse int Enable mouse idle events
interp int Enable matrix interpolation
mousewheel int TEXT_HERE
name symbol The name of the window. Jitter OpenGL objects attach to a rendering context
through the window's name.
noaccel int Disable OpenGL hardware acceleration
pickray int Enable output of picking ray
planemap int TEXT_HERE
pos int Window position is specified in pixels by an x and y offset value in global
coordinates from the upper left corner of the screen.
rect int The window rectangle is specified in pixels giving the left, top, right, and bottom
coordinates of the window from the upper left corner.
shared int TEXT_HERE
size int Window size
srcrect int TEXT_HERE
stereo int Enable stereo buffers
sync int The vertical sync flag sets the window to update synchronous to the monitor's
refresh.
title symbol The window title. If not title is set, the title of the window will be set to the name
of the window.
usedstrect int TEXT_HERE
usesrcrect int TEXT_HERE
visible int Enable window visibility

Information for box attributes common to all objects

Examples

See Also
Name Description
jit.gl.render Render Jitter OpenGL objects
jit.pwindow Show data in a patcher
Tutorial 1: Playing a QuickTime Tutorial 1: Playing a QuickTime Movie
Movie
Tutorial 31: Rendering Tutorial 31: Rendering Destinations
Destinations
Tutorial 38: Basic Performance Tutorial 38: Basic Performance Setup
Setup
Tutorial 47: Using Jitter Object Tutorial 47: Using Jitter Object Callbacks in JavaScript
Callbacks in JavaScript
Tutorial 49: Colorspaces Tutorial 49: Colorspaces
jit.xfade
Crossfade between 2 matrices

Description
Use the jit.xfade object to crossfade between two matrices. A crossfade value of 0. results in output values equivalent to the left
input values, while a crossfade value of 1.0 results in output values equivalent to the right input matrix.

Matrix Operator
matrix inputs:2, matrix outputs:1
Name IOProc Planelink Typelink Dimlink Plane Dim Type
in2 resamp 1 1 1 1 1 char long float32 float64
out n/a 1 1 1 1 1 char long float32 float64

Information for Jitter Matrix Operator (MOP) messages and attributes to this object

Attributes
Name Type g/s Description
xfade float The crossfade amount. A crossfade value of 0. (the default) results in output values
equivalent to the left input values, while a crossfade value of 1.0 results in output
values equivalent to the right input matrix.

Information for box attributes common to all objects

Examples

See Also
Name Description
jit.alphablend Blend two images with an alpha channel image
jit.op Apply binary or unary operators
Tutorial 8: Simple Mixing Tutorial 8: Simple Mixing
spigot~
Route QT audio into MSP

Description
Use the spigot~ object when you want to grab audio output from a jit.qt.movie object. The spigot~ object works with a sound
file which exported and cached from a movie loaded in the jit.qt.movie object and played in sync with the it.

Arguments
Name Units Type Opt Description
symbol Name of the spigot~ instance

Messages
signal For internal use only.

Information for box attributes common to all objects

Usage Information
Jitter Object Methods: Although the spigot~ object itself doesn't have any useful methods, there are a number of Jitter library
messages which can be used to control and get information about this caching process. All of these methods are sent using the
standard "; jitter (message) (args)" form in a message box.

Messages
spigot_cache Set the cache location. Cached audio will be saved:
0 = next to the original movie
1 = in the user-domain common folder (default)
2 = in the system-domain common folder
3 = in the user's temporary items folder
(symbol) = in the folder specified by the symbol

On Macintosh, the user-domain common folder is "~/Library/Application


Support/Cycling '74/spigot-cache/". On Windows, this folder is "C:\Documents
and Settings\(username)\Local Settings\Application Data\Cycling '74\spigot-
cache\"

On Macintosh and Windows, the system-domain common folder is "(Cycling '74


support folder)/spigot-cache/".

The temporary items folder is typically invisible and inaccessible to normal users
on both systems.

spigot_getcache Get the cache location. The cache location is sent to any receive object with the
same name as the receiver argument, and is reported as a fully-qualified path.
spigot_locatecache Open the cache location in your OS's file browser.
spigot_purgecache Delete the contents of the cache, to the limit specified by spigot_cachesize. This
method is called automatically every time jit.qt.movie opens a cached audio file,
or every time the cache size is set with the spigot_cachesize method.
spigot_cachesize Set the maximum size of the audio cache in megabytes. A cache size less than 0
indicates that the cache should have no maximum size (default).
spigot_getcachesize Get the cache site. The cache size is sent to any receive object with the same
name as the receiver argument.

Examples
See Also
Name Description
jit.qt.movie Play or edit a QuickTime movie
Tutorial 27: Using MSP Audio in a Tutorial 27: Using MSP Audio in a Jitter Matrix
Jitter Matrix
Max for Live Reference
chucker~
Segment audio and reorder it on looped playback

Description
chucker~ takes a specified amount of audio data, stores the data in an internal buffer, divides the buffered data into equal
sections, and allows the sections to be reordered on playback.

Arguments
Name Units Type Opt Description
buffer-size-in-ms int An optional integer argument can be used to set the number of milliseconds to
allocate for the recorded sound. (e.g. an argument of 8000 will allocate enough
memory for a stereo output of 8 seconds)
Note: The actual allocation will be larger than what is specified by the argument,
since the chucker~ object supports two buffers and provides for double-buffering.

Messages
directions direction-specifier [list] The word directions, followed by a 1 or 2 to indicate left or right channel and a list
of integer values whose length is equal to the number of steps, sets the direction of
playback for the sections. Playback direction is specified as follows:

1: forward (the default)


0: mute
-1: reverse
fademode mode [int] Sets the fade method for segment smoothing. Modes include:
0: Classic (same as Max 5)
1: Pre-fade (fades use buffered audio, fade executes prior to segment transition)
2: Post-fade (fades use buffered audio, fade executes after segment transition)
freeze buffer-segment [int] The message freeze 1 causes the current buffer segment to loop on playback.
Sending the message freeze 0 resumes normal playback.
nstep number-of-steps [int] The word nsteps, followed by an integer in the range 1 - 64, sets the number of
equal portions into which the chucker~ object's internal buffer is segmented for
playback.
signal In left inlet: Left channel audio input.
In middle inlet: Right channel audio input.
In right inlet: An audio signal in the range 0. - 1.0 provides the audio sync input.
This task is typically done using a phasor~ object's output as input.
smooth smooth-amount [float] The word smooth, followed by a floating point number in the range 0. - 1.0, sets
an amount of smoothing (crossfading) between the individual segments being
reordered for playback.
steps channel and range [list] The word steps, followed by a 1 or 2 to indicate left or right channel and a list of
integer values whose range is between 1 and the number of steps and whose length
is equal to the number of steps, sets the order of playback for the sections.
e.g. the message steps 1 4 3 2 1, steps 2 1 2 3 4, when sent to a chucker~
object whose number of steps is set to 4, will play the four left channel segments
in reverse order, and the right channel in regular order. order

Information for box attributes common to all objects

Examples
See Also
Name Description
buffer~ Store audio samples
groove~ Variable-rate looping sample playback
cverb~
A simple monaural reverberator

Description
cverb~ provides monaural reverberation for an input signal.

Arguments
Name Units Type Opt Description
reverb-time ms int Sets the reverb time in milliseconds.

Messages
float reverb-time [float] In right inlet: A floating point value in the right inlet is used to set the
reverberation time in milliseconds.
clear Clears the memory of the reverb (which may produce a click in the output).
signal In left inlet: Audio input to the reverberator.
In right inlet: A signal value may be used to set the reverberation time in
milliseconds.

Information for box attributes common to all objects

Examples

See Also
Name Description
tapin~ Input to a delay line
tapout~ Output from a delay line
allpass~ Apply an allpass filter effect
ddg.mono
Monophonic Synth Controller for Virtual Synths

Description
ddg.mono provides MIDI message handling for virtual monophonic synths in Max. It implements last/high/low note priority and
legato/retrigger phrasing.

Arguments
Name Units Type Opt Description
note priority int opt An optional integer argument in the range 0 - 2 can be used to specify note
priority. The mode settings are:

mode 0 (retrigger): Retrigger on each keypress (default).


mode 1 (legato): Retrigger on new note only.
mode 2 (laststep): Send a noteoff message on last note only.

Messages
int MIDI-note-value [int] In first inlet: The number is treated as a pitch value for a MIDI note-on message.
Output of the received number and its corresponding velocity value is dependent
on the mode attribute and the triggering modes (set using the legato or retrig
messages).

In second inlet: The number is stored as a velocity to be paired with pitch


numbers received in the left inlet.
(inlet1) MIDI-velocity-value [int] In right inlet: The number is stored as a velocity to be paired with pitch numbers
received in the left inlet.
clear The clear message will send a note-off message to stop any notes which are
currently playing.
laststep The laststep message will cause the ddg.mono object to send a note-off message
for the last note played.
legato The legato message will cause the ddg.mono object to send its output only when
a new note is played.
retrig The retrig message will cause the ddg.mono object to send its output on each key
press (i.e., retriggering previously played notes).

Attributes
Name Type g/s Description
legatomode int Sets the legato mode.
'Retrigger' = Retrigger mode
'Legato' = Legato mode
'Last Step' = TEXT_HERE
mode int Sets the note priority mode.
'Last Note' = TEXT_HERE
'High Note' = TEXT_HERE
'Low Note' = TEXT_HERE

Information for box attributes common to all objects

Examples
See Also
Name Description
kslider Output numbers from an onscreen keyboard
midiin Output raw MIDI data
midiparse Interpret raw MIDI data
notein Receive MIDI note messages
Max MIDI Tutorial 2: MIDI Note Max MIDI Tutorial 2: MIDI Note Management
Management
live.arrows
Vectorized arrow(s) user interface object

Description
live.arrows displays a variable number of directional arrow buttons.

Arguments
None.

Messages
int input [int] Sending an integer value to the live.arrows object will cause the displayed arrow
whose number corresponds to those arrow(w) currently displayed to flash and will
send a corresponding message out the live.arrows object's outlet. Index
numbering for arrows starts at 0 for the leftmost arrow. The indexing range will
vary depending on the number of arrows displayed (using the downarrow,
leftarrow, rightarrow, and uparrow attributes).
down When the down message is received, the down arrow will flash and the message
down will be sent to the live.arrows object's outlet if the downarrow attribute is
set to 1.
(mouse) Click to output the corresponding arrow symbol.
left When the left message is received, the left arrow will flash and the message left
will be sent to the live.arrows object's outlet if the leftarrow attribute is set to 1.
right When the right message is received, the right arrow will flash and the message
right will be sent to the live.arrows object's outlet if the rightarrow attribute is
set to 1.
up When the up message is received, the up arrow will flash and the message up will
be sent to the live.arrows object's outlet if the uparrow attribute is set to 1.

Attributes
Name Type g/s Description
arrowcolor float Sets the arrow color of the live.arrows object in RGBA format.
blinkcolor float Sets the blink color of the live.arrows object in RGBA format.
blinktime int Sets the blink time in milliseconds.
def.:150
bordercolor float Sets the border color of the live.arrows object in RGBA format.
downarrow int Toggles the display of the down arrow. The default is 1 (on).
def.:1
leftarrow int Toggles the display of the left arrow. The default is 1 (on).
def.:1
rightarrow int Toggles the display of the right arrow. The default is 1 (on).
def.:1
uparrow int Toggles the display of the up arrow. The default is 1 (on).
def.:1

Information for box attributes common to all objects

Output
symbol: When a left, up, down, or right arrow is clicked or selected using a message, a corresponding message (left, up, down
or right) is sent to the outlet

Examples
See Also
Name Description
live.button Flash on any message, send a bang
live.button
Flash on any message, send a bang

Description
live.button is used to trigger other messages and processes.

Arguments
None.

Messages
bang Performs the same function as anything.
int input [int] Performs the same function as anything.
float input [float] Performs the same function as anything.
anything input [list] When any message is received in the inlet, the button flashes briefly and a bang is
sent out the outlet.
assign assign-input [float] The word assign, followed by a floating point value, causes that value to be stored
and displayed and sent out the live.button object's outlet. If the Parameter
Visibility attribute is set to Stored Only, the assign message will not add the new
value to the Live applications undo chain.
(mouse) Clicking on the live.button object will cause it to flash briefly and send a bang
message out the outlet.

Attributes
Name Type g/s Description
active int Toggles the object's active mode. When active is set to 0, mouse action does not
def.:1 cause output and the inactive colors are used.
activebgcolor float When the active attribute is set to 1, this attribute sets the background color
displayed when the button is off in RGBA format.
activebgoncolor float When the active attribute is set to 1, this attribute sets the background color
displayed when the button is on in RGBA format.
bgcolor float When the active attribute is set to 0, this attribute sets the background color
displayed when the button is off in RGBA format.
bgoncolor float When the active attribute is set to 0, this attribute sets the background color
displayed when the button is on in RGBA format.
blinktime int Sets the blink time in milliseconds.
def.:100
bordercolor float Sets the border color of live.button object in RGBA format. Note that this color is
only used in the assignment mode within Live.
focusbordercolor float Sets the display color for the focused live.button object's border in RGBA format.
Note that this color is only used in assignment mode within Live.
transition int The parameter automation of live.button stores 0 and 1 values. The transition
def.:0 attribute specifies when a bang message will be sent to the outlet.
0 Zero->One: output a bang when the parameter value changes from 0. to 1.
1 One->Zero: output a bang when the parameter value changes from 1. to 0.
2 Both: output a bang when the parameter value changes from 0. to 1. and when
it changes from 1. to 0.
'Zero->One' = Output a bang on 0. to 1. transitions
'One->Zero' = Output a bang on 1. to 0. transitions
'Both' = Output a bang on 0. to 1. and 1. to 0. transitions

Information about attributes available for Parameter-aware objects


Information for box attributes common to all objects

Output
bang: A mouse click or any message in the inlet causes the live.button object to flash and send a bang message.

Examples

See Also
Name Description
button Blink and send a bang
trigger Send input to many places
Max Basic Tutorial 2: Bang! Max Basic Tutorial 2: Bang!
live.colors
Get the colors of the Live Skin

Description
Gets the color used in the current Live application color scheme (Skin).

Arguments
None.

Messages
active_automation Sends the active automation color out the outlet (in RGBA format).
assignment_text_bg Sends the assignment text bg color out the outlet (in RGBA format).
contrast_frame Sends the contrast frame color out the outlet (in RGBA format).
control_bg Sends the control bg color out the outlet (in RGBA format).
control_fg Sends the control fg color out the live.colors object's left outlet in RGBA format.
control_fg_off Sends the control fg off color out the live.colors object's left outlet in RGBA
format.
control_fg_on Sends the control fg on color out the live.colors object's left outlet in RGBA
format.
control_fg_zombie Sends the control fg zombie color out the live.colors object's left outlet in RGBA
format.
control_text_bg Sends the control text bg color out the live.colors object's left outlet in RGBA
format.
control_selection Sends the control selection color out the live.colors object's left outlet in RGBA
format.
control_zombie Sends the control zombie color out the live.colors object's left outlet in RGBA
format.
everything Sends all the available colors out the outlet as a series of messages. Each message
consists of the color scheme name followed by four floating-point values that
describe the color scheme color in RGBA format.
inactive_automation Sends the inactive automation color out the live.colors object's left outlet in
RGBA format.
key_assignment Sends the key assignment color out the live.colors object's left outlet in RGBA
format.
macro_assigned Sends the macro assigned color out the live.colors object's left outlet in RGBA
format.
macro_assignment Sends the macro assignment color out the live.colors object's left outlet in
RGBA format.
midi_assignment Sends the midi assignment color out the live.colors object's left outlet in RGBA
format.
led_bg Sends the led bg color out the live.colors object's left outlet in RGBA format.
numbox_triangle Sends the numbox triangle color out the live.colors object's left outlet in RGBA
format.
macro_title Sends the macro title color out the live.colors object's left outlet in RGBA format.
selection Sends the selection color out the live.colors object's left outlet in RGBA format.
surface_bg Sends the surface bg color out the live.colors object's left outlet in RGBA format.
value_arc Sends the value arc color out the live.colors object's left outlet in RGBA format.
value_bar Sends the value bar color out the live.colors object's left outlet in RGBA format.
value_arc_zombie Sends the value arc zombie color out the live.colors object's left outlet in RGBA
format.

Information for box attributes common to all objects

Output
bang: Out right outlet: A bang messages is sent out the right outlet if the Live colors are changed.
color: Out right outlet: The live.colors object sends a message composed of a color name followed by four floating point values
that specify the RBGA value of the color out the left outlet in response to a query.

Examples

See Also
Name Description
panel Colored background area
colorpicker Select and output a color
suckah Get a pixel from the display
live.dial
Output numbers by moving a dial onscreen

Description
live.dial works like a circular slider that outputs numbers according to its degree of rotation.

Arguments
None.

Messages
bang Sends the current value out the outlet.
int input [int] The number received in the inlet is stored and displayed by the live.dial object and
sent out the outlet.
float input [float] The number received in the inlet is stored and displayed in the live.dial and sent
out the outlet.
assign assign-input [float] The word assign, followed by a floating point value, causes that value to be stored
and displayed and sent out the live.dial object's outlet. If the Parameter Visibility
attribute is set to Stored Only, the assign message will not add the new value to
the Live applications undo chain.
init Restores and outputs the initial value.
(mouse) Click and drag in the dial to change the value. Hold down the Command key
(Macintosh) or the Control key (Windows) for more precise mouse control.
outputvalue Sends the current value out the outlet.
set set-input [float] Sets the current value without causing any output.

Attributes
Name Type g/s Description
active int Toggles the object's active mode. When the active attribute is set to 0, the mouse
def.:1 action does not cause output and the inactive colors are used.
activedialcolor float Sets the dial color in RGBA format to be used when the active attribute is set to 1.
activeneedlecolor float Sets the needle color in RGBA format to be used when the active attribute is set to
1.
appearance int The word appearance followed by a number, sets the display style for the
def.:0 live.dial object.
'Vertical' = Vertical dial display
'Tiny' = Tiny dial display
'Panel' = Panel dial display
bordercolor float Sets the display color for the live.dial object's border in RGBA format.
dialcolor float Sets the dial color in RGBA format displayed when the active attribute is set to 0.
focusbordercolor float Sets the display color for the focused live.dial object's border in RGBA format.
needlecolor float Sets the needle color in RGBA format. This is only used when the active attribute
is set to 0.
panelcolor float Sets the panel color in RGBA format. This is only used when the appearance
attribute is set to panel mode.
showname int Toggles the display of the parameter name. The default is 1 (displayed).
def.:1
shownumber int Toggles the display of the parameter value. The default is 1 (displayed).
def.:1
textcolor float Sets the display color for the live.dial object's text in RGBA format.
triangle int Toggles the display of a triangle in the dial display. When the triangle attribute is
def.:0 set to 1 and the triangle is displayed, clicking on it will restore the dial's initial
value.
tribordercolor float Sets the triangle border color in RGBA format.
tricolor float Sets the display color for the live.dial object's triangle in RGBA format.

Information about attributes available for Parameter-aware objects

Information for box attributes common to all objects

Output
float: Out right outlet: When an output is triggered, a raw normalized value (between 0. and 1.) is sent out this outlet.
int/float: Out left outlet: Numbers received in the object's inlet or produced by clicking or dragging on the live.dial object with
the mouse are sent out the outlet. The value sent is an integer if the Parameter Type is set to INT or ENUM.

Examples

See Also
Name Description
live.numbox Display and output a number
live.slider Output numbers by moving a slider onscreen
dial Output numbers using an onscreen dial
Max Basic Tutorial 7: Numerical Max Basic Tutorial 7: Numerical User Interfaces
User Interfaces
live.drop
Define a region for dragging and dropping a file

Description
The live.drop objects defines a region for dragging and dropping files and outputs the filepath when a file is dropped onto it.

Arguments
None.

Messages
bang Sends the current path out the outlet.
(drag) When a file is selected and dragged from the Live application's File Browser onto a
live.drop object in a Max for Live device, the full pathname of the file is sent out
the live.drop object's outlet.
The object will also provide the full pathname for a file when its icon is dragged
from the Max File Browser or your computer's Finder onto a live.drop object.
The live.drop object can be used with encrypted and encoded samples from Live's
File Browser. Encrypted samples will be decrypted, and a temporary filename will
be passed from the object's outlet, which can be used by objects in MaxMSP. Note
that this temporary file will become invalid 1 minute after the last object
(including live.drop) in MaxMSP has stopped using it.
Encoded samples (e.g. .mp3, .flac) are handled similarly, although they are not
automatically invalidated after use. Please see the decodemode attribute for more
information about encoded samples.
clear Clears the currently stored filepath.
(mouse) To drop a file, click on the name of an audio file or its icon in the Live
application's file browser, drag it onto the live.drop object's display area, and
release the mouse button.

When the mouse is positioned over the live.drop object, a round button will
appear in the lower right-hand portion of the object's display. The button indicates
the enabled or disabled state for dragging and dropping, and is enabled by default.
To toggle drag and drop behavior, click on the round button. The button's color
(set using the circlecolor and circleoncolor attributes found in the object
Inspector) changes to indicate its state.
set filepath-name [list] The word set, followed by a list that specifies a filepath, sets a filepath to be
reported by the the live.drop when it is initialized. The set message allows you to
store a filepath as reported by the object in the parameter and display and output
the path as if a file had been manually dropped on the object.

Attributes
Name Type g/s Description
bordercolor float Sets the display color for the live.drop object's border in RGBA format.
decodemode int When enabled (default), the live.drop object will attempt to decode non-PCM-
audio files dropped on it from Live's file browser (for instance, .mp3, .mp4, .m4v,
.mov, .flac, etc.). Decoded files will be cached to a temporary directory on the
computer's hard drive. In this case, the filename and path passed out of the
object's outlets will refer to the temporary decoded file, not to the original. This
feature is limited to file types which Live can decode.
You might wish to disable decodemode if you are using the live.drop object to
read, for instance, QuickTime Movie files for use in jit.qt.movie or if you
otherwise need the original file data, rather than extracted audio from the dragged
file.
focusbordercolor float Sets the color of the live.drop object's border when the object has focus in RGBA
format.
legend symbol Sets the text which appears in the display area of the live.drop object.
def.:Drop Something
Here!
textcolor float Sets the color for the text which appears in the display area of the live.drop object
in RGBA format.

Information about attributes available for Parameter-aware objects

Information for box attributes common to all objects

Output
symbol: Out left outlet: When a file from the Live application browser (or a file icon from the Max File Browser or your
computer's Finder) has been dragged onto the live.drop object and the mouse released within its box, the absolute pathname of
the file is sent out the left outlet as a single symbol (i.e. surrounded by double quotes).
Absolute pathnames look like this:

"C:/Max Folder/extras/mystuff/mypatch.pat"

If you want to use the live.drop object to cause a file to be read by another object that accepts the read message with a filename
argument, put a prepend read object between live.drop object and the object that will open a file.

Out right outlet: When a file from the Live application browser (or a file icon from the Max File Browser or your computer's
Finder) has been dragged onto the live.drop object and the mouse released within its box, the file type code of the file is sent out
the right outlet.

Examples

See Also
Name Description
dropfile Interface for file drag and drop
live.gain~
Decibel volume slider and monitor

Description
live.gain~ is a slider that scales input audio signals and provides a visual indication of the current sound level on a deciBel scale.

Arguments
None.

Messages
bang Sends the current value out the outlet.
int db-input [int] The number received in the inlet sets the level (in dB).
float db-input [float] The number received in the inlet sets the level (in dB).
assign assign-input [float] The word assign, followed by a floating point value, causes that value to be stored
and displayed and sent out the live.gain~ object's outlet. If the Parameter
Visibility attribute is set to Stored Only, the assign message will not add the new
value to the Live applications undo chain.
init Restore and output the initial value.
(mouse) Click and drag the slider to change the amplification. Hold down the Command
key (Macintosh) or the Control key (Windows) for more precise mouse control.
outputvalue Sends the current value out the outlet.
set set-slider-value [float] Sets the current value without causing output.
signal In left inlet: The input signal (left channel) to be scaled.

In right inlet: The input signal (right channel) to be scaled.


rawfloat input [float] A raw normalized value (between 0. and 1.) received in the inlet is converted to a
real value, stored, displayed by live.gain~ object, and the current value is sent out
the outlet.

Attributes
Name Type g/s Description
active int Toggles the object's active mode. When the active attribute is set to 0, mouse
def.:1 action does not cause output and the inactive colors are used.
channels int Channels
def.:2
clip_size int Sets the clipping zone size.
def.:0 'Normal' = Normal
'Extended' = Extended
coldcolor float Sets the Cold signal color in RGBA format.
display_range float Sets the range, in deciBels, displayed by the live.gain~ object. By default, the the
def.:-70. 6. display range is set to the same values as the range of the object itself (-70dB -
+6dB).
focusbordercolor float Sets the display color for the live.gain~ object's border in RGBA format.
hotcolor float Sets the Warning signal color in RGBA format.
inactivecoldcolor float Sets the Cold signal (inactive) color in RGBA format.
inactivewarmcolor float Sets the Warm signal (inactive) color in RGBA format.
interp float Sets the ramp time in milliseconds. The default is 10 milliseconds.
def.:10.
interval int Sets the update time interval of the meter display, in milliseconds. The minimum
def.:20 update interval is 10 milliseconds, the maximum is 2 seconds. This message also
sets the rate at which the live.gain~ object sends out the list of peak values (in dB)
for each channel received in that time interval.
metering int Specifies whether the live.gain~ object displays and outputs the signal level pre-
def.:1 fader (0) or post-fader (1).
'Pre Fader' = TEXT_HERE
'Post Fader' = TEXT_HERE
mode int The mode attribute allows you to specify metering to be displayed.
def.:0 'deciBel' = DeciBel display
'Linear' = Linear display
modulationcolor float Sets the modulation color of live.gain~ object in RGBA format.
orientation int Sets the slider object to a horizontal or vertical data display.
def.:0 'Vertical' = Vertical display
'Horizontal' = Horizontal display
overloadcolor float Sets the Overload signal color in RGBA format.
relative int Sets the mode for mouse behavior.
def.:0 'Absolute' = Absolute mode
'Relative' = Relative mode
showname int Toggles the display of the parameter name. The default is 1 (on).
def.:1
shownumber int Toggles the display of the gain parameter value. The default is 1 (on).
def.:1
slidercolor float Sets the slider background color in RGBA format.
textcolor float Sets the display color for the live.gain~ object's text in RGBA format.
threshold_db float Sets the redraw threshold for dB display. This allows you to balance the redrawing
def.:1. / efficiency. The maximum refresh rate is set by the interval attribute.
threshold_linear float Sets the redraw threshold for linear display. This allows you to balance the
def.:0.01 redrawing / efficiency. The maximum refresh rate is set by the interval attribute.
tribordercolor float Sets the triangle border color in RGBA format. This is only used when the
live.gain~ object does not have the focus.
tricolor float Sets the triangle color in RGBA format. This is only used when the live.gain~
object does not have the focus.
trioncolor float Sets the triangle color in RGBA format. This is only used when the live.gain~
object does have the focus.
warmcolor float Sets the Warm signal color in RGBA format.

Information about attributes available for Parameter-aware objects

Information for box attributes common to all objects

Output
float: Out third outlet: The current slider value in dB, when dragging on the slider with the mouse or when live.gain~ receives an
int or float.
Out fourth outlet: When an output is triggered, a raw normalized value (between 0. and 1.) is sent out this outlet.
list: Out fifth outlet: The amplitude of the two channels (in dB) is sent out this outlet.
signal: Out first and second outlet: The input signal, scaled by the current slider value.

Examples
See Also
Name Description
gain~ Exponential scaling volume slider
meter~ Visual peak level indicator
live.grid
A UI grid of steps, with constraints and directions

Description
live.grid is a user interfaces object designed for use with the chucker~ object. It provides a display grid of steps, constraints for
transposition, and playback direction for use in controlling the chucker~ object.

Arguments
None.

Messages
int step-index [int] Sets, displays and outputs the current step. The list sent out the left outlet of the
live.grid object takes the form step(s)direction (optional, depending on the
visibility of the directions panel). When the live.grid object is in Matrix Mode
and there is no value selected in the column, a 0 is sent as the step value.
list input-list [list] When the direction attribute is set to 0, a list of 2 values sets the step index and
value.
When the direction attribute is set to 1, a list of 3 values sets the step index, value
and direction.
When the matrixmode attribute is set to 1, a list of 3 values sets the object's
behavior: x, y, and state (0/1). An optional fourth value can be used to set
direction (-1/0/1).
clear The clear message is only used when the matrixmode attribute is enabled, and
will deselect all currently set rows and columns.
constraint constraint of the step Sets the constraint for a specific step. For instance, the message constraint 3 0 0
[list] 1 1 sets the constraints of the third step (column numbering starts at 1) to 0 0 1 1.
directions directions [list] Sets the grid directions, used to indicate the direction of playback of a step:
-1: Backward
0: Stop
1: Forward
down Decreases (lowers) the current values of all the steps by one. New step values are
sent out the second outlet.

Note: The current constraints, if any, are also taken into account when altering
current step values; the resulting shift might be "rounded" to the closest step.
freeze step-index [int] Set the index to 0 to hide the overlay used to indicate frozen values. Any index
greater than zero sets and displays the frozen step.
getconstraint column [int] The word getconstraint, followed by a number that specifies a column in the
live.grid display, will send a list consisting of the column number followed by a
list indicating the constrain state of each cell in the column, from bottom to top
(column numbering starts at 1). Constraints are indicated as follows:
0: Constraint
1: No constraint
getdirections column [int] The word getdirections, followed by a number that specifies a column in the
live.grid display, will send a list consisting of the column number followed by the
direction out the fourth (dumpout) outlet (column numbering starts at 1). The
direction is indicated as follows:
-1: Backward
0: Stop
1: Forward
getcell x-index [int] The word cell, followed by a pair of numbers that specifies the x and y indices of a
y-index [int] cell in the live.grid display, will send a list consisting of the word cell, a number
pair that specifies the x and y indices, and the value of the cell (column numbering
starts at 1).
getcolumn column [int] The word getcolumn, followed by a number that specifies a column in the
live.grid display, will send a list consisting of the word column, a number that
specifies the column index, and a list of the current column values out the fourth
(dumpout) outlet (column numbering starts at 1).
getrow row [int] The word getrow, followed by a number that specifies a row in the live.grid
display, will send a list consisting of the word row, a number that specifies the row
index, and a list of the current row values out the fourth (dumpout) outlet (row
numbering starts at 1).
init Restores and outputs the initial values.
left Rotate the values of all steps to the left. New steps values are sent out the second
outlet.

Note: The current constraints, if any, are also taken into account when altering
current step values; the resulting shift might be "rounded" to the closest step.
linkdump When the link attribute is set to 1, the linkdump message sends all messages
required to synchronize one live.grid object to another live.grid object out the
object's right outlet.
(mouse) Click and drag to edit the step values or constraints, depending on the current
display mode.
set step-index [int] Sets and displays the current output step without causing output.
random type (optional) [list] The word random generates new step values or step constraints, depending on the
current mode. An optional second argument can be used to select a portion of the
UI object to randomize:
steps: Randomize the steps values
constraint: Randomize constraints and make sure that the steps values are
correct with respect to the new constraints grid
directions: Randomize directions if the direction attribute is set to 1.
reset type (optional) [list] The word reset sets the default values or clears the constraints, depending on the
current mode. An optional second argument can be used to select a portion of the
UI object to reset:
steps: Reset the steps values (Note: since the reset may interact with the current
constraints, a given step value may not be completely reset)
constraint: Clear all constraints
directions: Set all the directions to forward if the direction attribute is set to 1.
setcell x-index [int] The word setcell, followed by a pair of numbers that specifies the x and y indices
y-index [int] of a cell in the live.grid display and a number value, will set the value of the
value [int] specified cell (column numbering starts at 1).
steps step values [list] Sets the values of all the steps at once. Value numbering starts at 1.
right Rotate the values of all the steps to the right. New steps values are sent out the
second outlet.

Note: The current constraints, if any, are also taken into account when altering
current step values; the resulting shift might be "rounded" to the closest step.
up Increases (raises) the values of all steps. New steps values are sent out the second
outlet.

Note: The current constraints, if any, are also taken into account when altering
current step values; the resulting shift might be "rounded" to the closest step.

Attributes
Name Type g/s Description
bgstepcolor float Sets the background step color of the live.grid object in RGBA format.
bgstepcolor2 float Sets the second background step color of the live.grid object in RGBA format.
bordercolor float Sets the border color of the live.grid object in RGBA format.
bordercolor2 float Sets the second border color of the live.grid object in RGBA format.
columns int Sets the number of columns in the live.grid object's display
def.:16
direction int Toggles the display of the directions arrows.
def.:1
directioncolor float Sets the color of the direction's arrows in RGBA format.
freezecolor float Sets the color of all frozen steps in RGBA format.
hbgcolor float Sets the highlighted background color of the live.grid object in RGBA format.
link int Toggles link mode. When activated, all the necessary messages to synchronize two
def.:0 live.grid objects are sent out the right outlet.
marker_horizontal int Defines the "first beat" indicator on the live.grid object's horizontal axis. The
def.:4 bgstepcolor attribute sets the display color for this indicator. To hide the
indicator, set the attribute value to zero.
marker_vertical int Defines the "first beat" indicator on the live.grid object's vertical axis. The
def.:4 bgstepcolor attribute sets the display color for this indicator. To hide the
indicator, set the attribute value to zero.
matrixmode int Toggles matrix mode for the object's display. In matrix mode, multiple cells in a
def.:0 row or column may be selected.
Note: The list and steps messages change their syntax slightly when used in
conjunction with this attribute. See the listing for these messages for more details.
mode int Defines the current display mode.
def.:0 'Step Edit' = TEXT_HERE
'Step constraint' = TEXT_HERE
rounded float Defines the roundness of the grid in pixels.
def.:4.
rows int Sets the number of rows in the live.grid object's display. The minimum number of
def.:16 rows is 2 when the matrixmode attribute is not set, and 1 if it is.
spacing float Defines the grid spacing in pixels.
def.:1.
stepcolor float Sets the step color of the live.grid object in RGBA format.

Information about attributes available for Parameter-aware objects

Information for box attributes common to all objects

Output
anything:
Out the fifth outlet: dumpout message used to query the live.grid object.
Out the rightmost outlet: Synchronization messages are sent through this outlet when the link attribute is set to 1.
list:
Out the leftmost outlet: Current step value: y value, direction (optional, depending on the visibility of the directions pane).
Out second outlet: The steps values are sent out this outlet whenever they are changed via the mouse or a message. If the
live.grid object is in Matrix Mode, the step value/y value coordinates of all "on" points are sent out the outlet.
Out third outlet: The directions values are sent out this outlet whenever they are changed via the mouse or a message. Note that
this outlet does not output anything when the direction attribute is set to 0.
Out the fourth outlet: Mouseover information: x, y, direction (optional, depending on the visibility of the directions panel). Also
when the mouse is used to change a setting, the message mousechange N is sent, where N indicates the type of change (0 =
steps, 1 = directions, 2 = constraints).

Examples
See Also
Name Description
live.step Step Sequencer UI object
multislider Display data as sliders or a scrolling display
itable Graphic display of a table
matrixctrl Matrix switch control
chucker~ Segment audio and reorder it on looped playback
live.line
Straight line

Description
live.line displays a straight line. It is useful for delimiting zones in your interface.

Arguments
None.

Attributes
Name Type g/s Description
arrows int Sets the display mode for the arrows.
def.:0 'None' = None
'Start' = Start
'End' = End
'Both' = Both
border float Defines the thickness of the line in pixels
def.:1.
justification int Sets the alignment of live.line object.
def.:0 'Left/Top' = Left/top
'Centered' = Centered
'Right/Bottom' = Right/bottom
'Xing 1' = TEXT_HERE
'Xing 2' = TEXT_HERE
linecolor float Sets the line color of live.line object in RGBA format.

Information for box attributes common to all objects

Examples

See Also
Name Description
panel Colored background area
live.menu
Pop-up menu

Description
The live.menu object can be used to display text associated with incoming numbers and provide a general user interface. Item
numbering starts from zero (0).

Arguments
None.

Messages
bang Sends the current item out the outlets.
int item-index [int] An integer specifies a menu item to be displayed, and causes the live.menu object
to display that item and output information about its index and the symbol
associated with that menu index. Menu item numbering starts at 0.
float item-index [float] Converted to int.
assign assign-input [float] The word assign, followed by a floating point value, causes that value to be stored
and displayed and sent out the live.menu object's outlet. If the Parameter
Visibility attribute is set to Stored Only, the assign message will not add the new
value to the Live applications undo chain.
init Restore and output the initial value.
(mouse) Clicking with the mouse lets you select a menu item to be displayed and outputs
information about its index and the symbol associated with that menu index.
outputvalue Sends the current value out the outlet.
set item index [float] The word set, followed by a number, specifies a menu item to be displayed by the
live.menu object without triggering any output.
setsymbol menu item [list] The word setsymbol, followed by a message, selects a menu item to be displayed
by name without triggering any output.
symbol menu item [list] The word symbol, followed by a message, selects a menu item to be displayed by
name. If the item is found, the menu item is displayed and information about its
index and the symbol associated with that menu index.
rawfloat input-value [float] A raw normalized value (between 0. and 1.) received in the inlet is converted to a
real value, stored, displayed by live.menu, and the current item is sent out the
outlets.

Attributes
Name Type g/s Description
active int Toggles the object's active mode. When the active attribute is set to 0, the mouse
def.:1 action does not cause output and the inactive colors are used. The default is 1 (on).
activebgcolor float Sets the background color off displayed when active attribute is set to 1.
bordercolor float Sets the display color for the live.menu object's border in RGBA format.
focusbordercolor float Sets the border color in RGBA format to be used when the live.menu has the
focus.
hltcolor float Sets the highlight color in RGBA format to be used when you select an item with
the mouse.
pictures symbol Sets the paths of any pictures used when the usepicture attribute is set to 1.
Bitmap images such as PNG or vectorized images (SVG) can be used.
textcolor float Sets the display color for the live.menu object's text in RGBA format.
tricolor float Sets the triangle color in RGBA format.
usepicture int Toggles the use of the pictures instead of text display. Note that you need to
def.:0 provide enough pictures by setting the pictures attribute properly.

Information about attributes available for Parameter-aware objects

Information for box attributes common to all objects

Output
anything: Out middle outlet: The text of the selected menu item is sent out as a message.
float: Out right outlet: When an output is triggered, a raw normalized value (between 0. and 1.) is sent out this outlet.
int: Out left outlet: The number of the selected menu item is sent out. Menu items are numbered beginning with 0.

Examples

See Also
Name Description
live.tab A user interface tab/multiple button object
umenu Create and fill a pop-up menu
live.meter~
Live-style visual peak level indicator

Description
live.meter~ is a simple mono Live-style signal level meter that can be attached to any signal whose level is between -1 and 1
(other signals should be scaled first).

Arguments
None.

Messages
int signal-value [int] Converted to float.
float signal-value [float] When no signal is connected to the live.meter~ object's inlet, a float number will
set the meter to react as though a signal with equal amplitude peak-value has been
passed to its input. Corresponding LEDs will light up and the peak-level value will
be passed out the outlet (0.0 will show silence, 0.0 through 1.0 will light up to any
but the overload LED, and anything above 1.0 will light all LEDs including
overload).
db db-value [float] The word db, followed by a floating point number that specficies a deciBel value,
will set the live.meter~ object to react as though a signal with that dB peak-value
has been passed to its input. Corresponding LEDs will light up and the value will
be passed out the outlet.
signal The peak amplitude of the incoming signal is displayed by the on-screen level
meter.

Attributes
Name Type g/s Description
active int Enables (1) or disables (0) the meter display.
def.:1
bgcolor float Sets the background color in RGBA format.
clip_size int Sets the clipping range for the display. The options are Normal or Extended.
def.:0 'Normal' = TEXT_HERE
'Extended' = TEXT_HERE
coldcolor float Sets the Cold signal color in RGBA format.
display_range float Sets the display range of the meter in dB.
def.:-70. 6.
hotcolor float Sets the Warning signal color in RGBA format.
inactivecoldcolor float Sets the Cold signal (inactive) color in RGBA format.
inactivewarmcolor float Sets the Warm signal (inactive) color in RGBA format.
interval int Sets the maximum update-time interval, in milliseconds, of the live.meter~
def.:20 display. The minimum update-interval is 10 milliseconds, the maximum is 2
seconds, and the default is 50 milliseconds. This message also sets the rate at
which meter~ sends out the peak value received in that time interval. The
threshold_db or threshold_linear attributes are used to limit the refresh and the
output, depending on the setting of the mode attribute.
mode int Sets the display and output mode of the live.meter~ object.
def.:0 'deciBel' = TEXT_HERE
'Linear' = TEXT_HERE
orientation int Sets the orientation of the meter display. The options are Horizontal or Vertical
def.:0 'Vertical' = TEXT_HERE
'Horizontal' = TEXT_HERE
overloadcolor float Sets the Overload signal color in RGBA format.
threshold_db float When the live.meter~ object's mode attribute is set to 0, this attribute sets the
def.:1. refresh threshold in deciBels. If the signal peak delta is greater than the threshold
value, the object will be redrawn and the value sent out the outlet.
threshold_linear float When the live.meter~ object's mode attribute is set to 1, this attribute sets the
def.:0.01 refresh threshold in deciBels. If the signal peak delta is greater than the threshold
value, the object will be redrawn and the value sent out the outlet.
warmcolor float Sets the Warm signal color in RGBA format.

Information for box attributes common to all objects

Examples

See Also
Name Description
average~ Multi-mode signal average
meter~ Visual peak level indicator
scope~ Visualize an audio signal
live.numbox
Display and output a number

Description
The live.numbox object is a number box used to display, input, and output numbers.

Arguments
None.

Messages
bang Sends the current value out the outlet.
int input [int] The number received in the inlet is stored and displayed by the live.numbox
object and sent out the outlet.
float input [float] The number received in the inlet is stored and displayed by the live.numbox
object and sent out the outlet.
assign assign-input [float] The word assign, followed by a floating point value, causes that value to be stored
and displayed and sent out the live.numbox object's outlet. If the Parameter
Visibility attribute is set to Stored Only, the assign message will not add the new
value to the Live applications undo chain.
init Restores and outputs the initial value.
(mouse) Click and drag the live.numbox display to change the value. Hold down the
Command key (Macintosh) or the Control key (Windows) for more precise mouse
control.
If the live.numbox object is set to store an initial value (set by checking the Initial
Enable option in the object's Inspector), double-clicking in the triangle region will
restore that value.
outputvalue Sends the current value out the outlet.
set set-input [float] Sets the current value without causing any output.
rawfloat input [float] A raw normalized value (between 0. and 1.) received in the inlet is converted to a
real value, stored, displayed by live.numbox, and the current value is sent out the
outlet.

Attributes
Name Type g/s Description
active int Toggles the object's active mode. When the active attribute is set to 0, the mouse
def.:1 action does not cause output, and the inactive colors are used.
activebgcolor float Sets the background color off displayed when the active attribute is set to 1.
activeslidercolor float Sets the slider color displayed when the active attribute is set to 1.
activetricolor float Sets the triangle color displayed when the actual value is equal to the initial value.
activetricolor2 float Sets the triangle color displayed when the actual value is different from the initial
value and the active attribute is set to 1.
appearance int Select different display modes:
def.:0 mode 0 (default): Standard display
mode 1: Triangle display
mode 2: Slider display
'Default' = TEXT_HERE
'Triangle' = TEXT_HERE
'Slider' = TEXT_HERE
bordercolor float Sets the display color for the live.numbox object's border in RGBA format.
focusbordercolor float Sets the border color in RGBA format to be used when the live.numbox has the
focus.
textcolor float Sets the display color for the live.numbox object's text in RGBA format.
tricolor float Sets the triangle color displayed when the actual value is different from the initial
value and the active attribute is set to 0.
tricolor2 float Sets the triangle color displayed when the actual value is different from the initial
value and the active attribute is set to 0.

Information about attributes available for Parameter-aware objects

Information for box attributes common to all objects

Output
float: Out right outlet: when an output is triggered, a raw normalized value (between 0. and 1.) is sent out this outlet.
int/float: Out left outlet: Numbers received in the inlet, or produced by clicking or dragging on live.numbox with the mouse, are
sent out the outlet. The value sent is an integer if the Parameter Type is set to INT or ENUM.

Examples

See Also
Name Description
live.dial Output numbers by moving a dial onscreen
live.slider Output numbers by moving a slider onscreen
number Display and output a number
flonum Display and output a number
live.object
Perform operations on Live objects

Description
live.object is used to perform operations on Live objects that have been selected using the live.path object. These operations
include retrieving information on the current state of the Live API and setting values to control Live.

Arguments
None.

Inlets
Name Description
Left inlet Gets all command messages described below.
Right inlet Gets object id message id nn to select the object to operate upon.
id 0 means no object, i.e. all messages to the left inlet are ignored, which is also the initial
state.

Outlets
Name Description
Left outlet Sends responses to get, call, bang, getid, getinfo, gettype and getpath.

Messages
get property [symbol] Arguments:
property the name of a single-value property of the current object

Operation:
Sends value of given property of the current object.

Outlet Output Example


left property value name base solo 3
get list-property [symbol] Arguments:
list-property the name of a list property of the current object

Operation:
Sends the list of values of given property of the current object.

Outlet Output Example


left list-property list input_routings Ext. In Max Resampling 1-Audio
of values A-Return Master No Input
get child [symbol] Arguments:
child the name of a child of the current object

Operation:
Sends the id of the child of the current object.

Outlet Output Example


left child id nn master_track id 10
get list-child [symbol] Arguments:
list-child the name of a list-child of the current object

Operation:
Sends the ids of the elements of the list-child of the current object.

Outlet Output Example


left list-child id nn ... id mm clip_slots id 4 id 5
set property [symbol] Arguments:
value [various types] property the name of a single-value property of the current object
value the new value for the property

Operation:
Set the value of given property of the current object.

Remark:
Not all properties can be set. The types of the properties are given in the Live
Object Model.

- no output -
set list-property [symbol] Arguments:
value-list [various types] list-property the name of a list property of the current object
value-list the new values for the property

Operation:
Set the given list property to the value list.

Remark:
Not all properties can be set. The types of the properties are given in the Live
Object Model.

- no output -
set child [symbol] Arguments:
id nn [id] child the name of a child of the current object
id nn the new child object for this name

Operation:
Set the child name to point to the given child.

Remark:
Not all children can be set.

- no output -
set list-child [symbol] Arguments:
id nn ... id mm [id-list] list-child the name of a list child of the current object
id nn ... id mm the new list of objects for the given name

Operation:
Set the list child to contain the given ids.

Remark:
Not all children can be set.

- no output -
call function [symbol] Arguments:
parameter-list [list of function the name of the function
different types] parameter-list an optional list of parameters

Operation:
Calls the given function of the current object, optionally with a list of parameters.

Remark:
The types of the parameters are given in the Live Object Model.

Outlet Output Example


left function value get_beats_loop_length 004.00.00.000
bang, Operation:
getid Sends the id of the current Live object to the outlet.

Outlet Output Example


left id nn id 5
getinfo Operation:
Sends a description of the current object.

Output to left outlet (most lines may occur multiple times, last line is info done):

info id nn
info type object-type
info description description
info children list-child object-type
info child child object-type
info property property property-type
info function function
info done

Example output:

info id 3
info type Scene
info description This class represents a series of ClipSlots in Lives session
view matrix
info children clip_slots ClipSlot
info child canonical_parent Song
info property is_triggered bool
info property name symbol
info property tempo float
info function fire
info function fire_as_selected
info function set_fire_button_state
info done
gettype Operation:
Sends the type (a.k.a. class) of the current object.

Outlet Output Example


left type object-type type Song
getpath Operation:
Sends the canonical path of current object.

Outlet Output Example


left path path path live_set return_tracks 0
id nn Operation:
Sets the current object. The message has the same effect if sent to both the right or
the left inlet. For clarity it is suggested to always use the right inlet to supply the
object id.

- no output -

Attributes
Name Type g/s Description

Information for box attributes common to all objects


Inspector
Persistence: The live.object object has a special entry in its inspector labelled "Use Persistent Mapping". This setting, when
enabled, causes the id associated with the object to persist when the Live document is saved and restored, and when the Max
Device is moved between the Live application and the Max editor, or within the Live Set. Beginning in Live 8.2.2, Live API ids
remain persistent between launches of Live, which in conjunction with the Persistence feature of live.object, live.observer and
live.remote~, makes it possible to create simpler devices which retain their association with elements in the Live user interface.

Examples

See Also
Name Description
Live API Overview
Live Object Model
live.path Navigate to objects in the Live application
live.observer Monitor changes in Live objects
live.remote~ Realtime control of device parameters
Using the Live API Creating Devices that use the Live API
The LiveAPI JavaScript Object The LiveAPI Object
(jsliveapi)
live.observer
Monitor changes in Live objects

Description
live.observer is used to listen to changes in the values of properties of Live objects. This object works in conjunction with the
live.path object, which sends id nn messages into the right inlet of live.observer.

After an object id and property is specified, its value is sent out the left outlet. From this moment on, the value is sent on each
change of the property ('notification') as well as in response to bang messages.

The left outlet is reserved for value messages, all other output is sent to the right outlet.

Not all properties can be observed, please consult the Live Object Model to see which can. Also, it is not possible to modify the
live set from a notification, i.e. while you are receiving a value message spontaneously sent by a live.observer 's outlet.

Besides properties, it is also possible to observer children of Live objects. Their values are object ids or lists of them.

Arguments
Name Units Type Opt Description
property symbol opt Specify a property or child name as argument to live.observer.

Inlets
Name Description
Left inlet Gets all command messages described below.
Right inlet Gets object id message id nn to select the object to operate upon. In response to the id
message, the current value of the property, if a property was already selected, is sent out the
left outlet.
id 0 means no object, i.e. all messages to the left inlet are ignored, which is also the initial
state.

Outlets
Name Description
Left outlet Sends the current value of the selected property of the selected object. The value type
depends on the property, as described in the Live Object Model, and may be int, float,
symbol, id nn or lists of ids.
Right outlet Sends responses to getproperty, gettype, getid.

Messages
property property [symbol] Arguments:
property the name of a property of the current object

Operation:
Selects the property to be observed. Outputs the current value to the left outlet if a
proper Live object is selected.

Remark:
Not all properties can be observed.
The types of the properties are given in the Live Object Model.

Outlet Output Example


left value 3.1415926
property child [symbol] Arguments:
child the name of a child of the current object

Operation:
Selects the child id to be observed. Outputs the id (or "id 0") to the left outlet if
the selected Live object has such a child.

Remark:
Not all children can be observed.

Outlet Output Example


left id nn id 17
property list-child [symbol] Arguments:
child the name of a child list of the current object

Operation:
Selects the child list to be observed. Outputs the id list (or nothing) to the left
outlet if the selected Live object has such a list child.

Remark:
Not all child lists can be observed.

Outlet Output Example


left id nn ... id mm id 4 id 5
getproperty Operation:
Sends the name of the selected property (or child resp. list-child) out the right
outlet.

Outlet Output Example


right property property or property name or
property child property selected_track
gettype Operation:
Sends the type of currently observed property or child to the right outlet. The types
of the properties and children are given in the Live Object Model.

For list-children it just sends type tuple, w/o further type information.
Outlet Output Example
right type property-type or type int or
type object-type type Track
getid Operation:
Sends the id of the currently observed Live object to the right outlet.

Outlet Output Example


right id nn id 20
bang Operation:
Sends current value of selected property of current object to the left outlet. Does
nothing if no property or no Live object is selected or if they don't match.

Outlet Output Example


left value Drums
id nn Operation:
Sets the current object. The message has the same effect if sent to both the right or
the left inlet. For clarity it is suggested to always use the right inlet to supply the
object id.

- no output -

Attributes
Name Type g/s Description
Information for box attributes common to all objects

Inspector
Persistence: The live.observer object has a special entry in its inspector labelled "Use Persistent Mapping". This setting, when
enabled, causes the id associated with the object to persist when the Live document is saved and restored, and when the Max
Device is moved between the Live application and the Max editor, or within the Live Set. Beginning in Live 8.2.2, Live API ids
remain persistent between launches of Live, which in conjunction with the Persistence feature of live.object, live.observer and
live.remote~, makes it possible to create simpler devices which retain their association with elements in the Live user interface.

Examples

See Also
Name Description
Live API Overview
Live Object Model
live.path Navigate to objects in the Live application
live.object Perform operations on Live objects
live.remote~ Realtime control of device parameters
Using the Live API Creating Devices that use the Live API
The LiveAPI JavaScript Object The LiveAPI Object
(jsliveapi)
live.param~
Generate an MSP signal from a parameter value.

Description
live.param~ produces a signal with the current value of a parameter.

Arguments
Name Units Type Opt Description
parameter- parameter- The live.param~ object takes as an argument the name of the parameter that you
name name wish to monitor.

Messages
signal The current value of the parameter is output as a value at signal rate.

Information for box attributes common to all objects

Examples

See Also
Name Description
live.observer Monitor changes in Live objects
live.remote~ Realtime control of device parameters
live.path
Navigate to objects in the Live application

Description
live.path is used to navigate to Live objects on which the live.object, live.observer and live.remote~ objects operate. The
navigation is purely path-based and is independent of the objects currently present in Live (navigating to a nonexistent path will
result in the message id 0 being sent out the left and middle outputs rather than an error message).

Arguments
Name Units Type Opt Description
initial path symbol opt Specify an initial path as argument to live.path, without any quotes.

Inlets
Name Description
Single inlet Gets all command messages described below.

Outlets
Name Description
Left outlet Sends the message id nn in response to a goto, bang or getid message only . Use this
outlet if you want to keep working with a particular object determined at goto or bang time,
even if its position in Live changes.

For example, consider a fresh Live set with two tracks, "1 Audio" as the leftmost track and "2
MIDI" to the right of it. If you navigate to the "2 MIDI" track (goto live_set tracks 1) and you
create a new Audio track between "1 Audio" and "2 MIDI", your original MIDI track now
would be at live_sets tracks 2. But since the id number of the MIDI track would stay the
same and no new id is sent out to the left outlet, the live.xxx objects connected to this
outlet keep working with the MIDI track, until you sent another goto.
Middle outlet Sends id nn whenever the id of the object at the current path changes (because the current
path is changed or because the object at this place in Live has changed, for example. Use
this outlet if you want to keep working with the same path, whatever object there might be.
This outlet is very useful for things like live_set view detail_clip.

Consider the example above. If the live.xxx objects would be connected to the middle outlet
of live.path, then they would work with the newly created audio track.

The spontaneous sending of object ids out of the middle outlet, i.e. without an inlet
message causing it, but caused by a change in Live, is called a notification.
Note: It is not possible to modify the Live set from such a notification.
Right outlet Sends responses to getpath, getchildren, getcount.

Messages
goto path [symbol] Arguments:
path is an absolute path (starts with live_app, live_set or control_surfaces N ) or
a relative path, or up

Operation:
Navigates to given path and sends id of the object at that path out the left and
middle outlets. If there is no object at the path, id 0 is sent.

Remarks:
You cannot go to a list property, only to one of its members.
invalid: goto live_set scenes
correct: goto live_set scenes 3

Outlet Output Example


left id nn id 5
middle id nn id 5
path absolute-path [symbol] Same as goto but limited to absolute paths that start with a root object name like
live_app, live_set, this_device or control_surfaces N .
bang, getid Operation:
Sends the id of the object at the current path to left and middle outlets. Sends id 0
if there is no object at the current path.

Outlet Output Example


left id nn id 5
middle id nn id 5
getpath Operation:
Sends a path message with the current path to the right outlet.

Outlet Output Example


right path path path live_set scenes 1
getchildren Operation:
Sends a list of children of the object at the current path, if any, to the right outlet.

Remarks:
The child names are the same names as used in the goto message.

Outlet Output Example


right children list-of-child-names children canonical_parent clip_slots
getcount child-name [symbol] Arguments:
child-name is the name of a child of the object at the current path.

Operation:
Sends a count message to the right outlet, containing the name of the child and its
number of entries.

Remarks:
The given child must be a list.

Outlet Output Example


right count child-name count count clip_slots 2

Attributes
Name Type g/s Description

Information for box attributes common to all objects

Examples
See Also
Name Description
Live API Overview
Live Object Model
live.object Perform operations on Live objects
live.observer Monitor changes in Live objects
live.remote~ Realtime control of device parameters
Using the Live API Creating Devices that use the Live API
The LiveAPI JavaScript Object The LiveAPI Object
(jsliveapi)
live.remote~
Realtime control of device parameters

Description
The live.remote~ object allows to remotely control Lives DeviceParameter objects in realtime.

Arguments
None.

Inlets
Name Description
Left inlet value (signal/float) Gets the value of the device parameter object selected by the right inlet.
For valid ranges look at the min and max properties of the DeviceParameter. The value curve
is linear to the parameter's GUI control in Live.
Right inlet id nn Gets object id message id nn to select the DeviceParameter object to control.
id 0 means no object, i.e. the remote stops controlling the DeviceParameter. This is also the
initial state.

Messages
float value [float] A floating point number value received in the left inlet will be applied to the
selected Live DeviceParameter, if any. Obviously not in realtime.
int value [int] An integer number value received in the left inlet will be applied to the selected
Live DeviceParameter, if any. Not in realtime, though.
signal Signal input values received in the left inlet will be applied to the selected Live
DeviceParameter, if any, in realtime.
id nn In right inlet: Sets the current object. The message has no effect if the id is no a
DeviceParameter.

Attributes
Name Type g/s Description

Information for box attributes common to all objects

Inspector
Persistence: The live.remote~ object has a special entry in its inspector labelled "Use Persistent Mapping". This setting, when
enabled, causes the id associated with the object to persist when the Live document is saved and restored, and when the Max
Device is moved between the Live application and the Max editor, or within the Live Set. Beginning in Live 8.2.2, Live API ids
remain persistent between launches of Live, which in conjunction with the Persistence feature of live.object, live.observer and
live.remote~, makes it possible to create simpler devices which retain their association with elements in the Live user interface.

Examples
See Also
Name Description
Live API Overview
Live Object Model
live.object Perform operations on Live objects
live.observer Monitor changes in Live objects
live.path Navigate to objects in the Live application
Using the Live API Creating Devices that use the Live API
The LiveAPI JavaScript Object The LiveAPI Object
(jsliveapi)
live.slider
Output numbers by moving a slider onscreen

Description
live.slider is a user interface object that resembles a sliding potentiometer.

Arguments
None.

Messages
bang Sends the current value out the outlet.
int input [int] The number received in the inlet is stored and displayed by the live.slider object
and sent out the outlet.
float input [float] The number received in the inlet is stored and displayed by the live.slider object
and sent out the outlet.
assign assign-input [float] The word assign, followed by a floating point value, causes that value to be stored
and displayed and sent out the live.slider object's outlet. If the Parameter
Visibility attribute is set to Stored Only, the assign message will not add the new
value to the Live applications undo chain.
init Restore and output the initial value.
(mouse) Click and drag in the slider to change the value. Hold down the Command key
(Macintosh) or the Control key (Windows) for more precise mouse control.
outputvalue Sends the current value out the outlet.
set set-input [float] Sets and displays the current value without triggering any output.
rawfloat input [float] A raw normalized value (between 0. and 1.) received in the inlet is converted to a
real value, stored, displayed by live.slider, and the current value is sent out the
outlet.

Attributes
Name Type g/s Description
active int Toggles the object's active mode. When the active attribute is set to 0, the mouse
def.:1 action does not cause output and the inactive colors are used.
focusbordercolor float Sets the border color in RGBA format to be used when the live.slider has the
focus.
modulationcolor float Sets the modulation color of the live.slider object in RGBA format.
orientation int Defines the orientation of the live.slider object.
def.:0 'Vertical' = Vertical
'Horizontal' = Horizontal
relative int Sets the way that the live.slider object responds to mouse clicks.
def.:0 'Absolute' = Absolute
'Relative' = Relative
showname int The word showname, followed by the number 1 or 0, shows or hides the
def.:1 parameter name.
shownumber int The word shownumber, followed by the number 1 or 0, shows or hides the
def.:1 parameter value.
slidercolor float Sets the slider color of the live.slider objectin RGBA format.
textcolor float Sets the display color for the live.slider object's text in RGBA format.
tribordercolor float Sets the triangle border color in RGBA format. This is only used when the
live.slider object does not have the focus.
tricolor float Sets the triangle color in RGBA format. This is only used when the live.slider
object does not have the focus.
trioncolor float Sets the triangle color in RGBA format. This is only used when the live.slider
object does have the focus.

Information about attributes available for Parameter-aware objects

Information for box attributes common to all objects

Output
float: Out right outlet: when an output is triggered, a raw normalized value (between 0. and 1.) is sent out this outlet.
int/float: Out left outlet: Numbers received in the inlet or produced by clicking or dragging on live.slider with the mouse are
sent out the outlet. The value sent is an integer if the Parameter Type is set to INT or ENUM.

Examples

See Also
Name Description
live.numbox Display and output a number
live.dial Output numbers by moving a dial onscreen
Output numbers by moving a slider onscreen
live.step
Step Sequencer UI object

Description
live.step displays multiple sequences which have multiple steps composed of pitch, velocity, and duration. Two additional steps
(Extra 1 and Extra 2) are available for user-defined display.

Arguments
None.

Messages
bang If the target_seq attribute is set to zero, a bang message will send the values
associated with the current step of all sequences out the object's left outlet. If the
target_seq attribute is set to a value greater than zero, a bang message will send
the values associated with the current step of the currently specified sequence out
the object's left outlet.
int step-index [int] If the target_seq attribute is set to zero, an integer sets the current step of all
sequences to the corresponding integer (index numbering starts at 1). If the
target_seq attribute is set to a value greater than zero, an integer sets the current
step of the currently specified sequence. The values associated with the current
step are sent out the object's left outlet.
active 0/1 [int] If the target_seq attribute is set to zero, the message active 0 deactivates all
sequences. The word active, followed by any non-zero value, will activate all
sequences.
If the target_seq attribute is set to a value greater than zero, the message active
0 deactivates the specified sequence. The word active, followed by any non-zero
value, will activate the specified sequence.
copy start-index [int] The word copy will copy the entire sequence. One or two optional integer
stop-index [int] arguments may be used to specify starting and ending indices (index numbering
starts at 1). For example, copy 2 will copy the sequence starting at index 2, while
copy 2 5 will copy starting at index 2 and ending at index 5.
direction direction-value [int] The word direction followed by an integer in the range 0-4, sets the playback
direction for sequence playback. The playback options are:
0: forward
1: backward
2: back and forth
3: Rotate
4: random

If the target_seq attribute is set to zero, the integer argument sets the direction of
all sequences when live.step object's playback is controlled using the time
message.
If the target_seq attribute is set to a value greater than zero, an integer sets the
direction of the specified sequence when live.step object's playback is controlled
using the time message.
doedit edit-mode [int] The word doedit, followed by a number in the range 0-4, provides a simple means
to move or rotate the parameters stored in the live.step object. The modes
specified by the number arguments are:
0: transpose the pitch upward.
1: transpose the pitch downward.
2: Rotate the steps to the left.
3: Rotate the steps to the right
4: Randomize steps depending on the mode attribute. For instance, if the mode
is set to velocity, doedit 4 will only randomize the velocity.
For more advanced editing features, use the up, down, left, right, random,
scramble, and sort messages.
down parameter [symbol] The word down will decreases the values of the sequence based on the target_seq
and mode attributes. For instance, if the mode attribute is set to velocity, the
down message will only decrease the velocity of the currently specified sequence
(or all the sequences if the target_seq attribute is set to zero).
An optional argument may be used with the down message to specify the
parameters to be decreased without having to use the mode attribute. The
optional arguments are:
all: decrease all parameters
pitch: transpose pitches downward
velocity: decrease velocities
duration: decrease durations
extra1: decrease values for the user-definable Extra 1 parameter
extra2: decrease values for the user-definable Extra 2 parameter
dump Sends the values (pitch, velocity, duration, extra1, extra2) of all steps of the
currently specified sequence out the live.step object's right outlet.
duration start-index/values [list] The word duration, followed by an integer that specifies a starting index into a
sequence (index numbering starts with 1) and a list of values (in ticks), will set the
duration values for the current sequence specified by the target_seq attribute.
extra1 start-index/values [list] The word extra1, followed by an integer that specifies a starting index into a
sequence (index numbering starts with 1) and a list of values, will set the extra1
values for the current sequence specified by the target_seq attribute.
extra2 start-index/values [list] The word extra2, followed by an integer that specifies a starting index into a
sequence (index numbering starts with 1) and a list of values, will set the extra2
values for the current sequence specified by the target_seq attribute.
fold 0/1 [int] The word fold, followed by a 0 or 1, toggles the folded display mode. When folding
is enabled, the live.step object only displays those pitches which are present in the
sequence specified by the target_seq attribute rather than all possible pitches.
Fold mode displays only the pitches specific to each individual sequence .
Note: Sequence editing messages such as up, down, and random use the list of
pitches displayed in fold state when performing operations (i.e., the random
message will only choose randomly from among the pitches displayed on fold
mode. These operations are also dependent on the target sequence, as well). for all
sequences.
getactive The message getactive will send the active state of the currently specified
sequence out the live.step object's fourth (dumpout) outlet in the form of a list
preceded by the word active.
getdirection The message getdirection will send the direction state of the currently specified
sequence out the live.step object's fourth (dumpout) outlet in the form of a list
preceded by the word direction.
getduration The message getduration will send a list of all the duration values in the sequence
specified by the target_seq attribute out the live.step object's fourth (dumpout)
outlet in the form of a list preceded by the word duration.
getextra1 The message getextra1 will send a list of all the extra1 values in the sequence
specified by the target_seq attribute out the live.step object's fourth (dumpout)
outlet in the form of a list preceded by the word extra1.
getextra2 The message getextra2 will send a list of all the extra2 values in the sequence
specified by the target_seq attribute out the live.step object's fourth (dumpout)
outlet in the form of a list preceded by the word extra2.
getinterval The message getinterval will send the interval of the currently specified sequence
out the live.step object's fourth (dumpout) outlet in the form of a list preceded by
the word interval.
getloop The message getloop will send the loop points of the currently specified sequence
out the live.step object's fourth (dumpout) outlet in the form of a list preceded by
the word loop.
getnstep The message getnstep will send the number of steps in the currently specified
sequence out the live.step object's fourth (dumpout) outlet in the form of a list
preceded by the word nstep.
getmodelist The message getmodelist will send the list of the display modes out the live.step
object's fourth (dumpout) outlet in the form of a list preceded by the word
modelist.
getpitch The message getpitch will send a list of all the pitch values in the sequence
specified by the target_seq attribute out the live.step object's fourth (dumpout)
outlet in the form of a list preceded by the word pitch.
getstep step-index [int] The message getstep will send a list of the values (pitch, velocity, duration, extra1,
extra2) of the specified index of the currently specified sequence out the live.step
object's fourth (dumpout) outlet in the form of a list preceded by the word step.
getvelocity The message getvelocity will send a list of all the velocity values in the sequence
specified by the target_seq attribute out the live.step object's fourth (dumpout)
outlet in the form of a list preceded by the word velocity.
fetch parameter name [symbol] The word fetch, followed by a symbol that specifies a step parameter (pitch,
step number [int] velocity, duration, extra1, or extra2) and an integer that specifies a step number,
will send a list out of the live.step object's fourth (dumpout) outlet in the form
<parameter-name> <step-number> <value> .
getzoom The message getzoom will send the zoom pitch values of the currently specified
sequence out the live.step object's fourth (dumpout) outlet in the form of a list
preceded by the word zoom.
fold_pitch pitches-list [list] The word fold_pitch, followed by an integer or list of integers that specify MIDI
note numbers, sets the pitches to be displayed by the live.step object in fold
mode. As with the fold message, the fold_pitch message sets pitches to be
displayed in the sequence specified by the target_seq attribute.
init Restores and outputs the initial values.
interval time-value [list] Sets the interval of the currently specified sequence.
left parameter [symbol] The word left will rotate (left-shift) the values of the sequence based on the
target_seq and mode attributes. For instance, if the mode attribute is set to
velocity, the left message will only rotate the velocity of the currently specified
sequence (or all the sequences if the target_seq attribute is set to zero).
An optional argument may be used with the left message to specify the parameters
to be rotated without having to use the mode attribute. The optional arguments
are:
all: Rotate all parameters to the left
pitch: Rotate all pitches to the left
velocity: Rotate all velocities to the left
duration: Rotate all durations to the left
extra1: Rotate all user-definable Extra 1 parameters to the left
extra2: Rotate all user-definable Extra 2 parameters to the left
loop start-index [int] The word loop, followed by two numbers that specify starting and ending indices,
stop-index [int] sets the loop points of the currently specified sequence.
nstep number of steps [int] Sets the number of steps in the target sequence.
(mouse) Whenever the live.step object is edited using the mouse, the message changed
followed by a number in the range 0-2 will be sent out the object's dumpout outlet.
The number specifies what portion of the live.step display has been modified, as
follows:

0: The pitch, velocity, duration, extra1, or extra2 settings have been modified.
1: The looping portion of the UI has been modified.
2: Edits have been made in the ruler area of the UI.
paste parameter [symbol] When the paste message is received without argument, all parameters are pasted
start-index [int] at the same location as they were copied. An optional argument to specify
parameter type (pitch, velocity, duration, extra1, extra2) can be used to paste only
specific items. An additional option number argument specifies the starting index
where the copied steps will be pasted (index numbering starts at 1).
pitch start-index/values [list] The word pitch, followed by an integer that specifies a starting index into a
sequence (index numbering starts with 1) and a list of values, will set the pitch
values for the current sequence specified by the target_seq attribute.
set step-index [int] If the target_seq attribute is set to zero, the word set, followed by an integer sets
the current step of all the sequences to the corresponding integer (index
numbering starts at 1).
If the target_seq attribute is set to a value greater than zero, the word set,
followed by an integer sets the current step of the currently specified sequence.
random parameter [symbol] The word random will randomize the values of the sequence based on the
target_seq and mode attributes. For instance, if the mode attribute is set to
velocity, the random message will only scramble the velocity of the currently
specified sequence (or all the sequences if the target_seq attribute is set to zero).
An optional argument may be used with the random message to specify the
parameters to be scrambled without having to use the mode attribute. The
optional arguments are:
all: Randomize all parameters
pitch: Randomize all pitches
velocity: Randomize all velocities
duration: Randomize all durations
extra1: Randomize all values for the user-definable Extra 1 parameter
extra2: Randomize all values for the user-definable Extra 2 parameter
reset The reset message allows you to deactivate the current step. It is equivalent to
setting the current step to 0.
right parameter [symbol] The word right will rotate (right-shift) the values of the sequence based on the
target_seq and mode attributes. For instance, if the mode attribute is set to
velocity, the left message will only rotate the velocity of the currently specified
sequence (or all the sequences if the target_seq attribute is set to zero).
An optional argument may be used with the right message to specify the
parameters to be rotated without having to use the mode attribute. The optional
arguments are:
all: Rotate all parameters to the right
pitch: Rotate all pitches to the right
velocity: Rotate all velocities to the right
duration: Rotate all durations to the right
extra1: Rotate all values for the user-definable Extra 1 parameter to the right
extra2: Rotate all values for the user-definable Extra 2 parameter to the right
time bar [int] The word time, followed by a list of 6 numbers, defines the timing position in the
beat [int] sequence. The required arguments are bar, beat, unit, resolution-in-ppq,
unit [int] time-signature-numerator, and time-signature-denominator. The live.step
resolution [int] object does not have an internal clock, so you need to send the time message often
time-sig-numerator [list] if you want to use it to drive the live.step object.
time-sig-denominator
[list]
scramble parameter [symbol] The word scramble will randomize the order of the values of the sequence based
keep-step-sync [int] on the target_seq and mode attributes. For instance, if the mode attribute is set
to velocity, the left message will only scramble the velocity of the currently
specified sequence (or all the sequences if the target_seq attribute is set to zero).
An optional argument may be used with the scramble message to specify the
parameters to be scrambled without having to use the mode attribute. The
optional arguments are:
all: Randomize the order of all parameters
pitch: Randomize the order of all pitches
velocity: Randomize the order of all velocities
duration: Randomize the order of all durations
extra1: Randomize the order of all user-definable Extra 1 parameters
extra2: Randomize the order of all user-definable Extra 2 parameters
If you are not using mode all, and that you pass 1 as argument, scramble will
keep your steps synchronized. For instance, the scramble pitch 1 message will
reorder the pitches, but the other parameters will follow.
setall value [list] The word setall, followed by a number, will assign that value to every layer in the
currently targeted sequence when the the live.step object is in display mode. An
optional first argument specifying a specific layer (i.e. setall velocity 85) can be
used to set all values in a specify layer. When the editlooponly attribute is set to 1,
the setall message will only be applied to indices inside the loop selection.
settimeshift time-shift [float] The word settimeshift, followed by a positive or negative number that specifies an
offset, will move to the relative position from the current step in the sequence and
first that step (e.g., sending the message settimeshift -1 when the current step
number is 3 will cause the content of step 2 to fire.
sort parameter [symbol] The word sort will sort the step values of the sequence based on the target_seq
keep-step-sync [int] and mode attributes. For instance, if the mode attribute is set to velocity, the sort
direction [int] message will only sort the velocity values of the currently specified sequence (or all
the sequences if the target_seq attribute is set to zero).
Optional arguments may be used with the sort message to specify behavior,
synchronization, and direction of sortint. The can be used to set the parameters to
be sorted without having to use the mode attribute. The optional arguments are:
all: Sort the order of all parameters
pitch: Sort the order of the pitches
velocity: Sort the order of the velocities
duration: Sort the order of the durations
extra1: Sort the order of all user-definable Extra 1 parameters
extra2: Sort the order of all user-definable Extra 2 parameters
The first integer argument specifies whether or not to keep the step values
synchronized - it only works if the mode attribute is not set to all. For instance,
the message sort pitch 1 will reorder the steps based on the pitch, but the
velocity, duration and user-definable extra1 and extra2 values associated to the
pitch will be maintained. An optional second integer argument can be used to set
the sorting order:
1: Ascending (the default) -1: Descending.
step index [int] The word step, followed by a list of three integers, sets the values of a specific
midi-note [int] step. The required arguments are:
velocity [int] the index (index numbering starts at 1)
duration [int] the MIDI note number (0-127)
the note velocity (0-127)
the duration (30, 60, 120, 240, 480, 960, 1920, 3840 ticks)
velocity start-index/values [list] The word velocity, followed by an integer that specifies a starting index into a
sequence (index numbering starts with 1) and a list of values, will set the velocity
values for the current sequence specified by the target_seq attribute.
up parameter [symbol] The word up will increase the values of the sequence based on the target_seq and
mode attributes. For instance, if the mode attribute is set to velocity, the up
message will only increase the velocity of the currently specified sequence (or all
the sequences if the target_seq attribute is set to zero).
An optional argument may be used with the up message to specify the parameters
to be increased without having to use the mode attribute. The optional arguments
are:
all: Increase all parameters
pitch: Transpose pitches upward
velocity: Increase velocities
duration: Increase durations
extra1: Increase the value of all user-definable Extra 1 parameters
extra2: Increase the value of all user-definable Extra 2 parameters
zoom low-pitch [float] Sets the zoom points of the currently specified sequence.
high-pitch [float]
zoom_fit The word zoom_in will cause the currently displayed pitch range of the live.step
object to adjust so that the highest and lowest note values become the upper and
lower limits of the display.
zoom_in The word zoom_in will cause the current pitch range of the live.step object
display to decrease by a factor of a fifth (7 steps) at the top and bottom, resulting
in a "zoom in" effect.
zoom_out The word zoom_out will cause the current pitch range of the live.step object
display to increase by a factor of a fifth (7 steps) at the top and bottom, resulting
in a "zoom out" effect.

Attributes
Name Type g/s Description
autoscroll int When set to one, this attribute lets you expand the scrolling dragging the cursor to
def.:1 the edge of the display or to drag a selected pitch beyond the range of the current
visual display.
bgcolor float Sets the background color of the live.step object in RGBA format.
bgcolor2 float Sets the second background color of the live.step object in RGBA format.
bgrulercolor float Sets the ruler background color of the live.step object in RGBA format.
bgunitcolor float Sets the unit background color of the live.step object in RGBA format.
blackkeycolor float Sets the color for the upper (black) keys in RGBA format.
bordercolor float Sets the border color of the live.step object in RGBA format.
display_seq int Sets the sequence to be displayed (index numbering starts at 1).
def.:1
duration_active int Activates display of the Duration layer
def.:1
editlooponly int When the editlooponly attribute is set to 1, the edit messages (up, down, left,
def.:0 right, random, scramble, sort) are only applied to indices inside the loop
selection.
extra1_active int Activates display of the user-definable Extra 1 layer
def.:1
extra1_max int Sets the maximum value for the user-definable Extra 1 layer.
def.:127
extra1_min int Sets the minimum value for the user-definable Extra 1 layer
def.:0
extra2_active int Activates display of the user-definable Extra 2 layer
def.:1
extra2_max int Sets the maximum value for the user-definable Extra 2 layer
def.:127
extra2_min int Sets the minimum value for the user-definable Extra 2 layer
def.:0
extra_thickness float Sets the thickness of the vertical bars displayed in the Extra 1 layer
def.:0.5
hbgcolor float Sets the highlight background color of the live.step object in RGBA format.
loopbordercolor float Sets the loop border color of the live.step object in RGBA format.
loopruler int Toggles the display of the loop ruler.
def.:1
mode int An integer or symbol can be used to set the information display mode of the
def.:0 live.step object.
'All' = Display all values
'Pitch' = Display pitch
'Velocity' = Display velocity
'Duration' = Display duration
'Extra1' = Display extra1
'Extra2' = Display extra2
nseq int Defines the number of sequences.
def.:1
pitch_active int Activates display of the Pitch layer
def.:1
stepcolor float Sets the step color of the live.step object in RGBA format.
stepcolor2 float Sets the second step color of the live.step object in RGBA format.
target_seq int Defines the target sequence (index numbering starts at 1).
textcolor float Sets the text color of the live.step object in RGBA format.
unitruler int Toggles the display of the unit ruler.
def.:1
usestepcolor2 int Toggles the use of a second step color in the display
def.:1
velocity_active int Activates display of the Velocity layer
def.:1
whitekeycolor float Sets the color for the lower level (white) keys in RGBA format.

Information about attributes available for Parameter-aware objects

Information for box attributes common to all objects

Output
anything:
Out the fourth outlet: The output in response to dumpout messages used to query the live.step object.
int:
Out the third outlet: Mouseover information.
Out the fifth outlet: Sequence index out.
list:
Out the leftmost outlet: Step values.
Out the second outlet: Current loop points.

Examples

See Also
Name Description
live.grid A UI grid of steps, with constraints and directions
multislider Display data as sliders or a scrolling display
matrixctrl Matrix switch control
live.tab
A user interface tab/multiple button object

Description
live.tab is used to create multiple-button and multi-column displays and interfaces.

Arguments
None.

Messages
bang Sends the current item out the outlets.
int input [int] The number specifies a tab item to be sent out, and causes live.tab to display that
item. The items are numbered starting at 0.
float input [float] The number specifies a tab item to be sent out, and causes live.tab to display that
item. The items are numbered starting at 0.
assign assign-input [float] The word assign, followed by a floating point value, causes that value to be stored
and displayed and sent out the live.tab object's outlet. If the Parameter Visibility
attribute is set to Stored Only, the assign message will not add the new value to
the Live applications undo chain.
init Restore and output the initial value.
(mouse) Clicking on a tab button will highlight and set the selection and send the tab text
out the second outlet and the index out the first outlet.
outputvalue Sends the current value out the outlet.
set tab index [float] The word set, followed by a number, specifies a menu item to be displayed by
live.tab without triggering any output.
setsymbol tab item [list] The word setsymbol, followed by a symbol that specifies a tab item, causes
live.tab to display that item, but does not cause any output.
symbol tab item [list] The word symbol, followed by a symbol that specifies a tab item, causes live.tab
to display that item and send the tab text out the second outlet and the index out
the first outlet.
rawfloat input [float] A raw normalized value (between 0. and 1.) received in the inlet is converted to a
real value, stored, displayed by live.tab, and the current value is sent out the
outlet.

Attributes
Name Type g/s Description
active int Toggles the object's active state. When active is set to 0, the mouse action does
def.:1 not cause output and the inactive colors are used.
activebgcolor float Sets the background color off displayed when the active attribute is set to 1.
activebgoncolor float Sets the background color on displayed when the active attribute is set to 1.
bgcolor float Sets the background color off displayed when the active attribute is set to 0.
bgoncolor float Sets the background color on displayed when the active attribute is set to 0.
blinktime int Sets the blink time in milliseconds.
def.:150
bordercolor float Sets the display color for the live.tab object's border in RGBA format.
button int Toggles button mode for the live.tab object.
def.:0
focusbordercolor float Sets the border color in RGBA format to be used when the live.tab object has the
focus.
mode int Sets the text tab layout mode.
def.:0 'Equal Spaced' = TEXT_HERE
'Proportional' = Proportional spacing
multiline int Toggles allowing multiple lines of text in a tab. When set, you can resize the object
def.:1 to create multicoloum displays.
pictures symbol Sets the paths for pictures used when the usepicture attribute is set to 1. Bitmap
images such as PNG or vectorized images (SVG) can be used.
spacing_x float Sets the horizontal spacing for the live.tab object in pixels.
def.:6.
spacing_y float Sets the vertical spacing for the live.tab object in pixels.
def.:6.
textcolor float Sets the display color for the live.tab object's text in RGBA format.
textoncolor float Sets the display color for the live.tab object's text when the tab is on in RGBA
format.
usepicture int Toggles the use of the pictures instead of text display. Note that you need to
def.:0 provide enough pictures by setting the pictures attribute properly.

Information about attributes available for Parameter-aware objects

Information for box attributes common to all objects

Examples

See Also
Name Description
live.text A user interface button/toggle
live.toggle Switch between off and on (0 and 1)
tab Select values with tabs or multiple buttons
live.text
A user interface button/toggle

Description
live.text object is a user interface object used to create buttons and toggles.

Arguments
None.

Messages
bang A bang message will toggle the state of the object. If it is off, it will switch on and
output a 1. If it is on, it will switch off and output a 0.
int input [int] In the toggle mode, any non-zero number will toggle the button to the "on"
position, send the button text out the middle outlet and send a 1 out the left outlet.
A zero sets the toggle to the "off" position, sends the button text out the middle
outlet and sends a 0 out the left outlet.
float input [float] Converted to int.
assign assign-input [float] The word assign, followed by a floating point value, causes that value to be stored
and displayed and sent out the live.text object's outlet. If the Parameter Visibility
attribute is set to Stored Only, the assign message will not add the new value to
the Live applications undo chain.
init Restore and output the initial value.
(mouse) In button mode, a mouse click on live.text highlights it for as long as the mouse
is held down, sending the text out the second outlet and a bang message out the
left outlet.
In toggle mode, a mouse click behaves the same as a live.toggle. When the
mouse is clicked, the live.text object will send a 1 out the left outlet if the cursor is
inside of the live.text object's rectangle, and a 0 if it is not. The button text is also
sent out the second outlet on mouse click.
outputvalue Sends the current value out the outlet.
set set-input [float] In the toggle mode, the set messages toggles the "on" or "off" state without
sending anything out the outlets. The word set, followed by any non-zero number,
sets toggle to on. The message set 0 sets it to "off".
setsymbol button-text-item [list] In the toggle mode, the word setsymbol, followed by a symbol that specifies a
button text item, causes live.text to display that symbol and act as though the
object were toggled to that state.
symbol button-text-item [list] In the toggle mode, the word symbol, followed by a symbol that specifies a
button text item, causes live.text to display that symbol and act as though the
object were toggled to that state.
rawfloat input-value [float] A raw normalized value (between 0. and 1.) received in the inlet is converted to a
real value, and then functions like any other received int value in toggle mode.

Attributes
Name Type g/s Description
active int Toggles the object's active mode. When active is set to 0, the mouse action does
def.:1 not cause output and the inactive colors are used.
activebgcolor float Sets the background color off displayed when the active attribute is set to 1.
activebgoncolor float Sets the background color on displayed when the active attribute is set to 1.
activetextcolor float Sets the display color for the live.text object's text in RGBA format.
activetextoncolor float Sets the display color for the live.text object's text when it is on.
appearance int Defines the display style. The options are:
def.:0
0: Default. The text appears with the boundaries of the text box.
1: Label. The text box appears as a square button, with the text appearing to the
right.
'Default' = TEXT_HERE
'Label' = TEXT_HERE
automation symbol Sets the automation "off" label that will appear in Live.
def.:val1
automationon symbol Sets the automation on label that will appear in Live.
def.:val2
bgcolor float Sets the background color "off" displayed when the active attribute is set to 0.
bgoncolor float Sets the background color on displayed when the active attribute is set to 0.
bordercolor float Sets the display color for the live.text object's border in RGBA format.
focusbordercolor float Sets the display color for the live.text object's border in RGBA format.
mode int Sets the button mode. Button modes are:
def.:1
0: Button mode
1: Toggle (switch) mode
'Button' = TEXT_HERE
'Toggle' = TEXT_HERE
pictures symbol Sets the paths for pictures used when the usepicture attribute is set to 1. Bitmap
def.:<none> images such as PNG or vectorized images (SVG) can be used.
<none>
text symbol Sets the button label when the button is in the off state.
def.:A
textcolor float Sets the display color for the live.text object's text when the active attribute is set
to 0.
texton symbol Sets the button label when the button is in the "on" state.
def.:B
transition int The parameter automation of live.text stores 0 and 1 values. The transition
def.:0 attribute specifies when a bang will be sent to the outlet.
'Zero->One' = TEXT_HERE
'One->Zero' = TEXT_HERE
'Both' = TEXT_HERE
usepicture int Toggles the use of pictures instead of text for display. Note that you need to
def.:0 provide enough pictures by setting the pictures attribute properly.

Information about attributes available for Parameter-aware objects

Information for box attributes common to all objects

Examples
See Also
Name Description
live.button Flash on any message, send a bang
live.tab A user interface tab/multiple button object
live.toggle Switch between off and on (0 and 1)
textbutton A user interface button/toggle
live.thisdevice
Send a bang automatically when a Max Device is loaded, report device state

Description
live.thisdevice reports three pieces of information about your Max Device. A bang message is automatically sent from the left
outlet when the Max Device is opened and completely initialized, or when the containing patcher is part of another file that is
opened. Additionally, a bang will be reported every time a new preset is loaded or the device is saved (and thus reloaded within
the Live application). A 1 or 0 will be sent from the middle outlet when the Device is enabled or disabled, respectively. A 1 or 0
will be sent from the right outlet when preview mode for the Device is enabled or disabled, respectively. Used within Max,
live.thisdevice functions essentially like the loadbang object. The middle and right outlets are inactive in this case.

Arguments
None.

Messages
bang Sending a bang message to a live.thisdevice object causes it to output a bang
message from the leftmost outlet.
(mouse) Double-clicking on a live.thisdevice object causes it to output a bang message
from the leftmost outlet.
getstate Sending a getstate message to a live.thisdevice object causes it to output the Max
Device state from the rightmost outlet.
loadbang Same as bang.

Information for box attributes common to all objects

Examples

See Also
Name Description
active Send 1 when patcher window is active, 0 when inactive
button Blink and send a bang
closebang Send a bang on close
freebang Send a bang when a patcher is freed
loadbang Send a bang when a patcher is loaded
loadmess Send a message when a patch is loaded
thispatcher Send messages to a patcher
live.toggle
Switch between off and on (0 and 1)

Description
live.toggle creates a toggle switch that outputs a 0 turned off and a 1 when turned on.

Arguments
None.

Messages
bang A bang message will toggle the state of the object. If it is off, it will switch on and
output a 1. If it is on, it will switch off and output a 0.
int input [int] Switches the live.toggle on (1) or off (0) and send the value to the outlet.
float input [float] Switches the live.toggle on (1) or off (0) and send the value to the outlet.
assign assign-input [float] The word assign, followed by a floating point value, causes that value to be stored
and displayed and sent out the live.toggle object's outlet. If the Parameter
Visibility attribute is set to Stored Only, the assign message will not add the new
value to the Live applications undo chain.
init Restore and output the initial value.
(mouse) A mouse click on the live.toggle object switches the object on if it is off, or off if it
is on.
outputvalue Sends the current value out the outlet.
set set-input [float] Switches the live.toggle on or off without causing any output.

Attributes
Name Type g/s Description
active int Toggles the object's active mode. When active is set to 0, the mouse action does
def.:1 not cause output and the inactive colors are used.
activebgcolor float Sets the background color displayed for the toggle in the off state when the active
attribute is set to 1.
activebgoncolor float Sets the background color displayed for the toggle in the on state when the active
attribute is set to 1.
bgcolor float Sets the background color off displayed for the toggle in the off state when the
active attribute is set to 0.
bgoncolor float Sets the background color on displayed when the active attribute is set to 0.
bordercolor float Sets the display color for the live.toggle object's border in RGBA format.
focusbordercolor float Sets the display color for the live.toggle object's border when the object has focus
in RGBA format.

Information about attributes available for Parameter-aware objects

Information for box attributes common to all objects

Examples
See Also
Name Description
live.button Flash on any message, send a bang
live.tab A user interface tab/multiple button object
live.text A user interface button/toggle
toggle Switch between off and on (0/1)
Live API Overview
Basic information about the Live API and links to further readings.

This document refers to Ableton Live version 8.2.2 or newer.

Introduction
Besides building new instruments and effects to be used in Live, Max For Live also allows to access Live itself, its tracks, clips,
devices and hardware control surfaces. This chapter defines some basic terms used throughout the whole Live API and introduces
the Max objects representing the Live API.

Live Object Model


The accessible parts of Live are represented by a hierarchy of objects called the Live Object Model (LOM) .

The model describes the hierarchy of objects inside Live, as seen from the Max devices. There are various classes of objects in the
model, like Track or Clip. For certain objects only a single instance exists, for other multiple instances are hold in lists. The Live
Object Model reference page shows how to navigate from a number of root objects down a path to the particular object of
interest, and what to do with it.

Object Path
Live objects are accessed using paths according to the Live Object Model. For example, the first clip in the third track can be
accessed by the path live_set tracks 2 clip_slots 0 clip. Alternatively, it can be accessed via live_set scenes 0 clip_slots 2
clip. Or, if the clip is shown in the detail view, via live_set view detail_clip.

As you can see, different paths can point to the same Live object. One of these paths is the canonical path .

When communicating with the Live API, no quotes are used in paths. List indexes start with 0.

When navigating through the object model, besides these absolute paths, relative paths can be used. These determine a subpath
beginning at the current position in the object hierarchy.

Root objects
(Absolute) paths to all objects start with one of live_app, live_set, control_surfaces N or this_device. These are the root objects.

Canonical Path
Different paths can lead to the same object. live_set view selected_track and live_set tracks 3 are the same object if the fourth
track is selected.

Each object has a unique canonical path, live_set tracks 3 in this case. The canonical path is send out of live.object in reponse to
getpath. In the Live Object Model, the canonical path is shown by bold connectors.

Canonical Parent
Additionally to what is described in the LOM, all objects have a canonical_parent child which is used by Live to determine the
canonical path of an object. The canonical parents are get-only and useful for patching, too. For example, goto this_device
canonical_parent is the perfect way to get the own track object.

Object ids
An object id identifies a particular object instance in Live like a track or a clip.

To get an id, a live.path object must be used to navigate to the Live object. When a live.path object sees this Live object the first
time, an id is assigned to it.
The id is only valid inside the device with the live.path and remains unchanged as long the object exists. If the object is moved in
Live, its id usually remains unchanged. There may be exceptions if the movement is implemented as a delete/create sequence,
though. When an object is deleted and a new object is created at its place, it will get a new id.

An id is never reused in the scope of a Max device. Ids are not stored. Therefore, after loading a saved device, the live.path object
must navigate to the object again.

An object id consists of the word id and a number, separated by a space, like id 3. id 0 refers to no object . In Max terms it's a list
of the symbol id and an integer.

Object Types
Each Live object is of a particular object type (or Class ). This object type determines what kind of object that is and what
children, properties and functions it has. The object types are described in detail in the Live Object Model.

Children
Live objects have children identified by name. The names of the possible children of some names point to single objects, others to
a list of objects. The child name also determines which object type you can expect to find there.

List names are in plural, whereas single child names are in singular. Lists may be empty. Sending getcount name to live.path
allows to find out how many children are in the list.

Single children names may point to no object, in which case you get id 0 if you navigate there or send get name to live.object.

Most children can be monitored using live.observer.

Properties
Live objects have properties which describe it's actual state. Properties are accessed by sending get and set messages to
live.object. Not all properties can be set, though.

Many properties can be monitored using live.observer.

Functions
Many Live objects have functions which can be called by the respective message to live.object. A function call may have
parameters (a list of values) and a single return value, which is sent to the outlet of live.object.

Datatypes
Properties and function parameters or return values used in the Live Object Model and by the Max objects to access the Live API
have one of the following data types:

Datatype Description
bool 0 for false and 1 for true
symbol a string with unicode character set
use double quotes in message boxes to create symbols with spaces
double quotes in symbols are to be prefixed by backslashes
backslashes are included as double backslashes
example: alpha beta \"gamma\" \\x\\ creates the symbol alpha beta "gamma" \x\
int a 32 bit signed integer
float a 32 bit float value
double a 64 bit float value (maily used for timing values)
beats song beat time counted in quarter notes, represented as double
time song time in seconds, represented as double
time = beats * 60 / tempo (in bpm)
sometimes the time is given in milliseconds (ms)
list a space separated list of the types above

Notifications
When Max devices need to know the state of the Live application and its objects, they can actively poll the state by navigating
through the object hierarchy and getting object properties or calling functions.

But changes happen in Live while the Max device is passive. To allow the Max device to react on these changes in Live,
notifications are sent from Live to the Max device. Notifications are spontaneous in the sense that messages are sent to outlets
spontaneously, not in response to a message received at an inlet.

The notifications include object ids sent when the Live object at a certain path changes and values sent when a property changes.

Note: changes to a Live Set and its contents are not possible from a notification. The error message in the Max Window is
'Changes cannot be triggered by notifications'. In many cases putting a deferlow between the notification outlet and the
actual change helps to resolve the issue.

Max Objects
Four Max objects interact in a certain way to allow Max devices to access the Live objects.

Max object Purpose


live.path select objects in the Live object hierarchy
live.object get and set properties and children, call functions
live.observer monitor properties and children
live.remote~ control Live device parameters in real time

The following patch shows the typical interconnections between the Live API objects. live.path is sending object ids out of its
leftmost outlet connected to the rightmost inlet of live.object, live.observer and live.remote~. This causes these objects to
operate on the object selected by live.path.

live.path
live.path objects are used to navigate to the Live objects on which live.object, live.observer and live.remote~ are supposed to
operate. For this purpose, navigation messages like goto live_set are sent to live.path, which replies by sending an object id to
the left outlet.

live.path can also observe the given path, and when the object at this path changes, its id is sent to the middle outlet. This is
particularly useful for paths like live_set view selected_track which point to the currently selected track.

live.object
live.object is used to operate on a particular Live object which id has been received from live.path. It allows to get or set
properties of the Live object and to call its functions with parameters.

live.observer
live.observer monitors the state of a particular Live object which id has been received from live.path. After telling live.observer
which property to observe it recognizes all changes of the property and sends the current values to its left outlet.

live.remote~
live.remote~ receives the id of a DeviceParameter object from live.path and then allows to feed this parameter with new values
by sending them into the left inlet, in realtime, without effects on the undo history or the parameter automation, which is
deactivated.

DeviceParameter objects are children of Live devices, including Max devices, and also of tracks, like volume and pan.

LiveAPI
The LiveAPI Javascript object is available in code written for the js object. It provides a succinct means of communicating with the
Live API functions from JavaScript, incorporating the functionality provided by the live.path, live.object and live.observer
objects.
LOM - The Live Object Model
What objects you find behind the Live API and what their structure, properties and functions are.

Introduction
The Live Object Model lists a number of Live object classes with their properties and functions as well as their parent-child relations through which a hierarchy is formed. Please refer
to the Live API overview chapter for definitions of the basic Live API terms and a list of the Max objects used to access it.

This document refers to Ableton Live version 8.1b7.

Object Model Overview

Click on the classes to navigate to their description.

Application
This class represents the Live application. It is reachable by the root path live_app.

Canonical path
live_app
Children
Name Type Access Description
view Application.View get
Properties
None
Functions
Name Description
get_document Returns: the current live set.
get_major_version Returns: the 8 in Live 8.1.5.
get_minor_version Returns: the 1 in Live 8.1.5.
get_bugfix_version Returns: the 5 in Live 8.1.5.

Application.View
This class represents the aspects of the Live application related to viewing the application.

Canonical path
live_app view
Children
None
Properties
None
Functions
Name Description
available_main_views Returns: view names [list of symbols]. This is a constant list of view names to be used
for the other functions: Browser Arranger Session Detail Detail/Clip
Detail/DeviceChain.
focus_view Parameter: view_name
Shows named view and focuses on it
hide_view Parameter: view_name
is_view_visible Parameter: view_name
Returns: [bool]
scroll_view Parameters: direction view_name modifier_pressed
direction [int] is 0 for up, 1 for down, 2 for left, 3 for right
modifier_pressed [bool] has no effect at the moment
Not all views are scrollable, and not in all directions. Currently, only the Arranger,
Detail/Clip, and Detail/DeviceChain views can be scrolled.
You can also pass an empty view_name "", which refers to the arranger or the session
(whichever view is visible).
show_view Parameter: view_name
zoom_view Parameter: direction view_name modifier_pressed
direction [int] is 0 for up, 1 for down, 2 for left, 3 for right
modifier_pressed [bool] if 0 and view identifier results in arranger and direction is
up or down, then only the hight of the highlighted track is changed, otherwise the
height of all tracks is changed
Not all views can be zoomed, only arranger and detail clip.

Song
This class represents a Live set. The current live set is reachable by the root path live_set.

Canonical path
live_set
Children
Name Type Access Description
tracks list of Track get, observe
return_tracks list of Track get, observe
master_track Track get
visible_tracks list of Track get, observe A track is visible if its not a subtrack folded in. Hiding tracks be scrolling them out of
view is something completely else.
scenes list of Scene get, observe
cue_points list of CuePoint get, observe Cue points are the markers in the arranger to which you can jump.
appointed_device Device get, observe The appointed device is the one used by control surfaces unless they control
themselves which device to use. it is marked by a blue hand.
view Song.View get
Properties
Name Type Access Description
back_to_arranger bool get, set, observe Indicates the current state of the back to arrangement button located in the Live
application's transport bar: 1=highlighted. This button is used to indicate that the
current state of the playback differs from what is stored in the arrangement.
can_jump_to_next_cue bool get, observe The reason why it can't jump (0=cannot jump) is that there is no cue point to the right
of the current, or none at all.
can_jump_to_prev_cue bool get, observe The reason why it can't jump (0=cannot jump) is that there is no cue point to the left
of the current, or none at all.
can_redo bool get 1=there is something in the history to redo.
can_undo bool get 1=there is something in the history to undo.
clip_trigger_quantization int get, set, observe Reflects the quantization setting in the transport bar.
0: None
1: 8 Bars
2: 4 Bars
3: 2 Bars
4: 1 Bar
5: 1/2
6: 1/2T
7: 1/4
8: 1/4T
9: 1/8
10: 1/8T
11: 1/16
12: 1/16T
13: 1/32
current_song_time float get, set, observe Live set play position in beats.
exclusive_arm bool get Current status (1=set) of the exclusive arm option set in the record preferences.
exclusive_solo bool get Current status (1=set) of the exclusive solo option set in the record preferences.
groove_amount float get, set, observe The groove amount from the current set's groove pool (0. - 1.0).
is_playing bool get, set, observe 1=the Live transport is running. Can be used to stop or start the Live transport.
last_event_time float get The beat time of the last event (i.e. automation breakpoint, clip end, cue point, loop
end) in the arranger.
loop bool get, set, observe 1=arranger loop is active.
loop_length float get, set, observe Arranger loop length in beats.
loop_start float get, set, observe Arranger loop start in beats.
metronome bool get, set, observe 1=the metronome switch in the transport bar is turned on.
midi_recording_quantization int get, set, observe Reflects the current selection of the Edit->Record Quantization menu.
0: None
1: 1/4
2: 1/8
3: 1/8T
4: 1/8 + 1/8T
5: 1/16
6: 1/16T
7: 1/16 + 1/16T
8:1/32
nudge_down bool get, set, observe The status (1=pressed) of the nudge down button in the transport bar.
nudge_up bool get, set, observe The status (1=pressed) of the nudge up button in the transport bar.
overdub bool get, set, observe 1=overdub flag in transport bar is highlighted.
punch_in bool get, set, observe 1=the punch in switch in transport is highlighted.
punch_out bool get, set, observe 1=the punch out switch in transport is highlighted.
record_mode bool get, set, observe 1=global record is enabled (record switch in transport is red).
select_on_launch bool get Current status (1=set) of the respective option set in the launch preferences.
signature_denominator int get, set, observe
signature_numerator int get, set, observe
song_length float get, observe A little more than last_event_time, in beats.
tempo float get, set, observe Current tempo of the Live set in bpm, 20.0 ... 999.0. The tempo may be automated, so
it can change depending on the current song time.

Functions
Name Description
continue_playing From the current playback position.
get_beats_loop_length Returns: bars.beats.sixteenths.ticks [symbol]
The arranger loop length.
get_beats_loop_start Returns: bars.beats.sixteenths.ticks [symbol]
The arranger loop start.
get_current_beats_song_time Returns: bars.beats.sixteenths.ticks [symbol]
The current arranger playback position.
get_current_smpte_song_time Parameter: format
format [int] is the time code type to be returned
0: the frames position shows the milliseconds
1: Smpte24
2: Smpte25
3: Smpte30
4: Smpte30Drop
5: Smpte29
Returns: hours:min:sec:frames [symbol]
The current arranger playback position.
is_cue_point_selected Returns: bool 1=the current arranger playback position is at a cue point
jump_by Parameter: beats
beats [double] is the amount to jump relatively to the current position
jump_to_next_cue Jumps to the right, if possible.
jump_to_prev_cue Jumps to the left, if possible.
play_selection Does nothing if no selection is set in arranger.
redo Causes the Live application to redo the last operation.
scrub_by Parameter: beats
beats [double] the amount to scrub relative to the current arranger playback position
Same as jump_by, at the moment.
set_or_delete_cue Toggle cue point at current arranger playback position.
start_playing
stop_all_clips
stop_playing
tap_tempo Same as tapping the tempo field in the transport bar. The new tempo is calculated
based on the time between subsequent calls of this function.
undo Causes the Live application to undo the last operation.

Song.View
This class represents the view aspects of a Live document: the session and arranger views.

Canonical path
live_set view
Children
Name Type Access Description
detail_clip Clip get, set, observe The clip currently displayed in the Live applications detail view.
highlighted_clip_slot ClipSlot get, set The slot highlighted in the session view.
selected_parameter DeviceParameter get, observe The selected parameter, or "id 0"
selected_scene Scene get, set, observe
selected_track Track get, set, observe
Properties
Name Type Access Description
draw_mode bool get, set, observe Reflects the state of the envelope/automation draw mode switch in transport bar, as
toggled with Cmd/Ctrl-B.
0=breakpoint editing (shows arrow), 1=drawing (shows pencil)
follow_song bool get, set, observe Reflects the state of the follow switch in transport bar as toggled with Cmd/Ctrl-F.
0=don't follow playback position, 1=follow playback position

Functions
Name Description
select_device Parameter: id NN
Selects the given device object in its track.
You may obtain the id using a live.path or by using get devices on a track, for
example.
The track containing the device will not be shown automatically, and the device gets
the appointed device (blue hand) only if its track is selected.

Track
This class represents a track in Live. It can be either an audio track, a MIDI track, a return track or the master track. The master track and at least one Audio or MIDI track will be
always present. Return tracks are optional.

Not all properties are supported by all types of tracks. The properties are marked accordingly.

Canonical path
live_set tracks N
Children
Name Type Access Description
clip_slots list of ClipSlot get, observe
devices list of Device get, observe Includes mixer device.
mixer_device MixerDevice get
view Track.View get
Properties
Name Type Access Description
arm bool get, set, observe 1=track is armed for recording. [not in return/master tracks]
can_be_armed bool get Is 0 for return and master tracks.
color int get, set, observe The RGB value of the track's color in the form 0x00rrggbb or (2^16 * red) + (2^8) *
green + blue, where red, green and blue are values from 0 (dark) to 255 (light).

When setting the RGB value, the nearest color from the Track color chooser is taken.
current_input_routing symbol get, set, observe As all other routings, reflects the string shown in the routing selector.
current_input_sub_routing symbol get, set, observe Doesn't send any output if the selector has no entries.
current_monitoring_state int get, set, observe 0=In 1=Auto 2=Off [not in return/master tracks]
current_output_routing symbol get, set, observe
current_output_sub_routing symbol get, set, observe Doesn't send any output if the selector has no entries.
fired_slot_index int get, observe Reflects the blinking clip slot.
-1=no slot fired, -2=track stop button fired
First clip slot has index 0.
[not in return/master tracks]
fold_state int get, set 0=subtracks are visible 1=track is folded and subtracks hidden
[only available if is_foldable is 1]
has_audio_input bool get 1 for audio tracks.
has_audio_output bool get 1 for audio tracks and MIDI tracks with instrument.
has_midi_input bool get 1 for MIDI tracks.
has_midi_output bool get 1 for MIDI tracks with no instruments and no audio effects.
input_meter_level float get, observe Hold peak value of input meters of audio and MIDI tracks, 0.0 ... 1.0. For audio tracks
it is the maximum of the left and right channels. The hold time is 1 second.
input_meter_left float get, observe Smoothed momentary peak value of left channel input meter, 0.0 to 1.0. For tracks
with audio output only. This value corresponds to the meters shown in Live. Please
take into account that the left/right audio meters put a significant load onto the GUI
part of Live.
input_meter_right float get, observe Smoothed momentary peak value of right channel input meter, 0.0 to 1.0. For tracks
with audio output only. This value corresponds to the meters shown in Live.
input_routings list of symbols get Available input routings. [not in master track]
input_sub_routings list of symbols get Available sub routings for the currently selected input routing. Does not output
anything if no entries are available. [not in master track]
is_foldable bool get 1 if track can be (un)folded to hide resp. reveal the contained tracks. This is currently
the case for group tracks. Instrument and drum racks return 0 although they can be
openend/closed. This will be fixed in a later release.
is_part_of_selection bool get
is_visible bool get 0=track is hidden in a folded group track.
mute bool get, set, observe [not in master track]
name symbol get, set, observe As shown in track header.
output_meter_level float get, observe Hold peak value of output meters of audio and MIDI tracks, 0.0 ... 1.0. For audio
tracks it is the maximum of the left and right channels. The hold time is 1 second.
output_meter_left float get, observe Smoothed momentary peak value of left channel output meter, 0.0 to 1.0. For tracks
with audio output only. This value corresponds to the meters shown in Live. Please
take into account that the left/right audio meters put a significant load onto the GUI
part of Live.
output_meter_right float get, observe Smoothed momentary peak value of right channel output meter, 0.0 to 1.0. For tracks
with audio output only. This value corresponds to the meters shown in Live.
output_routings list of symbols get Available output routings. [not in master track]
output_sub_routings list of symbols get Available sub routings for the currently selected output routing. Does not output
anything if no entries are available. [not in master track]
playing_slot_index int get, observe First slot has index 0, -1=no clip playing. [not in return/master tracks]
solo bool get, set, observe Remark: when setting this property, the exclusive solo logic is bypassed, so you have to
unsolo the other tracks yourself. [not in master track]

Functions
Name Description
jump_in_running_session_clip Parameter: beats
beats [double] is the amount to jump relatively to the current clip position.
Modify playback position in running session clip, if any.
stop_all_clips Stops all playing and fired clips in this track.

Track.View
Representing the view aspects of a Track.

Canonical path
live_set tracks N view
Children
Name Type Access Description
selected_device Device get, observe The selected device or, in case of multi/group selection, the first selected device.

Properties
Name Type Access Description
is_collapsed bool get, set, observe In arranger view: 1=track collapsed, 0=track opened.

Functions
Name Description
select_instrument Returns: bool 0=there are no devices to select
Selects track instrument or first device, makes it visible and focuses on it.

ClipSlot
This class represents an entry in Lives Session view matrix.

The properties playing_status, is_playing and is_recording are useful for clip slots of group tracks. These are always empty and represent the state of the clips in their subtracks.

Canonical path
live_set tracks N clip_slots M
Children
Name Type Access Description
clip Clip get id 0 if slot is empty

Properties
Name Type Access Description
controls_other_clips bool get, observe 1 for a group track slot that has non-deactivated clips in substracks.
Control of empty clip slots doesn't count.
has_clip bool get, observe
has_stop_button bool get, set, observe If 1, this clip stops its track (or subtracks).
playing_status int get, observe 0=all clips in subtracks stopped or all empty subtracks.
1=at least one clip in subtracks playing.
2= at least one clip in subtracks playing or recording.
Equals 0 if this is not a clip slot of a group track.
is_playing bool get For group tracks: 1 if playing_status != 0, otherwise 0.
For non-group tracks: 0 if empty, otherwise not available.
is_recording bool get For group tracks: 1 if playing_status == 2, otherwise 0.
For non-group tracks: 0 if empty, otherwise not available.
is_triggered bool get, observe 1=clip slot button (start, stop or record) or button of contained clip are blinking.
will_record_on_start bool get 1=clip slot will record on start.

Functions
Name Description
fire Fires the clip or triggers the stop button, if any. Starts recording if slot is empty and
track is armed. Starts recording of armed and empty subtracks if Preferences-
>Launch->Start Recording on Scene Launch is ON.
set_fire_button_state Parameter: state
state [bool]
If the state is set to 1, Live simulates pressing of slot start button until the state is set
to 0 or until the slot is stopped otherwise.
stop Stops playing or recording clips in this track or its subtracks, if any. It doesn't matter
on which slot of the track you call this function.

Clip
This class represents a clip in Live. It can be either an audio clip or a MIDI clip in an arrangement or the session depending on the track (slot) it lives in.

Canonical path
live_set tracks N clip_slots M clip
Properties
Name Type Access Description
color int get, set, observe The RGB value of the clip's color in the form 0x00rrggbb or (2^16 * red) + (2^8) *
green + blue, where red, green and blue are values from 0 (dark) to 255 (light).

When setting the RGB value, the nearest color from the Clip color chooser is taken.
is_audio_clip bool get 0=MIDI clip, 1=audio clip
is_midi_clip bool get The opposite of is_audio_clip.
is_playing bool get, set 1 if clip is playing or recording.
is_recording bool get, observe 1 if clip is recording.
is_triggered bool get 1 if play button is blinking.
playing_status bang observe Observer sends bang when playing/trigger status changes.
length double get For looped clips: loop length in beats. Otherwise its the distance in beats from start to
stop marker. Makes no sense for unwarped audio clips.
loop_start double get, set, observe For looped clips: loop start.
For unlooped clips: clip start.

loop_start and loop_end are in absolute clip beat time of clip is MIDI or warped. The
1.1.1 position has beat time 0. If the clip is unwarped audio, they are given in seconds,
0 is the time of the first sample in the audio material.
loop_end double get, set, observe For looped clips: loop end.
For unlooped clips: clip end.
loop_jump bang observe Bangs when the clip play position is crossing the loop start marker (possibly projected
into the loop).
looping bool get, set, observe 1 if clip is looped. Unwarped audio cannot be looped.
muted bool get, set, observe 1 if muted (i.e. power button of the clip is off).
name symbol get, set, observe
pitch_coarse int get, set, observe Pitch shift in semitones ("Transpose"), -48 ... 48.
Available for audio clips only.
pitch_fine float get, set, observe Extra pitch shift in cents ("Detune"), -50 ... 49.
Available for audio clips only.
playing_position float get, observe Current playing position of the clip.

For MIDI and warped audio clips the value is given in beats of absolute clip time. Zero
beat time of the clip is where 1 is shown in the bar/beat/16th time scale at the top of
the clip view.
For unwarped audio clips, the position is given in seconds, according to the time scale
shown at the bottom of the clip view.

Stopped clips have a playing position of 0.


notes bang observe Observer sends bang when notelist changes.
Available for MIDI clips only.
signature_denominator int get, set, observe
signature_numerator int get, set, observe
warping bool get, set, observe 1 if warp switch is on.
Available for audio clips only.
will_record_on_start bool get 1 for MIDI clips which are in triggered state, with the track armed and overdub on.

Functions
Name Description
fire Same effect as pressing the start button of the clip.
move_playing_pos Parameter: beats
beats [double] relative jump distance in beats. Negative beats jump backwards.
Jumps by given amount, unquantized.
Unwarped audio clips, recording audio clips and recording non-overdub MIDI clips
cannot jump.
set_fire_button_state Parameter: state
state [bool]
If the state is set to 1, Live simulates pressing of clip start button until the state is set
to 0 or until the clip is stopped otherwise.
stop Same effect as pressing the stop button of the track, but only if this clip is actually
playing or recording. It has no effect if this clip is triggered or if another clip in this
track is playing.
deselect_all_notes Call this before replace_selected_notes if you just want to add some notes.
Output:
deselect_all_notes id 0

For MIDI clips only.


get_selected_notes Use this if you want to operate on the selected notes.
Output:
get_selected_notes notes count
get_selected_notes note pitch time duration velocity muted
...
get_selected_notes done

count [int] is the number of note lines to follow.


pitch [int] is the MIDI note number, 0...127, 60 is C3.
time [double] is the note start time in beats of absolute clip time.
duration [double] is the note length in beats.
velocity [int] is the note velocity, 1 ... 127.
muted [bool] is 1 if the note is deactivated.

For MIDI clips only.


replace_selected_notes To replace the notes selected in the clip, send a series of the following function calls to
the Clip.

replace_selected_notes
notes count
note pitch time duration velocity muted
done

The sequence is the same as in get_selected_notes, the parameters are the same too.
The sequence must always be completed, the clip waits for the respective calls even if
intermediate messages are sent. If count is zero, there are no note calls, obviously.

In Live, notes don't overlap, so if the new notes overlap with unselected notes, the
unselected ones are made to fit just like it works when you edit notes manually

An example sequence of calls looks like this:

call replace_selected_notes
call notes 2
call note 60 0.0 0.5 100 0
call note 62 0.5 0.5 64 0
call done

For MIDI clips only.


select_all_notes Use this function, for example, to process all notes of a clip, independently of the
current selection.

Output:
select_all_notes id 0

For MIDI clips only.


Device
This class represents a MIDI or audio device in Live.

Canonical path
live_set tracks N devices M
Canonical path
live_set tracks N devices M chains L devices K
Canonical path
live_set tracks N devices M return_chains L devices K
Children
Name Type Access Description
parameters list of DeviceParameter get, observe Only automatable parameters are accessible. See DeviceParameter to learn how to
modify them.
chains list of Chain get, observe available for device Racks only
return_chains list of Chain get, observe available for device Racks only

Properties
Name Type Access Description
class_name symbol get Live device type such as MidiChord, Operator, Limiter, MxDeviceAudioEffect, or
PluginDevice.
name symbol get, set, observe This is the string shown in the title bar of the device.
can_have_chains bool get 0 for a single device
1 for a device Rack

Functions
Name Description
store_chosen_bank Parameters: script_index bank_index
script_index [int]
bank_index [int]
(This is related to hardware control surfaces and is usually not relevant.)

Chain
This class represents a group device chain in Live.

Canonical path
live_set tracks N devices M chains L
Canonical path
live_set tracks N devices M return_chains L
Canonical path
live_set tracks N devices M chains L devices K chains P ...
Canonical path
live_set tracks N devices M return_chains L devices K chains P ...
Children
Name Type Access Description
devices Device get, observe
mixer_device ChainMixerDevice get
Properties
Name Type Access Description
mute bool get, set, observe 1 = muted (chain activator off)
name unicode get, set, observe
solo bool get, set, observe 1 = soloed (solo switch on)
does not automatically turn solo off in other chains.

ChainMixerDevice
This class represents a chain's mixer device in Live.

Canonical path
live_set tracks N devices M chains L mixer_device
Canonical path
live_set tracks N devices M return_chains L mixer_device
Children
Name Type Access Description
sends list of DeviceParameter get, observe [in audio- and instrument racks only]
for Drum Racks, otherwise empty
panning DeviceParameter get [in audio- and instrument racks only]
volume DeviceParameter get [in audio- and instrument racks only]
chain_activator DeviceParameter get
DeviceParameter
This class represents an (automatable) parameter within a MIDI or audio device. To modify a device parameter, set its value property or send its object id to live.remote~.

Canonical path
live_set tracks N devices M parameters L
Properties
Name Type Access Description
default_value float get Applied when you press the delete key.
is_enabled bool get 1 if the parameter value can be modified directly by the user, by sending set to a
live.object, by automation or by an assigned MIDI message or keystroke.
Parameters can be disabled because they are macro-controlled, because they are
controlled by a live-remote~ object, or because Live thinks that they must not be
moved.
is_quantized bool get 1 for booleans and enums
0 for int/float parameters
Although parameters like MidiPitch.Pitch appear quantized to the user, they actually
have an is_quantized value of 0.
max float get Lowest allowed value.
min float get Largest allowed value.
name symbol get The short parameter name as shown in the (closed) automation chooser .
original_name symbol get For macro parameters, the name before assignment.
value float get, set, observe Linear-to-GUI value between min and max.

MixerDevice
This class represents a mixer device in Live. It provides access to volume, panning and other DeviceParameter objects. See DeviceParameter to learn how to modify them.

Canonical path
live_set tracks N mixer_device
Children
Name Type Access Description
sends list of DeviceParameter get, observe One send per return track.
panning DeviceParameter get
volume DeviceParameter get
cue_volume DeviceParameter get [in master track only]
crossfader DeviceParameter get [in master track only]
track_activator DeviceParameter get
song_tempo DeviceParameter get [in master track only]

Properties
Name Type Access Description
crossfade_assign int get, set, observe 0=A, 1=none, 2=B [not in master track]

Scene
This class represents a series of clip slots in Live's session view matrix.

Canonical path
live_set scenes N
Children
Name Type Access Description
clip_slots list of ClipSlot get, observe
Properties
Name Type Access Description
color int get, set, observe The RGB value of the scene's color in the form 0x00rrggbb or (2^16 * red) + (2^8) *
green + blue, where red, green and blue are values from 0 (dark) to 255 (light).

When setting the RGB value, the nearest color from the Scene color chooser is taken.
is_triggered bool get, observe 1=scene is blinking.
name symbol get, set, observe May contain bpm and signature commands (like "128bpm 3/4").
tempo float get, set Tempo in bpm as found by Live in the name.

Functions
Name Description
fire Fire all clip slots owned by the scene and select this scene.
Starts recording of armed and empty subtracks in these scene if Preferences->Launch-
>Start Recording on Scene Launch is ON.
fire_as_selected Fire the selected scene, then select next scene.
It doesn't matter on which scene you are calling this function.
set_fire_button_state Parameter: state
state [bool]
If the state is set to 1, Live simulates pressing of scene button until the state is set to 0
or until the scene is stopped otherwise.

CuePoint
Represents a 'marker' in the arrangement.

Canonical path
live_set cue_points N
Properties
Name Type Access Description
name symbol get, observe
time float get, observe Arranger position of the marker in beats.

Functions
Name Description
jump Set current arranger playback position to marker, quantized if song is playing.

ControlSurface
The control surfaces are reachable by the root path control_surfaces N .

Canonical path
control_surfaces N

this_device
This root path represents the device containing the live.path object to which the goto this_device message is sent. The class of this object is Device.

Canonical path
live_set tracks N devices M
midiselect
Select and interpret raw MIDI data

Description
midiselect receives raw MIDI bytes and separates the input stream. MIDI data to be selected for output is set using object
attributes. There is a separate data outlet associated with each MIDI data selection attribute. Any input data which is unselected
will be sent out the object's eighth outlet.

Arguments
None.

Messages
bang Clears the midiselect object's memory of any partial MIDI messages received up
to that point.
int byte [list] Numbers received in the inlet (usually from a seq or midiin object) are treated as
bytes of a MIDI message. The status byte and the filtering attributes determine the
outlet which will be used to output the data bytes.
float byte [float] Floating-point numbers received in the inlet are converted to integer values and
treated as bytes of a MIDI message. The status byte and the filtering attributes
determine the outlet which will be used to output the data bytes.

Attributes
Name Type g/s Description
bend int When then bend attribute is set to 1, Pitch Bend information is sent out the 6th
outlet, otherwise the Pitch Bend is sent out the 8th outlet as raw MIDI Data.
ch atom The ch attribute allows you to specify which MIDI input channels will be selected.
While you can choose input from all channels by instantiating the midiselect
object the the argument @ch all, you can also select specific channels (e.g., the
argument @ch 1 3 5 will only select MIDI information on the first, third and fifth
channels).
ctl atom The ctl attribute allows you to specify which MIDI controller messages will be
selected. By default, no controlers are selected. You can select specific controlers
to be filtered (e.g., the argument @ctl 7 9 64 will select the controler 7 (Volume),
9 (Pan), 64 (Sustain Pedal)). To select all controllers, use the argument @ctl all.
To select no controllers (the default), use @ctl none.
note atom The note attribute allows you to specify which MIDI note messages will be
selected. By default, no notes are selected. You can select specific notes to be
filtered (e.g., @note 60 64 67 will select the C4, E4, G4 notes). To select all
notes, use the argument @note all. To select no notes (the default), use @note
none.
pgm int When then pgm attribute is set to 1, Program Change information is sent out the
4th outlet. Otherwise, the Program Change is sent out the 8th outlet as raw MIDI
Data.
poly atom The poly attribute allows you to specify which MIDI poly pressure will be
selected. By default, no poly pressure is selected. You can select specific notes to
be filtered (e.g., @note 60 64 67 will select the C4, E4, G4 notes). To select all
the notes, use the argument @note all. To select no notes (the default) use @note
none.
touch int When then touch attribute is set to 1, After touch data is sent out the 5th outlet.
Otherwise, the Aftertouch is sent out the 8th outlet as raw MIDI Data.

Information for box attributes common to all objects


Output
int: Out 4th outlet: The number is the program change.

Out 5th outlet: The number is the aftertouch (channel pressure) value.

Out 6th outlet: The number is the pitch bend value.

Out 7th outlet: The number is the MIDI channel number.


list: Out leftmost outlet: A note-on message. The first number is a pitch value and the second number is the velocity value.

Out 2nd outlet: A polyphonic key pressure message. The first number is an aftertouch (pressure) value and the second number is
the pitch value (key number).

Out 3rd outlet: A control message. The first number is a control value and the second number is the controller number.

Examples

See Also
Name Description
midiparse Interpret raw MIDI data
borax Report note-on and note-off information
midiformat Prepare data in the form of a MIDI message
midiin Output raw MIDI data
midiinfo Fill a pop-up menu with MIDI device names
Max MIDI Tutorial 3: MIDI Parsing Max MIDI Tutorial 3: MIDI Parsing
Parameter Properties
Properties common to parameter-aware objects.

Description
This refpage lists the roperties common to all parameter-aware objects. You can adjust these values using either the Inspector or
the Parameters window.

Messages
Attributes
Name Type g/s Description

Properties
Name Type Description
Order int Order
Parameter Mode Enable int Parameter Mode Enable (not available from Parameters window)
Link to Scripting Name int When checked, the Scripting Name is linked to the Long Name attribute.
Long Name symbol Long Name
Short Name symbol Sets the short name for the object's visual display. The maximum length
varies according to letter width, but is generally in a range of 5 to 7
characters.
Type int Specifies the data type. The data types used in Max for Live are:

Float
Int
Enum (enumerated list)
Blob

Note: By convention, the Live application uses floating point numbers for
its calculations; the native integer representation is limited to a range of
0-255 (similar to the char data type used in Jitter). When working with Live
UI objects whose integer values are likely to be outside of the 0-255
range, the Type attribute should be set to Float, and the Unit Style
attribute should be set to Int.
Range/Enum list When used with an integer or floating point data type, this field is used to
specify the minimum and maximum values of the parameter.
When used with an enumerated list (Enum) data type, this field contains a
space-delimited list of the enumerated values (if list items contain a space
or special characters, the name should be enclosed in double quotes).
Modulation Mode int Sets the Modulation Mode used by the Live application. The modulation
modes are:

None
Unipolar
Bipolar
Additive
Absolute

Modulation Range list This parameter is only used with the Absolute modulation mode. It
specifies defines the range of values used.
Initial Enable int When checked (set to 1), the UI object can store an initialization value. The
value is set using the Initial attribute (see below).
Initial list Sets the initial value to be stored and used when the Initial Enable
attribute is checked.
Unit Style int Sets the unit style to be used when displaying values. The unit style values
are: Int: displays integer values
Float: displays floating point values
Time: displays time values in milliseconds (ms)
Hertz: displays frequency values (Hz/kHz).
deciBel: displays loudness (dB)
%: Percentage
Pan: displays Left and Right values
Semitones: displays steps (st)
MIDI: displays pitch corresponding to the MIDI note number
Custom: displays custom data type
Native: defaults to floating point values
Custom Units symbol Sets the units to be used with the 'Custom' unit style (see "Unit Style",
above). Custom unit strings may be simple symbols (e.g. "Harmonic(s)"), in
which case the parameter's value will be displayed in its 'Native' display
mode, followed by the symbol (e.g. "12 Harmonic(s)" for an Int-typed
parameter or "12.54 Harmonic(s)" for a Float-typed parameter). For
additional control over the numerical component displayed, a sprintf-style
string may be used (e.g. "%0.2f Bogon(s)", which would display a value
such as ".87 Bogons").
Exponent float When set to a value other than 1., the parameter's input and output values
will be exponentially scaled according to the factor entered in this column.
Steps int The number of steps available between the minimum and maximum values
of a parameter. For instance, if the parameter has a range from 0.-64.,
with Steps set to 4, the user can only set the parameter to 0, 21.33, 42.66
and 64.
Units int The string to use when displaying the parameter's value, if "Unit Style" is
set to 'Custom'. Simple symbols or sprintf-style strings may be used.
Hide From Automation int Toggles hiding the object from the Live application's automation features.
paraminspector
TEXT_HERE

Description
Messages
Attributes
Name Type g/s Description
_parameter_order int Sets the order of recall of this parameter. Lower numbers are recalled first. The
order of recall of parameters with the same order number is undefined.
_parameter_path int This feature is debug-build only, so you will never see this message. If you insist,
this is the moniker path to the parameter object from the top-level of the
patcher hierarchy.
_parameter_linknames int If enabled, the parameter's long name will be linked with the object's scripting
name.
_parameter_longname int The long name of the parameter. This name must be unique per patcher
hierarchy.
_parameter_shortname int The short name of the parameter. This name is used for display in the user
interface.
_parameter_scriptname int The scripting name of the object. This name must be unique per patcher.
_parameter_type int The type of the parameter. In general, this will be Int (0-255), Float (32-bit
float), Enum (enumerated list of values) or Blob (list). Some parameters do not
support certain parameter types, in which case those types will be unavailable in
the drop-down menu.
_parameter_range int The range of the parameter (for Int and Float types), or the members of the
enumerated list (for Enum types). Range in unsupported for Blob parameters.
_parameter_modmode int The modulation mode of the parameter. Available modes depend on the
parameter's type. Modulation is unsupported for Enum and Blob parameter
types.
_parameter_modrange int The modulation range of the parameter, if modulation is enabled.
_parameter_initial_enable int If enabled, the parameter will be set to an initial value (as specified in the Initial
Value column) when the patcher or device is loaded. Turn this on (or off, and
then on again) to store the current value of the parameter as the initial value.
_parameter_initial int The parameter's initial value, if the Initial Value Enabled checkbox is enabled.
_parameter_units symbol The string to use when displaying the parameter's value, if "Unit Style" is set to
'Custom'. Simple symbols or sprintf-style strings may be used.
_parameter_unitstyle int Parameters have a number of built-in display styles for their data. Choose
between them from the drop-down menu.
_parameter_exponent int When set to a value other than 1., the parameter's input and output values will
be exponentially scaled according to the factor entered in this column.
_parameter_steps int The number of steps available between the minimum and maximum values of a
parameter. For instance, if the parameter has a range from 0.-64., with Steps
set to 4, the user can only set the parameter to 0, 21.33, 42.66 and 64.
_parameter_units int If the parameter uses a Custom Unit Style (see Unit Style), the value entered
here determines the units displayed in the user interface.
_parameter_lval int For Int, Float and Enum types, the linear value (without exponential scaling) of
the parameter.
_parameter_mval int The parameter's value.
_parameter_invisible int For automatable parameters (Int, Float, Enum), 'Stored Only' disables
automation, although parameter values are stored in presets. 'Hidden' causes
the parameter's value to be ignored when storing and recalling data. Non-
automatable parameters (Blob) are 'Stored Only' by default, and can be set to
'Hidden', if desired.
_parameter_annotation_name symbol The name displayed as the header of the Info View in Live's user interface. By
default, this is the Long Name of the parameter, but it can be overriden here.
annotation_name symbol The name displayed as the header of the Info View in Live's user interface. By
default, this is the Long Name of the parameter, but it can be overriden here.

Information for box attributes common to all objects

Examples

See Also
Name Description
Max Tutorials - Table of Contents
Basics
Hello Creating objects and connections
Bang! The bang message
Numbers and Lists Types of data in Max
Metro and Toggle Creating automatic actions
Message Ordering Debugging program flow
Simple Math Performing calculations
Numerical User Interfaces Sliders and dials
Keyboard and Mouse Input Working with standard input interfaces
Mouse Drawing Introduction to drawing
Random Drawing Working with random numbers
Procedural Drawing Creating procedural code
Movie Playback Introduction to video playback
Movie Sequencing Working with multiple media files
Encapsulation Patchers inside of patchers
Abstractions Creating libraries of re-usable code
Remote Messaging Sending messages without patchcords
Data Structures and Probability - Working with histograms and lookup tables
Data Collections Using databases
Timing Scheduling events
Presentation Mode Creating a presentation interface for a patcher
Controlling Data Flow Routing messages
Designing Equations Creating complex mathematical statements

MIDI
Basics Getting MIDI input and output
Note Management Generating and managing note events
Parsing Decoding and encoding MIDI streams
Basic Sequencing Playing back MIDI sequence data
Advanced Sequencing Recording and manipulating MIDI sequences

Data
Data Viewing Visualizing data streams
Data Scaling Mapping and scaling numerical information
Gesture Capture Recording and playing back captured input
Cellblock Working with a visual spreadsheet interface
List Processing Manipulation of lists of data

Communications
Human-Interface Devices Working with game controllers
Serial Communication Using standard serial devices
UDP Networking Passing messages over a network

User Interface
Bpatchers Working with inlined patchers
Picture UI Elements Designing user interfaces with custom image elements

Patcher Storage
Pattr Basics Introduction to state management
Autopattr Bindings Advanced patcher storage

JavaScript
Basic JavaScripting Using JavaScript in a patcher
JavaScript Scripting Using JavaScript to create patcher elements
Tasks, Arguments, and Globals Scheduling events and sharing data in JavaScript
Designing User Interfaces Designing graphical user interfaces with JavaScript
Creating objects and connections
Tutorial 1: Hello
Max patcher basics
In this tutorial, we will examine the building blocks of a Max patcher: the object box, the message box and the comment
box. We will also delve into some of the basic editing functions provide by the Max environment.

This brief tour of a simple patcher will show the basic typology of simple programs written in Max: object boxes that
perform command actions within a patch; message boxes that allow us to create messages that can be sent to the objects;
comment boxes that allow us to document our patchers to make them easier to understand.

Looking around
Take a look at the patcher 01mHello. At the top right-hand side of the patch window, we can see three types of boxes.

The first element is the box labeled print. This is an object box, and can be recognized by it's rounded outline and (in this
case) a small "port" at the top left that we call an inlet. Object boxes are the basic logic element of Max they contain
functions that perform some sort of task, and operate like miniature programs within the larger environment.

Just below the object box is a message box (labelled with the word "message"). These are visually different from the object
box they have a gray background, and do not have an outline. Message boxes contain some information (called a message)
that can be sent to objects, and can operate as either commands or control data.

The third box doesnt look like a box at all it appears to be text on the background of patcher window. There is actually a
box around this text, but it is not visible until we decide to edit our patch. This comment box is used to add text for labeling
controls (e.g. "click me"), or for adding comments to your patch to make its operation more apparent to you or anyone you
might share your patch with.

Max programs function by passing messages between objects. Object boxes can be connected to one another, and message
boxes can be used to originate or, in some cases, process messages that are used to control other objects.

Unlocking the patcher


When you first opened this patcher, we found it in a "locked" state meaning that we cannot edit any of the objects or text
in the window. When a patcher is locked, the intention is that it be used as a program. Since the power of Max is that we can
to edit and manipulate these programs to do whatever we like, let's "unlock" this patch and do some editing.

Choose Edit from the View menu. You will see several changes in the patcher. First, the boxes surrounding the comment
boxes are revealed (we told you they were there). Secondly, the message and comment boxes show inlets that were hidden
in the locked state. In addition, ports on the bottom of these boxes are revealed; these are outlets. Finally, many more of the
icons at the bottom of the patcher window are now available for our use.

In addition to the visible changes, we are now free to edit the contents of the window. Double-click inside the object box in
the upper-right that says print; the text is selected, and you can type the name of another object name into that box. Type
"metro" (without the quotes), and click outside the object box to complete the edit. We have now changed the function of
that object (it is now a metro object). You will see the object box change size, and the number of inlets and outlets will
change as the function of the object has changed. We learn Max by building up a vocabulary of objects and how they connect
to other objects (i.e. what messages they understand and transmit).

Double-click inside the message box right below that. Change the message text to anything (for example, type in the word
"anything"), then click outside the box to accept the change. Note that changing the message text does not change the inlets
or outlets, since only the contents (but not the function) of the message box has changed.

Finally, double-click inside the comment box and change its text. Since the comment box has no function other than adding
text to the patch, you are free to put in any text that pleases you.

Interacting with a locked patcher


Lock the patch by unchecking Edit in the View menu. Lets see what happens when we click on each of the box types. In the
upper right-hand corner of the patch, click on the object box (which we changed from print to metro) nothing happens.
Clicking on the message box directly below it, however, changes the background color obviously, something is happening
when we click on that box.
On the left side of our patcher, there are three message boxes connected to a print object with lines (called patchcords).
Click on each of these message boxes in turn, then look at the Max window; you will see that the contents of the message
boxes we clicked are displayed there. This was a result of clicking on the message boxes: they generated a message (the
content of the message box) and sent it down the patchcord to the print object. The print object takes any message it
receives in its inlet and "prints" it out in the Max window. (If the Max window is not shown, you can select it from the
Window menu, or select the "Max Window" tab in an open sidebar.)

Commas change everything


You probably noticed that two of the message boxes have almost identical text, but the display in the Max window is
different. The message box with the text "Good morning, everybody!", when sent to the print object, caused the text to be
displayed on two lines. The message box right below it (with the text "Good morning\, everybody!") was displayed by the
print object on a single line in the Max window. The difference is in the use of the comma, which has a special meaning in
message boxes within Max.

In a message box, the comma is used as a message separator; in essence, it turns a single line of text into two discrete
messages. Thus, the message "Good morning, everybody!" is really treated like two messages: "Good morning" is sent out the
outlet of the message box, followed immediately by "everybody!".
In order to treat the comma as text (rather than as a message separator), you need to let the message box know that you are
overriding the commas special behavior. You do this by preceding the comma with the backslash ("\") character, which tells
the message box to ignore the commas special use, and treat it as a literal text character. Those of you familiar with textual
programming languages will find the use of a backslash character to "escape" a character that has special meaning familiar.

Unlock the patcher, click inside the lower message box (the one with the backslash) and remove the slash. Lock the patch
and click on the edited message box you will see that it, too, now creates two lines of text in the Max window. Edit the
first message box, adding a backslash before its comma, and lock the patch; it now exhibits the expected behavior of printing
the entire message on a single line.

Getting help
The print object is obviously doing something to send text to the Max window; in fact, every object box performs some sort
of task. To determine what function an object box performs, you can view several types of document to get help.

Unlock the patcher and select the print object box by either clicking into it or clicking and dragging the mouse over it to
highlight it. Select Open print Help from the Help menu. A new patcher window (called a Help patcher) opens with an
example that shows the print object in action. Note that this is an actual Max patch, and can be unlocked, edited, or copied
elsewhere, retaining any of the displayed functionality.

Close the print object's Help patcher and reselect the print object. Select Open print Reference from the Help menu. A
browser window (much like this one) is displayed with the Reference Manual page for the print object. This gives detailed
information about the object, all of its inlets and outlets, and even provides an example patch for your reference. This is
perhaps the most detailed information available for any object. Objects and topics relevant or similar to the object you're
viewing can be viewed by clicking on links in the See Also section at the bottom of the reference or on the "?" tab of an
object's help file.

Create some new messages


Lets add some objects to our patch, and create our own message passing logic. First, with the patcher unlocked, click on the
Object Explorer icon (the "binocular" symbol at the bottom of the window), then select the object in the Basic section. This
will place an empty object box on your patcher window, ready for you to enter its name. Enter "print", then click outside the
box to accept this change. Move the object somewhere in the patcher with some clear space above it by clicking and dragging
it around.

Next, open the Object Explorer and select a message box. When it appears in your patcher window, type in the message
"Goodbye!". Place this message box above the print object. Finally, connect the two boxes by clicking on the outlet of the
message box, dragging the mouse to the inlet of the print object, then releasing the mouse button. This will create a
patchcord between the two objects, allowing messages to pass from the message box to the print object.
Lock the patch and click on the new "Goodbye!" message. You will see the text "Goodbye!" appear on the Max Window.
Congratulations youve just done your first Max patching!

Conclusion
The three main elements of a Max patch (object boxes, message boxes and comment boxes), along with patchcords, are
the core of all Max programs. Each type of element responds to a variety of messages and editing functions; these can be
explored by viewing the help files and Reference Manual documents. Each of these aspects will be expanded upon in later
tutorials.

See Also
Name Description
print Print any message in the max window
message Send any message
comment Explanatory note or label
The bang message
Tutorial 2: Bang!
The bang message
In this tutorial, we will work with the bang message as a way to follow messages through the connections in a Max patcher.

This simple patcher will let us look at how to generate messages in Max, and how these messages execute through a patcher
in a pre-defined order.

Looking around
Take a look at the patcher 02mBang. At the left side of the patcher window is a very simple patch, with a button UI object
connected to a print object. If you click on the button (marked by the comment, "Click me!"), you will see that the Max
window displays a bang message the output from the button.
The bang message has a specific use within Max it's the message that tells many objects to do that thing you do. As a
result, sending the bang message to other objects will normally cause them to send messages from their outlets. In the
second part of the patcher (to the right), there is a button (labeled "Now click me!") connected to a message box (with the
message Gotcha!), which is subsequently connect to a print object. If we click on the message box, we can see the Gotcha!
message sent to the Max window just like in the previous Tutorial. Now, click on the button object. We see the same
Gotcha! message appear in the Max window. How did that happen?

Lets follow the messages. First, clicking on the button object sends a bang message from its outlet. This message follows
the patch cord to the inlet of the message box. When the message box receives the bang message, it performs its task it
sends out its message. Hence, the Gotcha! message is sent from the message box outlet to the print object, where it is
printed to the Max window.

Most Max objects (the message box and button included) will interpret a bang as an instruction to perform their main
task using whatever information they have available. We'll see in subsequent tutorials how this plays out with objects that
manipulate numbers and other items of data in the Max universe, but for now it's worth observing that since the primary
function of the message box is to construct and pass messages, sending a bang to any message box will cause that object
to output whatever message is stored in it.

Following messages through connections


The bang message is not only useful for triggering message boxes as we mentioned above, it can act as a trigger for many
other objects as well. Click on the button at the top-right of the third patch it is connected to a second button that is
triggered by a bang message, which then sends its message (bang) to the print object.
Note that this print object has an argument after it ("one"). If you look at the Max window, you will see that instead of the
word "print" appearing in the object column, the argument to the print object appears - "one". This is useful for debugging
Max patchers, as it allows you to create multiple print objects with custom labels to differentiate them from one another in
the Max window.

Now unlock the patcher, and connect the outlet of the top button to the lone button to its left. Notice that this doesnt break
the connection that already exists; outlets can be connected to more than one object, and the same message will be sent
down each of the patch cords. Lock the patch and click on the top-most button. The bang gets sent to both button objects,
and each of them produces a bang message of their own.

By a similar token, multiple patch cords can also be connected to a single inlet of an object. In this case, both of our button
objects are connected to a single print object. When you click on the top button, the output of both buttons that receive
bang messages are routed to the print object, and two bang messages are displayed in the Max window.
The next patch over demonstrates both of these principles. Clicking the button at the top of the patch sends three bang
messages to the Max window (through a print object labelled "several"). The print object receives a bang from both of the
"second-tier" button objects (triggered by our topmost button) as well as a single bang from the top button itself,
connected directly to the print object.
We can take this idea further with the right-most patch. It has a number of message boxes, all connected to a single print
object named many. Each message box has a button attached to it, and a higher-level button controlling them all. You
can make individual message box objects print their message by either clicking on the message box itself, or by clicking on
their attached button objects. If you want to trigger all of the message boxes at once, you can click on the top-most button.
When you hit the top button, notice the order in which the messages are displayed in the Max window. The messages are
not in an arbitrary order they are generated based on the spatial organization of the objects in the patcher, executing from
right-to-left. We will explore the details of message ordering in a future tutorial, but it is useful to understand that messages
are sent in right-to-left order when a single object is connected to many other objects.

Unlock the patch, and add several more button objects. You can do this by bringing up the Object Explorer and selecting the
button object's icon, or by simply clicking the 'b' (for button) key on the keyboard in an unlocked patcher. Connect them to
other button objects on that right-hand patch. Try different combinations of multiple outlet connections and multiple inlet
connection. As you connect each button, try to guess which messages will display and what order they will be sent to the
Max window.

Conclusion
The bang message is among the most powerful messages in the Max environment; it causes other objects to trigger their
output, and can be used to create matrices of connections that produce the desired output. Weve also seen that both inlets
and outlets can have multiple connections, and that these connections output their messages in a predictable order. Weve
also seen that some objects, such as the print object, can be assigned an argument, which causes the object to change its
behavior. An argument to the print object allows you to identify the source of messages printed to the Max window.

See Also
Name Description
button Blink and send a bang
print Print any message in the max window
message Send any message
Types of data in Max
Tutorial 3: Numbers and Lists
Numeric Data in Max
A lot of what goes into programming in Max involves being able to manipulate different types of data. In this tutorial, we'll
look at how Max deals with some new types of messages: numbers and lists. We will spend some time with user interface
elements that allow us to manipulate numbers, and learn how to use arguments to insert list elements into a message.

While messages made of text are useful for communicating with humans (and sending commands to a lot of Max objects
which we'll look at later on), much of the media world is dependent on numbers, whether they are MIDI note data, video
pixel colors or robotic motion control. Having a command of numeric messages is critical to understanding how Max works.

Numeric messages in Max are not always singular entities; they are often combined with command text or other information
to create a list of data that is useful to other objects, the user of your patch, or the outside world. Hence, combining
messages into lists provides the formatting necessary to create useful data structures.

Number boxes
Take a look at the 03mNumbersAndLists tutorial. The patch window contains several small patches that feature number and
list manipulations. The left-most patch looks at a new object (in green) called the number box. It deals with integer (often
called whole) numbers, and accepts many different messages. Click on some of the connected message boxes, and notice
their effect on the number box (as well as any messages that might appear in the Max window via the print object).
The most noticeable effect comes when numeric data is sent to the number box: it responds by displaying the data as well
as sending the number from its outlet. When a floating-point number (such as 3.5) is sent to the object, it takes the integer
portion of the number and truncates the decimal portion. If a non-numeric message is sent (such as the Hey! message), the
Max window displays a complaint by the object, stating that it doesnt understand that type of message.

Two special messages are accepted by the number box. First, sending a number box a bang forces the current value to be
output without any change to the data. Secondly, preceding a number with the set message will change the data without any
output in essence, providing a way to "silently" change the contents of a number box. The set method is fairly common in
Max objects as a way to manipulate the state of the object without triggering any additional messages.

The patch just to the right is similar, but uses a floating-point number box that allows for decimal values to be displayed
and output. Many of the messages produce similar results to the integer number box. However, when a floating point value
is received, the entire value is saved (and displayed) in this number box. The bang and set messages behave as wed expect,
and the Hey! message is not valid.

The user interface of the number box


In addition to sending them messages, we can also directly enter and manipulate the values stored in number boxes. For
example, we can click-drag within the box to manually change the number box contents. This is useful for performance
situations where we may want a change a number in real-time while the patch is running. Rather than having to set up
message boxes for every possible value we might need, we can manipulate the number box to change a setting. If we click-
drag on the integer number box, we see that the Max window displays a stream of data the number box generates output
for each of the values that we scroll through.

With integer data, it is easy to support a scrolling value area moving up adds 1 to the value, while scrolling down subtracts
1. But what do we add/subtract when we have floating point values? In the case of the floating-point number box, the
answer is based on where we place the mouse before we click-drag. If the mouse is on the integer portion of the data (to the
left of the decimal point), click-dragging will produce changes similar to the integer number box. However, if we position
the mouse over the fractional portion of the data, we can change any of the displayed digits. This allows us to manipulate the
data stored in the number box at both a "coarse" and "fine" grain.
Sometimes we will encounter situations where scrolling around in number boxes will trigger too many events or be too
inaccurate. Alternately, we might simply know exactly what number we want. We can also change the data for both integer
and floating-point number boxes by clicking on them (when the patch is locked), typing in that number, and then either
pressing the return key or clicking elsewhere in the patcher. This is a convenient way to enter numbers accurately without
having to resort to a message box (or having to scroll for days). Notice that the new data is displayed in the number box,
and the object outputs its value as well.

The third patch has three number boxes hooked up to each other. Here, you can see the visible difference between integer
and floating-point number boxes the floating-point versions have a displayed decimal point. If you change the top-most
(floating-point) number box, you will see its data being used to update an integer number box, which subsequently updates
the next (floating-point) number box. You can also directly manipulate the integer one to see how its messages affect the
floating-point variant.

Enter a large number into the top-most number box something like 60000. You will see that the integer number boxes
cant display this number, since it is too large for the provided display area. Unlock the patch and move your mouse to the
right-hand side of the object. You will see a small "handle" appear, and the cursor will change to a left/right arrow; this is
called a grow box, and can be used to re-size most user interface objects in Max. Click-drag on the handle to change the
width of the number box, then click on a blank area of the patch to deselect the object. You will see an immediate change in
the integer display.

Finally, enter a ridiculously high number, like 7245569558. The integer number box changed to -2147483648. How did that
happen? While floating-point numbers have a very high threshold of recognized value, the 32-bit integers have a limit in
this case, the maximum value of an integer is 2147483520. Any numbers greater than that cause the integer value to
"overflow", and become the greatest negative number. Other very high values might provide other values, depending on how
far over this limit the number is.

Looking at lists and replaceable arguments


The right-most patch is a little different it is just a group of message boxes with contents that are groups of number and
text. When we click on the message box with 60 30, we see the two numbers displayed together on the Max window. A
combination of numbers and text is called a list; the list is a mechanism for keeping data together into a single message that
can be send via patchcords to other objects. The numbers can be either integer, floating-point, or a combination, as you can
see in the second example (22 33.9 -5 -44.2).

The next example message is a number box connected to a message box. Use the mouse to change the value of the number
box; the result is that the Max window displays the fleas message, but replaces the $1 text with the incoming number. The
$1 text is called a replaceable argument, and allows you to substitute message content variably using a message box.

The last example accepts two values (as noted by the $1 and $2 replaceable arguments), and uses the incoming list values to
create the fleas and ticks message. You can have up to 9 replaceable arguments, numbered $1 through $9, and the
arguments can be in any order. Lets try an experiment with the arguments:

Unlock the patch window, and select the text in that last message box. At the end of the existing text, add the following text:
$2 ticks are worse the $1 fleas.

Lock the patch, and click on one of the two connected lists. You should see the new statement displayed in the Max window,
with the proper list content replacing the arguments in the message. This demonstrates that replaceable arguments can be
re-used (i.e. you can have multiple $1 arguments in a message) and can be invoked in any order (i.e. $2 can precede $1 in a
message).

Conclusion
Max can send numeric data as messages, just like text. There are a few user-interface objects that help us construct and
process numeric data, such as the integer and floating-point number boxes. Max can also keep groups of numbers linked in
a single message using lists; message boxes can be used to construct lists and other more complex messages with
replaceable arguments.

See Also
Name Description
number Display and output a number
Creating automatic actions
Tutorial 4: Metro and Toggle
Automated actions
This tutorial focuses on automated actions and the ability to control them. We will work with the toggle user interface object
to control the metro timing object. We will also look further into object arguments and overriding those arguments.
One of the most used objects in your home is the light switch it provides a simple user interface to a complex system (the
lights in your home). Likewise, the toggle object, combined with the automated timing function of metro, offer a simple
interface into an otherwise complicated world of automated and scheduled actions.

Fun with the toggle object


Take a look at the 04mMetroAndToggle patcher. The left-most patch features a series of message boxes (and a button)
connected to a square box. Start by clicking in that box we see its interior fill with a checkbox. A 1 message was also sent
from the object downstream to the number box connected below it. Clicking in the object again will remove the checkbox
and send out a 0. That's all this object does it outputs either a zero or non-zero value, depending on its state (off or on).
This objects formal name is toggle, and it is one of the most-used objects in Max programming.
Unlike most of the checkboxes that we run into when using our computers, this checkbox can be automated by sending it
messages. Click on the message boxes that are connected to the toggle to see their effect on the objects state. By looking at
the connected number box, we see that any number other than 0 turns it to "on" (the check mark is visually set); the toggle
also "echoes" the value of the number that turned it on out its outlet. Clicking on the 0 message turns the toggle off, and
outputs a 0.

The action of the button object is even more interesting. Clicking on the button switches the toggle object on and off, with
the output (seen in the Max window and in the number box) alternating between 0 and 1. This is the root of the toggle
object's name its ability to "toggle" states based on incoming bang messages.

Introduction to metro: the metronome object


The patch in the center introduces a new object: metro. The metro produces bang messages, much like the button object.
However, unlike button, metro objects send these messages automatically on a scheduled basis. Once started, metro will
continue to send bang messages until stopped. Click on the toggle that is connected to the metro, and watch the result it
sends a bang message (in this case, to a button object) once every second. We can turn it off by un-checking (turning off)
the toggle. the metro object is one of the Max objects that can be used to create automated or self-running actions in our
programs.

If we click on the button that is connected to the metro we see that it, too, starts the metro running. If we click on it again,
we see that it immediately triggers a bang out of the metro immediately; rapidly click on the button, and the output
continues being generated. It is only when we pause that we see the scheduled event generation. When a metro receives a
bang, the metro will "re-start" itself and begin scheduling subsequent bang messages from the moment we triggered it.
When we want to turn it off, we can click on the stop message to turn off event generation; telling a metro to stop with a
message is equivalent to sending it a 0.

How do we determine the speed at which the metro outputs bang messages? We determine the speed of a metro by setting
its period. The metro object takes an argument (the number 1000, in this case) that sets the time interval (in milliseconds)
between messages. 1000 milliseconds equals 1 second, which is why we see the bang messages coming out at that rate. How
do we change this rate? That is the function of metro object's right inlet it allows you to send a new time interval setting
without having to type in a new argument value.

In our patch, there is a number box with several message boxes connected to it. Click on the 2000 message, and (after the
next scheduled period) the output will slow to one message every two seconds. Click on the 500 and the metro speeds up,
sending bang messages twice a second. The message 250 will cause four bang messages per second. Changing the interval
setting doesnt change any other aspect of metro (e.g. whether it is "on" or "off").
Changing the interval with a message in the right inlet also does not change the argument of the metro. Why not? Wouldnt
it be convenient to see the new value? Perhaps, but it would mean that any changes to the object would change the value
saved with the patch and, most times, you want to maintain the typed-in argument since it functions as the default
starting value of the metro. Many Max objects behave in this way: they have one or more arguments that can be overridden
by messages sent into inlets.
Running in parallel
The third patcher in our tutorial features a single toggle attached to three additional toggle objects, each of which is
connected to a metro with a different argument. Turn on the top-level toggle, and the metro objects generate a "galloping"
light show. This is because the three time interval arguments of the metro objects are related: the first metro fires every
second (1000 milliseconds), the second triggers three times per second, and the third fires every quarter-second. There is
nothing managing this pattern it just occurs because the scheduled output of the metro objects are constant, so the
pattern keeps appearing. Note that the time interval of a metro can be both an integer (e.g. 1000) or a floating-point (e.g.
333.33) number.

Lets expand on the idea of creating rhythmic patterns by using some of the other ideas we just learned. We can change the
pattern by changing the time values of each metro; lets start by adding three message boxes, of values 500, 200 and 750,
and connecting one to the right inlet of each metro. When we click them to change the time intervals of our metro objects,
no apparent pattern exists. This is because we need to synchronize the start of the metro objects to see the pattern. This can
be accomplished by turning the top-most toggle off and on again. The result is a quickly flashing center light, with a
syncopated outside pattern.

Lets make another pattern, using message boxes for the values 200, 400, and 600, respectively. However, instead of using
the toggle to switch the metro objects off and on, connect a single button object to the left inlet of all three metro objects.
Click on the three message boxes, and then click on the button to restart all of the metro objects. The button forces the
metro objects to restart in sync, giving us the expected "rolling" light show.

Conclusion
Automated actions are at the heart of many Max performance patches, and metro objects are often used as the starting
point for these actions. Once started, the scheduling system of Max provides a stable timing system for Max output, and we
can allow the events to run without further interaction.

Controlling patches using the checkbox-like toggle object is also a key programming tool, since a single toggle can provide
a simple on/off interface to much more complicated processes.

See Also
Name Description
toggle Switch between off and on (0/1)
metro Output a bang message at regular intervals
Debugging program flow
Tutorial 5: Message Order and Debugging
Introduction
This tutorial is focused on message ordering the sequence in which messages are passed from object-to-object and how
objects generate them. We will also use some of the debugging tools in Max to determine how a patch is running.

Max patches often seem to have everything happening at once; in reality, messages are produced and acted upon in a specific
order. In order to make patches that operate correctly, we need to understand the order that things are occurring, and how
to control complex matrices of actions.

Right-to-left, bottom-to-top
Take a look at the tutorial patcher. This file has a number of small patches that we will use to learn about the rules that
messages follow. Click on top-most button in the top-left patch; it seems that all three of the connected button objects fire
simultaneously. This is an illusion messages are sent down the patch cables in a sequential order.

The easiest way to see this in action is to use some of the debugging tools in Max. You'll notice that the top row of patches in
the tutorial have small red circles with numbers in them covering the patchcords. These are called watchpoints (specifically -
breakpoint watchpoints). When we debug our patcher, we can use these watchpoints to stop the execution of the patch at a
specific point. This is done by enabling the Max Debugger. Select Enable Debugging from the Debug menu. Once
debugging is enabled, these watchpoints will help us see the way messages are passed in our patcher.

Click on the topmost button in the left-hand patch. Instead of the immediate "flash" of all the button objects lighting up,
the rightmost patchcord begins blinking red and shows a message path indicator. In addition, a window opens called the
Debug Window. Looking at the window, you can see what kind of information it gives us. The window tells us that a bang
message has been intercepted by a watchpoint; moreover it tells us which watchpoint was tripped (in this case, watchpoint
#1), the name of the patcher and what class of object the sending and receiving object was (in this case, both are button
objects). Select Step from the Debug menu (or click on the Step button in the Debug Window toolbar). You will see that the
middle cord flashes; select Step again and you will see that the left-most cord flashes. Select Step once more to finish our
patch trace. When the outlet of an object is connected to more than one inlet, the messages are sent in right-to-left order.

But what happens when the receiving objects are stacked vertically (and therefore at the same horizontal position)? With
debugging still enabled, click on the topmost button in the middle patch on the top row. As the watchpoints fire, select Step
from the Debug menu. When we Step through the patch, we see that the bottom-most button receives its message first,
follow by the middle, then the top. So, we can see that Max has two levels of ordering: right-to-left, then bottom-to-top.

There is one more twist to message ordering, and that is the effect of messages that cause more messages to be generated.
The third patch illustrates the issue. Click on the top-most button and Step through the order of the messages. By tracing
through this matrix of button objects we see that messages travel through the entire depth of one message chain before
sending a message to the next "branch" of objects. Notice that the Debug Window shows you the length of each message
chain in a branch; it only clears when a branch has been completed.

Therefore, the message-ordering rules in Max are:


1. Right-to-left, then bottom-to-top.
2. Depth-first traversal of connected objects.

Note that, for determining the right-to-left or bottom-to-top ordering, it is the location of the connected object, not the
location of the patch cords, that determines the message route.

As an exercise, create a new matrix of button objects, with both vertical and horizontal arrays of button objects (perhaps
using the Align option from the Arrange menu), and multiple depths of objects. Use comment boxes to number the boxes
in the order you think they will fire then trace the patch. Do this until the message ordering becomes second nature!

Select Disable Debugging from the Debug menu, and let's look at the other patches in the tutorial patcher.

More message ordering


Sometimes it is inconvenient to match the spatial order of the patch with our desired result. In the bottom row of patches,
the left-most patch is well structured: it is cleanly laid out, and has the number boxes in ascending numerical order from left
to right. If we wanted the messages to go from low to high, it is also wrong; when we click the top button, we see the
numbers come out in reverse order in the Max window. This is because the message boxes are receiving bang messages in
right-to-left order.

The next patch shows a corrected version of this patch, using a new object: bangbang. This object takes an incoming
message and produces bang messages from its outlets in right-to-left order. The number of outlets is determined by the
argument to bangbang (in this case, the 3 argument produces three outlets). The outlets are connected to the message
boxes in the appropriate order; when we click on the top button, the Max window displays the messages in the preferred
order.

Notice that the outlets of bangbang fire in right-to-left order, mimicking the message ordering of the patch itself. Most
objects with multiple outlets will follow this rule: output is from the right-most outlet to the left-most outlet.

Using the bangbang object makes the message order explicit; that is, it forces the messages to follow a specific path
regardless of spatial orientation, and lets us place objects anywhere we want in the patch, knowing that they will be triggered
in deterministic order based on which outlets we trigger them from. Another message that provides explicit ordering is the
trigger object. The trigger object accepts input, and outputs messages based on its arguments. The arguments determine the
type of output, with options of l (for list), b (for bang), i (for integer), s (for symbol a text message) and f (for floating-
point number). You can also use specific integers, floating point numbers or symbols as constant outputs.

The next patch contains two message boxes with the integer 90. If we click on the one connected directly to the print
objects, the Max window displays the typical right-to-left ordering of messages. However, if we click on the message box
connected to the trigger object, we see that we can control the output to print in left-to-right (reversed) order. The sent
messages are all printed as the integer 90, since our arguments for trigger were are of type i (integer).

The next patch to the right also uses an incoming integer message (90), and is connected to a trigger object (using the object
abbreviation: t). However, in this case, three different arguments are used. When we click on the message box, we see that
the output of the three outlets are all different, matching the difference in arguments. The right-most outlet, with argument
of type i (integer), produces an unchanged 90 output. The middle outlet, set to type f (for floating-point), casts the incoming
message to its floating-point equivalent (90.000000) and sends it to the print object. Finally, the left-most outlet, of type b
(bang), accepts the incoming message but turns it into a bang. So, in addition to making the message order explicit, the
trigger object can do type conversion of messages.

The right-most patch shows the use of constant values within the trigger object. When we change the floating-point
number box to any number, the trigger object again converts the incoming number, but also includes a number of symbols
(text messages) that are used as constant values. We also see that the incoming message did not change the output of the
bang outlet a bang is a bang, regardless of incoming message type.

Now would be a good time to build some more button matrices, but combining them with trigger and bangbang objects,
and labeling them with their expected message order.

The trouble with loops


The final patch in our tutorial file is a set of four button objects all interconnected in a loop. When we click on any of the
button objects, the system comes to a halt with a stack overflow error. Why did this happen? Remember that Max does a
depth-first prioritization of messages. However, a looped patch construction has an infinite depth, and therefore cannot be
properly parsed. One button sends to the next, which sends to the next, which sends to the next, which sends to the first,
triggering the cycle all over again. When a stack overflow occurs, Max shuts off its scheduler to prevent anything else from
happening; once we've found the problem and corrected it in our patch (e.g. by disconnecting one of the button objects in
the loop), we can turn the patch "on" again by clearing the stack overflow message at the top of the patch.

Conclusion
A deep understanding of message ordering rules is necessary to create properly functioning patches. The right-to-left,
bottom-to-top, depth-first order is the implicit rule for message passing, but you can use objects like bangbang and trigger
to make the ordering explicit. In all cases, however, you need to watch out for structural loops they are literal patch-killers!

See Also
Name Description
bangbang Output a bang from many outlets
trigger Send input to many places
Performing calculations
Tutorial 6: Simple Math in Max
Performing calculations
This tutorial covers the basic mathematical operations that are available with Max objects, and the process of connecting up
several objects into a calculation chain. We will also cover the common operations of objects with multiple inlets, and some
issues with numeric conversion.

Common math operations, such as addition and multiplication, are important for manipulating incoming data into a range
and form that is useful for our patches. Additionally, dealing with the difference between integer and floating-point numbers
is critical when working with many types of data such as MIDI, audio and serial information.

Everybody loves Math


Look at the tutorial file 06mSimpleMath.maxpat. The top row of patches shows examples of the various simple mathematical
operations that are available in Max. The left-most patch performs addition using the + (plus) object. The + object, like
most math objects in Max, has two inlets one for each operand. Numbers coming into the right inlet are stored, and added
to numbers coming into the left inlet. If no number has yet come into the right inlet, the right operand is set to the object's
argument; if no argument is supplied, the right operand defaults to 0.

When we click on the message box containing the number 2 (on the left), the result (which is displayed in the connected
number box) is revealed to be 2 as well; since no number has come into the right inlet, the current stored operand remains
0. Clicking on the message box with the number 3 produces no output, but stores the number 3 as the new right-hand
operand. When we click on the 2 again, we see the additive result 5 displayed in the number box.
The next patch uses an argument to the + object that sets an initial default value for the right-hand operand. Now, when we
put a number into the + object (using the top number box), we see a result without having to send any number into the
right inlet. Using default arguments for math operations is a common setup in many situations where you need to perform a
constant mathematical operation (e.g. offsetting or scaling a number) on a stream of input values.

Next are the - (minus) and * (multiply) objects, which perform subtraction and multiplication, respectively. Like the +
object, they have default operands of 0, and accept stored values in their right inlet and produces results based on values
coming in the left inlet. The divide (/) and modulo (%) operations are also similar, but with one difference in order to
prevent unwanted "divide by zero" errors, their default right-hand operands are one (1) rather than zero.

Inlets, Hot and Cold


As weve seen in the first set of math objects, some inlets cause an object to output a message, while others cause the object
to simply store values. In fact, messages sent to any of the inlets cause these objects to store values; the difference is that
values coming in the left-most inlet have an implicit bang message attached to them - this forces the math object to output
the result of the calculation once the value is received and stored. We can see this in action by attaching a bang object to a
math object, and using it to explicitly force output.

The first patch in the second row is a simple addition patch, but with a button connected to the left inlet. Sending numbers
into the + object performs the expected result: numbers in the right inlet are stored and used as a right-hand operand, while
numbers in the left inlet are used as left-hand operands and cause the object to output results. Clicking on the button also
produces a result: the addition is performed with the current set of operands, and the result is sent out of the outlet. This is
useful when you want to change the right-hand operand, but want output without having to resend the left-hand operand.
It is also a good example of the bang message performing its "do it!" function.

Inlets that cause an object to output messages are often called hot inlets while inlets that only store information are called
cold inlets. It is a common practice, when a cold inlet needs to produce output, to route a bang message (via a button or
trigger object) into the left-most inlet to force output.

Type conversions through arguments


The next two parts of the patcher show what appear to be equivalent operations using the + object. Both of them purport to
add together the numbers 2.5 (in the right inlet) and 12.75 (in the left). Try them both out (remember we need to click the
right-hand message first to set the right operand).

The result of adding 12.75 and 2.5 should be 15.25. But between the two + objects, only the right-hand one produces the
correct result. The left-hand + outputs 14. Why?
Like many programming languages, Max has different types of numeric data, and operations on that data can be done using
integer or floating-point mathematics. By default, all of the objects that perform math operations in Max use integer-based
arithmetic. When floating-point numbers are received by a math object in "integer" mode, they are truncated to integers
before being used. Thus, 12.75 becomes 12, and 2.5 is converted to 2 which adds up to 14. In order to set a math object
to use to floating-point arithmetic, we need to provide an argument that is floating-point. The right-hand patch does just
that it uses a 0. argument to inform the + object that we want to perform floating-point arithmetic, and the addition
results in the 15.25 value that we were expecting.

Forcing a calculation
The final two patches in the second row show a simple mechanism for triggering output from the + object, regardless of
which inlet receives messages. The left inlet is fed directly by a number box; since left inlets are already hot, they need no
further attention. However, in order for the right inlet to produce output, we have to send a bang into the left inlet after the
right inlet has received input. This is a perfect application for the trigger object, which is used to manage this function.
In both cases, the trigger object (abbreviated to t) has two outlets (defined by its arguments): the right outlet is type-specific
(i for integer, f for float), while the left (b) sends out a bang. When a number is entered into the object, trigger processes the
arguments in a right-to-left order, first sending the numeric value (integer or floating-point) into the right inlet of the +
object. Then, a bang is sent to the left inlet of +, forcing calculation and output to the number box below. In this way, we
can force both inlets of the + object to behave as though they are "hot", and receive output regardless of which inlet is sent
messages.

Using cold inlets for recursion


At the bottom of the tutorial file is a curious little patch that has the result of a + object feeding back into itself. You can see
what it happening by clicking on the top number box, entering a number, and then entering more numbers after that (you
can also drag the number box to scroll values). As you enter numbers, the result keeps accumulating.

This is a case where we are taking advantage of the "cold" (right-hand) inlet of the + to change its right operand based on
the previous operation's output. In this case, the result of the addition is fed back into the right-hand inlet, where it is stored
as the right operand for the next addition operation. This results in an accumulation of the output, which can be handy for
tracking a running total of incoming values. These types of recursive operations are useful for making counters, smoothing
algorithms, and pieces of code where the system's behavior is dependent on previous outputs of the system.

Cascading math objects


All of the above examples have been pretty simple theyve been simple math operations with a simple result. However, you
can chain several of these operations together to create more complex equation.

For example, let's say we wanted to make a Max patcher for converting temperatures: specifically, converting Fahrenheit to
Celsius. The formula for this conversion is:

C = (F 32) * (5/9)

From an object standpoint, it might be easier to simplify this to:

C = (((F 32) * 5) / 9)

We can produce this output by using the -, *, and / objects chained together. Unlock the patch, and begin by using a
number box for the Fahrenheit (F) input. Connect this to a - object with an argument of 32 as the default right-hand
operand. Connect the output of the - object to a * object with 5 as an argument, and connect it to a / object with 9 as the
argument. Finally, connect the output of the / object to another number box to see the result of the Fahrenheit to Celsius
conversion.

Conclusion
The mathematical objects, used either singly or in a sequence, provide the tools necessary for manipulating numeric input in
many ways. The math objects provide both hot and cold inlets, but simple patching operations can be used to force output
on cold inlets. Math objects, by default, perform their computations using integer arithmetic; a floating-point argument can
be provided to tell the object to perform arithmetic using real numbers.

See Also
Name Description
+ Add two numbers, output the result
- Subtract two numbers, output the result
* Multiply two numbers
/ Divide two numbers
% Divide two numbers, output the remainder
trigger Send input to many places
Sliders and dials
Tutorial 7: Numerical User Interfaces
Sliders and Dials
In this tutorial, we will work with several user interface elements that provide for numerical display and editing. We will use
both messages and the object inspector to change the appearance and behavior of objects in order to make them work as we
wish.

Numerical display and editing is at the heart of Max patching. Whether data comes from sensors, MIDI devices or just from
moving on-screen controls, numerical data is easy to test, manipulate and use for program control.

Numeric UI Objects
Look at the patcher named 07mNumericalUserInterfaces. At the left side of the patch is a set of interconnected message
boxes, sliders, knobs and number boxes. The basic "slider" object in Max is called a slider, and can be oriented horizontally
and vertically, depending on what we need for our patcher interface. The "knob" is called a dial object.
Click and drag on the "thumb" of the slider objects to see the results displayed in the connected number boxes. The output
of a slider is an integer number based on the range of the slider. Both the vertical and horizontal slider perform identically.
The dial next to the vertical slider performs a similar function; however, in its current configuration, you need to move the
mouse pointer in a vertical motion to change the position of the knobs wiper. This is something we will look at changing
later in this tutorial.

Click on the button just above the horizontal slider it doesnt seem to perform any function. However, if we change the
number box connected to the slider, then click the button again, we will see that when a slider receives a bang, it responds
by outputting its most recent value. Thus, a slider acts like a number storage tool as well as a numerical editor.
Finally, lets unlock the patch. If we put the mouse pointer near the bottom-right corner of a slider or dial, we see a small
resize box appear, and the cursor changes to reflect that we can resize the objects. When we click and drag the resize box, the
size of the object changes, but the function of the object stays the same. This allows us to change the layout of our patch for
convenience without changing the way our user interface elements operate.

Changing UI object behavior


All three of our user interface objects share the same output range: 0 through 127. Obviously, this is not the behavior we
would always (or even normally) want. By default, these objects output numbers in the range of 0 to 127 (which mimics the
MIDI number range); this range can easily be changed using messages to the object.

Above the objects are some message boxes formatting messages based on numbers coming in from attached number
boxes. As weve seen in earlier tutorials, this is a mechanism to send commands to another object; in this case, we will use
them to change the behavior of the slider and dial objects. If we change the first number box (connected to the size $1
message) to 50 and then move the sliders or knob, we see that the range has changed: you can now produce output from 30
through 79. Why not 80? It is because the size message determines the number of discrete steps for the object. If the
starting step of 30 is included, 50 steps will give you a maximum value of 79.

Next, let's adjust the number box which triggers the min message. If we change this to 0, the slider objects and the dial now
output messages in the range of 0 to 49. Using the min and size messages in tandem allow us to set the objects to output
whatever range of values we need for our patching.

If we change the third number box (connected to the mult message) to 5, the output changes to output the range from 0 to
245, in steps of 5. This result is based on multiplying the current range by the multiplier value.

When you move the sliders, you might be surprised by some of the interim values that you see. This is based on the way in
which the interface objects calculate their output: the objects maintain an internal value from 0 to the range (max - min -
1). This is multiplied by the mult value, then offset to match the min value. This means that the output will always have step
sizes of mult, even as the value goes through 0.

number box options and the Inspector


On the right-hand side of the patch is a diamond array of number boxes, each one providing a different display format. The
top-most number box is familiar to us a decimal format number, with a triangle that helps us recognize this as an editable
number box. Connected to this are two number boxes with different display formats: the left box displays information in
hexadecimal (base-16), while the right box displays the information as if it were an incoming MIDI value.

The bottom number box shows a change in display characteristics: the number is in a bold font, and there is no triangle on
the left of the box. This may be useful if you want to see more of the number in a limited space, or if you want to imply that
the value shouldnt be edited.

All of these variations on the number box are based on changes in the attributes of the object. Attributes are changed using
the object inspector, a window containing all of an object's attributes, and an interface for editing them. Unlock the patch
and hover the mouse over the middle-left of one of the number boxes a multi-segment circle menu will appear. Select the
object inspector from the Object segment to open it.

The initial display of the inspector shows all of the available attributes, sorted by type. There is also a set of tabs across the
top of the inspector that allow us to limit the attributes that we see. The "Display Format" attribute has a discrete number of
values; you can see the available formats by clicking on the current value. The options are "Decimal", "Hex", "Octal",
"Binary", "MIDI", and "MIDI (C4)". These are all variations on decimal display that may be useful, depending on the values
you are entering or displaying in a number box.
When we click on the "All" tab, we see all of the attributes that affect the appearance and operation of the number box.
Options include "Draw Triangle", something we saw disabled in the bottom number box in our patcher. Turn this on and off
in the inspector, and notice that there is an immediate change in the object; changes to inspector values cause instant
changes to the object.

The names used by the inspector do not necessarily match the messages used to control the object. How do we know what
message might match a particular attribute? The easiest way to create a matching message is to click on the name of an
attribute and drag it into an unlocked patcher. The name will be transformed into a message box formatted with the
proper message, offering a shortcut when you want programmatic control of attributes.

Using the inspector


Let's unlock the patcher and create our own small user interface. Open the Object Explorer and select a slider, a dial and a
number box. Resize them to be different sizes, and move them around to make an attractive layout. Note how the slider
switches from a vertical to horizontal orientation depending on the aspect ratio (height versus width). Connect the objects to
see how they interact, and use the objects as both display and editing tools. Then, for each object, open the inspector and
make some changes in appearance. Change the colors, and (if you like) change their behavior. When you are done, lock the
patch and make sure the object look and act as you expected.

Conclusion
Visual display and editing of numerical data can take many forms. Weve seen how to use slider and dial objects, and how to
display numbers in various formats within the number box. Weve also changed the behavior of objects using both messages
and the Object Inspector. Since using numerical data is so important in Max programming, it is helpful to have many ways
to show and alter this type of data.

See Also
Name Description
slider Move a slider to output values
dial Output numbers using an onscreen dial
Working with standard input interfaces
Tutorial 8: Keyboard and Mouse Input
Type, click, and drag
In this tutorial, we will look at controlling Max actions using two common controllers your computer's mouse and
keyboard. We will also see how to convert numbers into letters, and identify particular keystrokes.

It is not always convenient or even useful to use external hardware for controlling Max patches. Sometimes the computer
itself contains all of the control mechanisms that you need to work with your patches. Working with the mouse and keyboard
can give us extensive control of our patches without having to worry about any other devices.

Watching the mouse


Take a look at the patcher 08mKeyboardAndMouseInput, which will be our example patch for this tutorial. At the left side of
the window is a small patch that connects a metro object to two new Max objects labeled mousestate and modifiers. Click
on the checkbox to turn on the metro, then move your mouse around the screen. You will notice that the number boxes
connected to the mousestate object report information as your mouse moves, and that the connected checkbox is turned on
whenever you click the mouse button.

The output of the mousestate object provides button-status and cursor-position information about the mouse/cursor when
the cursor is positioned within a Max patcher window. It provides a value stating whether the mouse button is "clicked" as
well as two sets of coordinates: absolute mouse position on the x and y axis, and a delta position showing the movement
since that last time the mousestate was polled. The absolute position is based on screen coordinates, not coordinates within
the patcher window, so you can track movement anywhere on your computer screen. It also means that the results of
mousestate will vary depending on the size of your computer screen real estate. Screen coordinates on the computer are
reverse-cartesian, which is to say that the upper-left hand coordinate of your screen will be 0, 0, and the lower-right
coordinate will be the size of your screen minus 1 (e.g. a 1024x768 display will give you the coordinates 1023, 767 when the
mouse is at the bottom-right edge).

The delta value reports changes in mouse position but when are changes actually reported? The change (as well as the
absolute position) are only reported when a bang message is received in the objects inlet hence, the use of the metro
object to generate messages. This is called polling, and allows you to control the density of messages that are created by an
object. This is especially important in the case of an object like mousestate, where massive streams of unwanted data could
be generated if it acted automatically. The only output that does not require active polling is the mouse button notification
(the left outlet of the object).

Watching the keyboard


Adjacent to the mousestate object is the modifiers object. This will track (from left-to-right) the shift and caps-lock keys on
your keyboard, as well as the Cmd, Control and Option keys on a Macintosh system or the Alt, right-hand mouse keys or Ctrl
keys on a Windows system. All of these outputs require polling as well, but are a great way to capture the state of the
modifier keys as special cases within your patch.

The next three small patches demonstrate capturing key presses on your computer keyboard. Unlike mouse messages,
keystrokes produce output only when pressed and released, so there is no need to use polling to reduce message density. In
the leftmost patch, the key object is used to get the ASCII value of a key when it is pressed. That output is sent to a number
box (to display the value), then passed to an itoa object which translates that integer value into an alphanumeric symbol.
This is sent to the Max window (via a print object), where you can see the letter of the pressed key. Try typing your name
and watching the Max window; notice that the integers coming out of the key object are correctly converted to their
corresponding symbol. Keys that generate non-printing characters, e.g. the return key (ASCII 13) and the tab key (ASCII 9)
generate the correct numerical values from the key object, but print a single blank line in the Max window.
Just to the right is another small patch that uses the keyup object. This is almost identical to the key object, except that it
doesnt report any key information until the key is released. This is useful for situations where you want an action to only
occur while a key is being pressed; you could turn the action on when you receive a message from key, then turn it off when
you get a message from keyup.
The next small patch feeds the output of a key object to an object called numkey. This is a very convenient object that allows
you to work with numeric keyboard input in the integer domain. Start by typing in a few numbers you will see them being
accumulated into a number from the right-hand outlet. If you hit the return key, you will see that the number is reported as
an integer from the left outlet. This means that the numkey object is performing all of the accumulation and translation of
keyboard values into a numeric outlet. Note that this patch is limited to integer output; if you want a floating point output,
you would need to add a floating-point argument (like 0.0) to the numkey object to tell it to respect the decimal point and
report floating-point output.

Controlling output with mousefilter


Finally, the right-most patch shows an object called mousefilter in action. When we click and drag the upper slider, we see
that no output is generated until the mouse button is released. This is another convenience object that can be used to limit
the generation of unwanted intermediate data. In this case, you may not want to perform any action until the movement of
the slider is complete. By funneling the slider object's output through mousefilter, all output is suppressed until the mouse
button is released.

Creating an "intelligent" patch


Let's use some of these objects and techniques to create a patch that works "intelligently" based on keyboard and mouse
activity. Create two metro objects with arguments of 250, and connect button objects to their outlets these will be our
test subjects. Using the left-most patch as a starting point, connect the left-most outlet of mousestate (which reports the
mouse button state) to the left inlet of the two metro objects. Lock the patch and verify that pressing the mouse button turns
on the metro objects, and releasing them causes the metro objects to stop.
Next, lets track the horizontal mouse position using a slider. Add a slider to the patch, and connect it to the second outlet of
mousestate. In order to have this make sense, we will need to change the range of the slider. Use the size message (or use
the Object Inspector) to change the maximum range of the slider to the width of your screen in pixels this will be
something like 800, 1024, or 1280 (depending on the resolution of your screen). Now, if you turn on the metro object
polling the mousestate, you should see the slider move in tandem with horizontal movements of your mouse.
Let's use this value to control the output speed of the two metro objects. Connect the outlet of the slider to the right inlet of
the first metro you created. Now, as you move the mouse (with the button held down), you will see the speed of the first
metro change based on the mouse's current position. Let's also use the slider to control the second metro object's speed, but
scaled using a math operator. Add a * object to the patch with an argument of 2, and connect it between the slider and the
second metro objects right inlet. Now, as you move the mouse (and press the mouse button), you will see that the second
metro takes twice as long to fire as the first, but both are being controlled by the mouse position.

Finally, lets use the keyboard to change the scale of that * object. Using the output of the numkey object's left outlet (the
one that only reports values after the return key is hit), we can connect it to the right inlet of the * object. Now, we can
change the scaling of the second metro by entering in a number using the number keys and do so without having to click
on the number box to make the change. You can test this by entering a number (try 3 for example), hitting return, then
testing the mouse click function. You should see the metro objects respond to the current mouse position.

Conclusion
This tutorial shows how the computer itself can be used as a controller for your Max patch. Rather than depending solely on
user interface elements, you can query the mouse and keyboard directly, and use the resultant values to alter the actions of
your work.

See Also
Name Description
itoa Convert integers to ASCII characters
key Report keyboard presses
keyup Report key information on release
modifiers Report modifier key presses
mousestate Report the mouse information
mousefilter Gate messages with the mouse
numkey Interpret numbers typed on the keyboard
Introduction to drawing
Tutorial 9: Mouse Drawing
Introduction
In the previous tutorials, we've looked at a set of basic objects that we use all the time for constructing patchers in Max. In
this tutorial, we'll use these objects (and a few more) to actually control something (in this case, drawing). We will look at a
few ways to manipulate messages by routing them (using the gate object) and manipulating lists (using the pack and
unpack objects). We will also query the state of the mouse to change the way that our patch works, and we will learn more
about getting information on individual objects and changing the appearance of objects and patchcords. We will use these
new objects and techniques to control the lcd object, which allows us to draw simple two-dimensional graphics inside of
Max.

One of the most powerful aspects of Max is the ability to create small segments of programming that perform specific
functions, and having the ability to route messages to the appropriate portion of a larger patcher. Intra-patch routing is key
to that power, and the gate object provides that functionality in a very flexible way. It is also useful to build complex
messages on-the-fly, so we can control complex patch processes with relative ease.

The pack and unpack objects are used to create list messages and to split them into their individual components again. Lists
are the key to working with objects that require more complex messages, and it's often necessary to construct and
deconstruct lists from smaller components (integer and floating-point numbers, for example).

Finally, we will dig into getting more information on object messages. We'll also learn how to color and manipulate
patchcords. Visual cues help us figure out other peoples patch functionality, and make patches more readable when we share
our patches.

Getting more info


Before we begin looking at what our tutorial patcher does, lets take a short diversion to look at some of the ways we can get
information about the objects that we have in our patch. Unlock the patcher and move your mouse around the objects in the
patch. Youve probably noticed that when we place our mouse on an inlet or outlet, a small box is displayed with information
about the use of that inlet or outlet. This assistance text is provided as a reminder for the programmer of what that inlet or
outlet does in an object. You will also notice that a small circle is displayed around the inlet/outlet.

If we control-click on an inlet while the circle is displayed, a contextual menu is displayed that shows all of the supported
incoming messages, as well as shortcuts to view the objects help file, reference pages and even to search our system for
relevant matches in the file browser. This provides a greater level of detail if we need to know details about the exact use of
the object. This information is also available in the Messages and Attributes segments of the circular menu.

There are other options for on-the-fly information. Select Clue Window from the Window menu of Max; a small window
will be displayed. Now, when you hover the mouse over an object, we will see a brief explanation of the function of the
object. Also, if the contextual menu is displayed, hovering over messages will display a brief clue about how the message will
affect the object. Using the clue window to view the use of objects is a great way to examine the objects used within a more
complex patch.

When you select a new object and begin typing, you will be presented with an auto-completion menu that not only provides
names for objects, but can give you some information on their use. Something similar happens when you create a new
message box: typing information into it will reveal messages that might be useful for objects in the current patcher.
More about objects and patchcords
If you look at the objects in this tutorial patcher, we notice that the patchcords look a little different than the ones we've seen
earlier. First of all, a number of the patchcords have right-angle segments; in addition, some of them are different colors.
Lets look at some of the ways we can manipulate the patchcords themselves. Under the Options menu in Max, check the
option Segmented patchcords. This allows us to create patchcords that have bends in them. We can delete a patchcord by
selecting it and hitting the Delete key, or by choosing Delete from the patchcord menu. Delete one of the patchcords
connecting the message boxes to the gate object at the top-left of the patch.
Now, reconnect the message box to the gate, but instead of making a direct connection between the two, make a
segmented patchcord by clicking the outlet of the message box and then releasing the mouse; we can add segments by
clicking the mouse anywhere while we draw the patchcord; we finish the connection by clicking the inlet of the destination
object (the gate). Whether you use straight or segmented patchcords is largely a matter of personal style, but often you can
sometimes make a patch look cleaner by using segmented patchcords.
Max also can help us clean up our patchcords. Click on the patchcord and hit Command-Y on the Mac, Ctrl-Shift-A on the PC
(alternately, you can select the Align function under the Arrange menu in Max). Max will segment and reroute the
patchcord to avoid overlapping objects. We can also select several patchcords by holding the Shift key while clicking on
patchcords - the command sequence will then reroute all of the selected patchcords. There is no difference whatsoever
between a regular and segmented patchcord in terms of how messages are passed between objects.

Finally, lets look at Maxs ability to change the color of objects and patchcords. We can select an object or patchcord (by
clicking on it) then select Color from the Object or patchcord menu. This will display a color picker dialog, where we can
select a color for the selected item. Selecting a color returns to the patch editor with the object or patchcord having the newly
selected color. We've been coloring objects green as we introduce them in the tutorials; as you can see, it's a great way to
focus attention on important parts items within our patch.

Working with the gate object


Now lets look at what the patcher does. In our tutorial patcher, we find two small patches (on the left) and one very large
patch. The patch at the top left is where we will start.

This patch shows the gate object in action. The gate object is one of the most important objects used for dynamic message
routing within Max. We will start by clicking on the message labeled 1 (the middle message box), then changing the value
of the number box attached the right inlet of the gate. When we do this, we see that the value of the number box is sent out
the left outlet of the gate (outlet 1). If we click on the message labeled 2 and alter the number box again, we see that the
changes are now sent out the right outlet of the gate (or outlet 2).
As we can see, the number sent into the left inlet determines the routing of the message received in the right inlet; in
essence, the left inlet determines which outlet is opened. Now, click on the message labeled 0 and change the number on
the right. The message never makes it out of the gate the 0 message has closed all of the outlets. This is useful for
situations where we want to suppress messages within our patch, for example when we need to selectively enable and disable
numbers flowing from one part of our patch to another.

As an exercise, change the gate object to have a 4 for an argument (it currently has a 2). We see that the object changes it
now has four outlets. The argument to gate determines the number of outlets that the object has. If we add a few more
messages to the left inlet (by adding a 3 and 4 option to support the new gate outlets) and attaching number boxes to the
new outlets, we can see how easy it is to expand the routing matrix supported by the gate object.

pack, unpack, prepend


The next part of patch that we will look at is just below the gate it uses the unpack and pack objects to split and
reassemble lists of numbers, and the prepend object to place a message selector (a symbol) in front of the list. The two
message boxes contain two-number lists; when we click on them, we see the two number boxes connected to the unpack
object display the individual numbers within the list. The unpack object has taken the incoming list and split it into
individual numeric messages. Since lists are often used to create complex messages, we often use the unpack object to
unwrap these lists into its individual components (called atoms).

After the number boxes display the messages, they send out their contents into the pack object below, which reverses the
process by combining them back into lists that are sent to the prepend object and displayed in the Max window (via the
print object. Notice that only one message is displayed in the Max window, even though the pack object received two
messages (one from each number box). This is because the pack object (like most other objects in Max) will only produce a
message when the leftmost inlet receives a message. The patch editing environment provides a clue for this: if we unlock the
patch and hover the cursor over the right inlet, we see that it displays a blue circle meaning that it is a cold (non-message
producing) inlet. Hover over the left inlet and we see it circled in red; it is a hot inlet, and will cause the object to generate
output when it receives a message. We can confirm this by typing other numbers into the number boxes that are sandwiched
in between the unpack and pack - only the left-hand number box will cause a list to come out of the pack object.
The arguments to pack and unpack determine both the number of inlets and outlets, respectively, the object will have, but
also the type of message that can be sent into those inlets. In our case here, both of these objects are working with two-
element lists made up of integer numbers (signified by the use of 0 as an initial argument). If the list we were making
required floating-point numbers, we could have used 0. (or any other initial floating-point value) as an argument; similarly,
if a symbol (a word) was needed in the list, we could have used the letter s (or any symbol); types of data can be mixed and
matched within a list.

Notice that the prepend object places the word thelist in front of the list of numbers coming out of the unpack - this
symbol can be any word we like, but in many cases in Max we use prepend to place a message selector at the start of a list
before sending it into an object that has a special use for that message.
The lcd object
Now its time to attack the big patch to the right. Lets see what it does by turning on the metro object at the top of the patch
by clicking the toggle object to 1 (checked).
The large rectangular object in the center of the patch is an lcd (liquid crystal display) object: we can use this object to draw
pixels, lines, shapes, text, and other simple two-dimensional vector graphics. If you drag the mouse in this area while holding
down the mouse button, we see that it draws lines wherever you go. Release the mouse button, and the drawing will stop.

If you hold down the shift key, option/alt key or a combination of both, the lcd object draws different shapes under the
mouse rather than lines. There are three colored message boxes above the lcd that can be used to change the foreground
color of the drawing (using the frgb message), and another message box (to the right) that will send the clear message to
the lcd, erasing its screen.
One of the key sections of this patch is the handling of the shift and option/alt keys; this is done by the modifiers object,
which is polled using the metro, and reports the current setting of the various modifier keys on your keyboard. In this case,
we use the outlets that report the shift and option/alt keys; we multiply the option key's state by 2 and add it to the state of
the shift key. The result is that shift alone will give us the value 1, option/alt alone will give the value 2, and the combination
will give us 3. If no modifier keys are depressed, the value will be 0. This type of patch circuit is perfect for controlling the
state of the gate object below.
In addition to providing a drawing surface, the lcd object can give us the current location of the mouse in a manner
analogous to the mousestate object, only relative to the position of the lcd in the patch. Sending the message idle 1 to the
object allows us to get mouse coordinates regardless of whether or not the mouse is actually clicked inside the lcd (we
enabled idle mousing when we turned on the toggle box, above).
These coordinates are provided by the second outlet of the lcd object we can see the values (a list of two numbers that
represent the X and Y coordinates within the LCD object) in the number boxes at the lower right, after they've been split
apart by the unpack object. This list is also sent to the right inlet of the gate object; weve colored that patchcord red to
make it easy to see.

By routing the mouse coordinates to different areas of the patcher, the gate object now controls what type of drawing will
occur in the lcd. If no modifier keys are depressed, the gate receives a 0 and none of the drawing routines are used, though
we can still click-drag inside the lcd to draw lines. If shift, option/alt, or both are depressed, the gate routes the mouse
location to the appropriate section of the patch.

In each of these sections, the X and Y locations are run through unpack objects to get the coordinates individually. They are
then used to create a properly sized shape. In the left-hand (shift) case, a value of 10 is subtracted and added to both
coordinates and sent into a pack object in the order:
X-10 Y-10 X+10 Y+10

This list of four values is then sent to a prepend, which places a symbol at the front of the list. The lcd object supports a
number of drawing commands which do different things; in this case, we're instructing our lcd to draw rectangular frames by
providing it with a framerect message followed by four arguments - the left, top, right, and bottom boundaries of the
rectangle we'd like to draw.

Looking at the other two pieces of drawing code, we can see that they work in similar ways. The middle outlet of the gate
object (responding to the option/alt key) draws oval-shaped frames (the frameoval message) that are 10x10 pixels in size
(notice the + and - objects). The third drawing alternative (for when both shift and option/alt are held down) draws filled in
rectangles with rounded corners (paintroundrect). In addition to the coordinates of the rectangle, two additional number
boxes are sent into the packobject - these control how rounded the corners are.
When the coordinates are created and determined (using the math objects and pack) and given a message selector to
determine the drawing routine (using the prepend object), the message is sent back into the lcd object. In order to easily
see this message routing, weve colored the drawing command patchcords in blue. The frgb message boxes are also colored
to match the color it will tell the lcd to draw with. These are examples of using object and patch cord coloring to make the
function of a patch more obvious.

Conclusion
There have been several different (but important) topics covered in this tutorial. We see how the gate object can be used to
activate message passing to sections of your patch. Weve also seen how to use the unpack, pack, and prepend objects to
build and parse complex messages. Weve also seen how to color and manipulate patchcords and objects to help make
patches and message routing more easily visible. Finally, we've seen how to use the lcd object for simple drawing.
See Also
Name Description
gate Pass input to an outlet
pack Create a list
unpack Break a list into individual messages
prepend Add a message in front of input
lcd Draw graphics in a patcher window
Working with random numbers
Tutorial 10: Random Drawing
Introduction
In this tutorial, we will further explore drawing using the lcd object. However, instead of explicitly drawing shapes, we will
look at ways of automatically generating draw commands using the random and drunk objects.
Many different art forms use random and pseudo-random techniques for generating interesting or unexpected content. We
will see how to use the random object to produce a range of numbers for source material, since this is the method used
within Max to create random material. The drunk object provides a way to perform a random walk through a number range,
which can provide the unexpectedness of random number generation while avoiding undesired large jumps in the number
generated.

Drawing with random


Take a look at the tutorial patcher. At the top left of the patcher is a patch that uses the random object (colored green) to
generate a random number. When we hit the button connected to it, the output of the object is a number between 0 and
999 giving us a range of 1000 potential random numbers. That is the purpose of the object argument; it sets the range of
numbers the object can generate.

Each time you click on the button, the object generates another number. If you want to change the range of the output, you
can change the argument or you can send a new value into the right inlet of the random object. If we enter 20 into the
connected number box at the top, we can see that hitting the button will now generate numbers between 0 and 19. Now,
lets use this to generate some interesting graphics in the lcd object at the bottom-left of the patch.
The section of the patch labeled with the 1 comment is an automated graphics generator for the lcd below. A metro object
provides a steady stream of bang messages into five random objects, each with a range that is appropriate to the size of the
lcd object (which is 320 pixels wide and 240 pixels tall). The output of the the first two random objects are manipulated
with some math objects to create the numbers we need; everything is then packed together to create a list of seven numbers
(via the pack object); the message paintoval is placed before the list (via the prepend object), and then sent to the lcd.
In order to see what the seven numbers in the list represent, we should check the lcd reference text. We can do this by
unlocking the patcher, selecting the lcd object, then choosing Open lcd Reference from the Help menu. This displays the
lcd manual page, where we can review the paintoval message.

According to the reference manual, the arguments are left, top, right, bottom and color (sent as a list of three values
representing the red, green, and blue amounts of the color to be used). Looking at the automated drawing code, we see that
the first random object provides the left and right location (with 5 pixels added and subtracted to provide a 10 pixel-wide
shape); the second random object is similar, but provides the top and bottom locations for the shape. Finally, the last three
random objects create three random numbers (in the range of 0255) that will create a random RGB color for drawing.

When we turn on the metro with the toggle box, we see that the lcd quickly becomes filled with small (10 pixel) circles of
random color. This is a great example of truly random location and color selection. But what if we want to exert a bit more
control over the drawing location?

Drawing with drunk


There are many types of random behavior that can be modeled by the computer. The random object provides the closest
approximation to "pure" randomness we can get; every number within its range has an equal probability of being selected.
An alternative to the random object is the drunk object, so-called because it allowed you to perform the drunken walk
through a range of numbers; this randomization (technically a variant of something called brownian motion) characterizes
many "random" processes in nature.

Just below our random example (at the top left of the patch) is a second test patch for the drunkobject. If you click on the
connected button, you will see that it gives us a random number based on the range provided by its first argument (an
argument of 1000 gives us numbers between 0 and 999). Hitting the button a second time, however, gives us a somewhat
different result: we still get a random number, but it remains within the range of +/- 20 of the previous value (the second
argument). Continue hitting the button, and you will see the value will always stay within 20 steps of the previously chose
number. The second argument to drunk gives us the maximum step size for each receipt of a bang.
As with the random object, both arguments to drunk can be changed by connecting number boxes to the provided inlets.
In the case of the drunk object, the second inlet changes the range value, while the right (third) inlet changes the step value.
If we change the range and step sizes to smaller numbers (like 10 and 2 respectively), we can see how the output is clamped
to a smaller range when we click the button again.
We can wipe the lcd canvas clean by clicking the message box labeled clear below section 1 in the tutorial patch. The top-
right patcher (labeled 2) shows how we can use the drunk object to perform another automated drawing task. In
appearance, it is very similar to the drawing routine that we used to demonstrate the random object, merely with one object
substituted for another. After clearing the lcd object, start the metro by clicking the toggle above it. The lcd object is sent
paintrect messages with a list of generated integer values; the resulting rectangles move around the lcd, but never make a
large leap because they are constrained by the small step size (20 by 15 pixels) of the drunk objects. You will also note that
the color changes very slowly, because the color arguments created are also constrained by the step size (5) of the drunk
objects.

More random drawing


The third set of automated drawing objects is at the lower-right of the patch (labeled 3). This section of the patch looks
somewhat more complicated, and uses a new drawing message for the lcd object: framepoly. If we reopen the lcd reference
page again, we see that this message expects a series of x/y pairs for creating a polygon frame, where each x/y pair
represents a corner or vertex. Our automated routine uses eight random objects to create four pairs of coordinates, these are
combined into a list (with pack), prepended with the framepoly message (with prepend), then sent to the lcd. Rather than
embed the framepoly message with color information, we separately calculate a random set of three values, make them into a
list, and create an frgb (for foreground RGB) message that is also sent to lcd.
This routine takes a different approach to the random point selection. Rather than randomly selecting any point on the lcd
surface, the random numbers generate a value from 0-9, then multiply the result to complete the coordinate selection. In
the case of horizontal (x) coordinates, the value is multiplied by 32; for vertical (y) coordinates, the value is multiplied by
24. Thus, the lcd surface is divided into a 10x10 grid, and all coordinates are "locked" into this grid.

When we turn on the metro for this section of the patch (via the toggle object above it), we see that the polygons frame is
drawn in the generated (random) color, but we also quickly see the result of limiting the random number selection: the
graphic takes on a web-like quality, especially noticeable along the edges. By slightly changing the way we use the random
object, we have implied some control on the generated result.

A slightly different result can be seen if we replace the random objects used for coordinate creation with drunk objects.
Replace all of the random 10 objects with drunk 10 2 objects. Now, when you run the patch, the creation of the web seems
even more controlled. You can further tweak the drawing function by replacing the color generators, changing all random
255 objects to something like drunk 255 15. This will cause the color to change smoothly, giving you a different perspective
on the generated drawing.

Conclusion
Weve learned a little more about drawing in the lcd object, using the paintoval (to create small circles), paintrect (to create
small squares) and framepoly (to create jointed lines) messages. More interestingly, weve also learned to have Max perform
the drawing for us, using the random and drunk objects to generate coordinates and colors on the lcd surface. Weve also
seen, using ranges and multiplication, that we can manipulate the random number generation to fit application-specific
needs. It should be no surprise that the random and drunk objects are at the heart of many generative music and graphics
applications.

See Also
Name Description
random Generate a random number
drunk Output random numbers within a step range
Creating procedural code
Tutorial 11: Procedural Drawing
Introduction
In this tutorial, we will be using several new objects to perform procedural drawing with the lcd object. The counter object
will provide enumerated step processing, the line object will allow us to create smoothed output, and the scale object will
allow us to change the range of output. Finally, we will introduce a few mathematical objects that will help us create some
common shapes that require simple trigonometry.

We often use programmatic and procedural constructs to perform tasks in our programs; these can present new
opportunities for graphic display, but can also be used any time we need to count through a set of numbers, create a
numerical trajectory, or scale values. Whether used for audio visualization, controller feedback or just an interesting bit of
art, procedural code can serve as both a useful tool and an inspiration.

Using counter to draw


Take a look at the tutorial patcher. This patch has a few areas that help us understand some new objects, and another large
drawing patch. At the top-left is a small patch that demonstrates the counter object. When we click on the left button, the
object produces numeric output that increments by 1 for each bang message it receives. When the output reaches 9, the
next bang will reset the output to 0. The arguments we've provided here to the counter provide the minimum and
maximum numbers for the output. When the object hits its maximum, it will loop back again to the minimum number. This
allows us to use counter to create loops of values.
The counter object is somewhat unusual in that it can accept a variable number of arguments:
If you have one argument, it sets the maximum value of the counter.
If you have two arguments, they set the minimum and maximum values of the counter.
If you have three arguments, they set the direction, minimum and maximum values of the counter.
Our test patch for counter includes an additional button (colored blue) and two number boxes to set values of the object.
This is a great opportunity to use the assistance on inlets to find out what they do. If we unlock the patch and hover over the
third inlet (which has both a button and number box connected), the assistance says Resets Counter to Number on Next
Clock. This lets us change the current value of the counter while it is running.
If we change the number box to 5 then hit the first button, we see that the output is the number 5 regardless of what the
previous value was. This is how we set the state of the counter on the fly. Clicking on the second (blue) button (which sends
the bang message) will reset the value to the minimum: 0 in this case.

The number box on the right allows us to change the maximum value on the fly. This would be useful for drawing situations
where you might need to change the size of the drawing area, or when you are sequencing an effect and need to change the
number of steps. When we change this value and repeatedly hit the button, we see that the new maximum value is honored.
The drawing patch has a section labeled 1; this is where we use the counter object to procedurally draw in the lcd object.
When we start the metro (using the connected toggle object), we see that the patch begins drawing small circles in the lcd,
with the color gradually changing as it progresses. When the drawing reaches the bottom of the lcd, it restarts drawing at
the top.

Four different counter objects are used in this patch; one to set the drawing location and size, and three others to change the
color. Understanding the leftmost counter is the most important: it counts from 0 to 767, giving us 768 steps total. The
drawing X/Y location is calculated with the % (modulo) and / (division) objects, breaking up our lcd object into a 32x32
grid. If we look at the output of the counter and the % and / objects, we can see that the system works by creating two loops
from 0 to 31, one going quickly (from the % object) and the other incrementing each time the first loop has repeated (the /
object). The values are multiplied by 10 (to get the pixel location for the top-left location), then have 10 added (to get the
pixel location for the bottom-right). This sets up a lcd-filling grid of circles for our program to draw.

The three other counter objects cycle through three different number ranges to give us an ever-changing color palette. These
counter objects use the three-argument initialization, where the initial 2 forces the counter to move upward to the
maximum, then downward to the minimum. This is what causes the drawing to slowly change colors as it draws. Clicking
the button labeled "reset" will restart the simulation from the beginning of the loop.

Using scale to draw


If we return back to the top-left of the patcher, the second small example shows the use of the scale object. This object
allows you to set a range of input values and a range of output values; the object will then correctly scale the values so that
they are mapped into the new number range. In our example, input values between 0 and 100 are mapped to the range of -
1.0 to 1.0 this is determined by the arguments provided to the object. If you change the input number box, you will see
that a value of 0 yields an output of -1.0, a value of 50 will give us a value of 0.0, and a value of 100 will give us a result of
1.0. These numbers are mapped in a linear fashion across the range we provide.

If you choose to exceed the input range, you will find that the output continues to use the calculated range effect, thereby
allowing you to exceed the expected range without failing. Hence, a value of 150 will translate into an output of 2.0, while a
value of -100 will give you a value of -3. The arguments are used to determine the mathematical expression used for
conversion.

The section of the drawing patch labeled 2 uses scale to draw a shape based on sine wave calculations. A counter object
produces output ranging from 0 to the maximum value (set using the two number boxes to the right of the metro object).
This is scaled from 0.0 to 6.283185 (2*pi), then sent to a sin object, which calculates the sine of the input value. This
produces a sine wave that varies from -1.0 to 1.0 in range. This value is sent to another scale object which maps this range
to the integer range 0 to 319 the size range of the lcd object. This is used to provide the X locations of the line. A similar
set of functions are used to set the Y location. These numbers are then inserted into a list (using pack, prepended with the
lineto message (using prepend) and then sent to the lcd.
Clear the lcd using the message box containing the clear message. Turn on the metro using the toggle, and watch the
result. The result is a sine-based drawing over the entire lcd face. You can set the maximum values of the procedure by
altering the number boxes that are attached to the counter objects. Note that the number boxes change not only the
parameters of the counter objects, but also the maximum input range expected by the scale objects immediately below (the
third inlet for the scale object determines the maximum input range expected).
The two counter objects, when set to different maximum points, create different interlocking sine waves that draw across
the lcd. These curves are called lissajous patterns and simulate what happens when out-of-phase oscillators are fed into the
X and Y inputs of an oscilloscope. This is a great example of using simple math functions to create complex drawings.

Using line to draw


Going back to the top-left of the patch, the third example gives us a chance to see the line object in action. The line object
takes a pair of incoming values (configured as a value/time pairing) and slowly moves from one value to the next. If a single
value is received, it jumps immediately to that value. However, when a second value is provided, it is treated as the number
of milliseconds to move to that new value.

Clicking on the first message box (labeled 100 1000) will move the line from the starting value of 0 to the target value
(100) over 1000 milliseconds. Clicking on it again will show no change, because the current value (which remains at 100) is
the same as the target value (it has nowhere to go). The line object is state aware, meaning that it understands its current
value, and will adjust its action based on the state of that value.

Clicking on the second message box (0 5000) will move the result of the line back to 0 over 5000 milliseconds (5 seconds).
Clicking on the first box will move us back to 100.

The third message box is a little more interesting. It uses a special function of the message box to create multiple
messages; when a comma separates values, they are treated as separate message, and will function as if two messages were
sent down the same patch cord immediately after one another. In this case, the value 20 is sent as the first message. Since
there is no time pairing, the current value out of the line immediately jumps to 20. Immediately afterward, the 50 2500
pair is sent, causing the output to slide from 20 to 50 over 2.5 seconds. We can also use the number box to immediately
jump the line to a new value; since no timing value is provided, it too will cause the current state to jump to the entered
value.

The section of the drawing patch labeled 3 is the most complex procedure weve yet seen. It depends on the idle mechanism
of the lcd object to do some procedural drawing. When the idle message is turned on (with the idle 1 message), the lcd
object outputs the current mouse location relative to the lcd object's canvas when you move your mouse over it. These X/Y
coordinates are sent as a list out the second outlet of the lcd.
The light blue patchcord out of the lcd connects our mouse coordinates to an unpack object back at the top. These values are
sent into our drawing code, which creates a set of values used to draw a pair of round shapes that follow the cursor. The line
object is used to slow the changes in the shapes, and causes them to slowly "zero in" on the current cursor location. Turn on
the idle message with the toggle box, then mouse around the lcd object to see how it reacts.
There are two very important things in this procedure. First, the use of the line object to slew the output values over a one
second (1000 ms) timeframe. This gives the results a more organic feel by causing them to interpolate over time. Secondly,
we use the cartopol (cartesian to polar) object to change the X/Y ("Cartesian") position of the cursor into a Distance/Angle
("Polar") pair of coordinates, useful for drawing contents in a circular domain. Once the polar coordinates are calculated,
they are scaled to match the size of the circular drawing area, then used as part of a complex, multi-message message box
to create the two eyes found in the middle of the lcd object.
The message box at the bottom of the code sends four drawing commands in sequence to the lcd. The first two draw two
background circles using the paintoval command at fixed positions (100 100 140 140 and 180 100 220 240). The last
three arguments to paintoval set the color (black: 0 0 0). The second two messages use the values from the pack object to
draw green "pupils" on the eyes. The four values provide the starting and ending angle for the pupils using the paintarc
message.

Understanding all of the functionality of this procedure may be difficult, but it is worth it this is another example of using
some mathematical programming to create a complex and life-like end result. Simple realtime graphics are made out of
building blocks of procedural code just like this; taking a set of input values and scaling them to your needs is critical for
many applications in Max.

Conclusion
Weve seen some fairly complex programming that provides controlled drawing functionality within an lcd object by creating
loops (counter), scaling input values to output values (scale), and interpolating numbers over time (line). Weve also
worked with a few objects that compute trigonometry. By using these new objects in combination, we can assert a lot of
procedural control over what we want to accomplish in our programs.

See Also
Name Description
counter Keep count based on bang messages
scale Map values to an output range
line Generate timed ramp
sin Sine function
cartopol Convert cartesian to polar coordinates
Introduction to video playback
Tutorial 12: Movie Playback
Introduction
In this tutorial, we will be focused on the display of movies using Apples QuickTime video playback tools. We will also learn
about using Maxs built-in file browser to find useful video content, and learn a few ways to manipulate movie playback in
realtime.

Apples QuickTime system is well-known as a movie-playing mechanism, but it also provides software developers with a rich
toolbox for playback and manipulation of many types of media content. The QuickTime developer tools were used to create
several objects for Max; one of the most important is the imovie object, which displays video content inside of a patcher. We
will use imovie to load and play videos as well as manipulate the playback speed and playback location. We will also learn to
load and switch between videos, opening the door for interactive performance patches.

While the imovie object provides a lot of functionality for working with video media within Max, the Jitter set of object
extensions for Max provide much more. Once you get comfortable with imovie, you'll find it easy to use its Jitter equivalent
jit.qt.movie, which allows you to not only play video but sent it into the Jitter matrix processing system to dynamically add
effects, perform compositing operations, and develop more advanced video-based systems.

Basic imovie operation


This file loads with a number of small patches and one large display area - this should initially be showing a number inside
cross-hairs. This display area is actually the imovie object, and it allows you to embed a QuickTime movie clip directly inside
a patcher. The number with crosshairs is a video clip that the object has loaded when we opened the patcher; it's called
countdown15.mov. We will use this instance of imovie, along with several control messages, to display and control
QuickTime movie playback.

Just above the imovie object is an array of message boxes that sends commands to the object. The top four messages
provide some basic commands: the read message will read in a specified movie file; start will cause it to begin playing; stop
will cease playing the file; dispose will remove the current movie from the imovie object's memory. Once you have disposed
of the movie, you can reload it again using the read command. Try clicking these message boxes. Note that start begins the
movie at the beginning every time you send that message.

Next is a vertical set of five different rate messages. The rate message tells the imovie object to change the playback speed of
the movie clip, where the value 1. means normal (forward) playback. A rate of -1. will play the movie backwards at normal
speed; rate 0.5 moves the clip forwards at speed. Start the movie's playback (with the start message), then click on the
rate messages to see the alteration. Note that sending the message rate 0. pauses the movie where it is. A subsequent rate
1. message (or any other speed) will pick things up where it left off.

When the movie reaches the end, you can click the start message again to restart it. However, just to the right of the rate
messages, we can see an alternative to constant restarting: using the loop message to cause the video file to loop over and
over. Click on the toggle box to turn on looping. Now you can see that the movie, upon reaching its end, will restart at the
beginning running forever.

The imovie object can also tell us things about the QuickTime movie currently playing. There are many different messages
that can be used to query imovie information; you can find out about them in the reference manual pages. One of the most
important pieces of information is the duration of the movie the amount of time for a single iteration of a movies
playback. This could be used to generate a music score, or just set up a display that helps show where we are in the film. In
any case, sending the duration message causes imovie to send the movies duration (in milliseconds) out the leftmost outlet
of the object.

Using the File Browser


The messages weve just tried give us basic control of the imovie object, but having to change the read message any time
that we want to add a new file would be rather onerous. One option is to change it to a read message with no argument; this
will open a dialog box that lets you pick any file on your computer system. However, perhaps the easiest way to add a new
movie to your imovie object is to use the file browser.
You can open a file browser window by selecting New File Browser from the File menu. This presents a window with file
names, file types, modification dates, and custom tags all files that Max determined might be useful for your patcher
programming.
Displaying everything (the default option) may not be that helpful, but if you search for specific files, you can normally
zero into the contents you need. For example, in the search box at the top right of the browser, enter in the file suffix .mov.
This is the file extension often used for QuickTime movies; searching for this text will display all of the files with .mov as part
of their name.

The browser is also able to do a search based on the type of file you need (rather than just its name). Clear out the search
box, then hit the + button to its right. Another pane of search criteria is displayed at the top of the window. The drop-down
menu at the left lets you choose the field to search if we change it to Kind, then select moviefile, we quickly get the list
of all movies, whether using the .mov extension or some other movie identifier. If this is a search you are going to use often,
you can add it to the file browser window by clicking on the + (Save Search) button at the bottom of the window; this allows
us to save searches for use later.

Now that we have the list of available movies displayed, we can grab a movie by name and drag it onto the imovie object to
open it. Click on one of the files by name (or any other column, really) and drag it to the patcher window. When you hover
over the imovie object, you should see a blueish border appear in the object this means that it can be a recipient of the file
you are dragging. Releasing the mouse at this point will load the movie file into the imovie object.

Using the mouse to alter rate


During our first experiments with this patch, we used rate messages to determine the speed of playback; we also noted that
rates greater than 0. caused forward playback while rates less than 0. caused reverse playback. We are going to use this
concept, along with some mouse-tracking, to perform some realtime video scrubbing/scratching.

In the section of the patch labeled 1, you will see that a metro is set up to poll a mousestate object, and the second outlet
(the horizontal location of the mouse) is being used. The value is displayed and scaled (through a scale object) into a value
that will range from -2. to 2. (or greater, if your screen is wider than 1024 pixels wide). The result is used to create a rate
message that is sent to the imovie.
If we turn on the metro with the toggle box, we will see the horizontal mouse location being tracked in this portion of the
patch. Start the movie (with the start message) and turn on looping (with the toggle box connected to the loop $1
message). Move the mouse across the screen you will see it speed up, slow down and reverse direction depending on the
current mouse position. Going through zero (producing positive numbers that move through zero and back into higher
negative numbers) produces the typical scratching function weve come to identify as a useful VJ manipulation.

Using the mouse to alter playback point


Turn off the metro in section 1, and turn on the metro in section 2. This small sub-patch is very similar to the first we are
tracking mouse movements and turning them into video playback messages. In this case, we are using the vertical mouse
location to set the current playback position. In order for this to work correctly, you will need the duration of the current
movie, which you can get by clicking on the duration message box (found just above the loop selector at the top of the
patch).

Once the proper duration has be communicated to our patch, we can see that changes to the vertical mouse position will be
scaled to the range 0 10000 (for the "countdown" video) and sent to the imovie inlet. The imovie object treats incoming
integers as current position settings, and the movie will immediately jump to that position.

By default, however, once the position is set it will just keep playing at its current speed. The behavior of QuickTime movies
is that they are always running at their current rate; if you want to completely control the playback location of the movie,
you will need to start by setting the rate to 0. If we do this (using the rate 0. message box), vertical mouse moves will now
allow us to maneuver through the movie in frame-by-frame steps.

Switching between several movies


Another way that we can control the imovie output is by loading and switching between several movies. Unlike many other
media-related objects, imovie can load several different movie files, then can use the switch message to jump among the
files to determine which one is active.

The segment of the patch labeled 3 is the area that shows how to load and cue multiple videos. In this case, four files are
pulled from the search path and read into the imovie object through the message box at the top. Next, we have a key object
watching user keyboard entry; the letters a, s, d and f (ASCII 97, 115, 100, and 102, respectively) are each mapped
using the select object to a switch statement (followed by a start message to restart the video). If you click on the four-part
read message box, you can see that the videos have been loaded. Now, using one of the 4 files, type a, s, d or f on the
keyboard to select the movie you want to display. You can do this as rapidly as you wish; since the movie files are already
loaded into the imovie object, there will be little latency when switching between them.
Conclusion
Weve focused on the imovie object, which allows us to play and manipulate video content. In addition to simply playing and
stopping movies, weve learned to alter the playback speed with messages and with mouse movement; weve also learned
how to use mouse movement to change the current playback position. Finally, we learned that imovie can have many movies
loaded, and a simple patch can accept keyboard input and perform high-speed movie switching. All of this builds on the
simple commands provided by the imovie object.

See Also
Name Description
imovie Play a movie in a patcher window
Working with multiple media files
Tutorial 13: Movie Sequencing
Introduction
In this tutorial, we will work with a few new objects: the rslider, umenu and loadbang objects. The rslider object allows us
to select a range of numbers using a single UI element. The umenu object allows us to pick an item from a pop-up menu
within a patcher. The loadbang object is a setup object it allows us to trigger messages when a patcher is first loaded. All
of these are important items for more complex patches and we will use them in the context of making some interesting
video-driven programs.

Providing user selections is important once your patch gets complicated or if you want to share your patch with others.
The rslider object is great for selecting loop points (since it gives you the ability to select start and end points with a single
mouse swipe), and the umenu object is perfect for selecting among a list of files or display options. Finally, loadbang gives
us the ability to set object parameters when a patch is loaded, allowing us to create patchers that require a minimum of
setup to get started with.

A few new objects: rslider, loadbang, umenu


Take a look at the tutorial patcher. This patch contains a few simple patches at the left, and two larger patches to the right.
Lets start by looking at the left-hand patches, where we are introduced to our three new objects.

The top-most patch is the example patch for the rslider object. Click on the surface, and you will see that the wiper will jump
to your current location much like the slider object that weve worked with in the past. However, if you click the mouse
then drag up or down on the surface, you will see that you can actually select a range of values reflected in the two outputs
of the object. The name rslider refers to the fact that this is a range slider, capable of selecting a range of values with a
single mouse movement. The actual range that the rslider covers can be set with a simple message (it defaults to the range 0
to 127), as we'll see later in the tutorial.

The next object is pretty simple, but very important. It is the loadbang object, and it sends out a bang whenever the patcher
file is loaded (hence the name). This is most often used for setting up values in a user interface in this case, we are loading
the number box with 55 (it would normally default to 0) each time we open the patch. We can also force the loadbang to
fire by double-clicking on it. If we change the connected number box to another number, double-clicking on the loadbang
will cause a bang message to hit the message box (containing the message 55), and the number box will again update to its
previous value.

Finally, the umenu is shown in the bottom of the three small patches. If you click on the umenu, it displays all of the
options available as a pop-up menu. Selecting one will produce two forms of output: the left outlet will send the index
number of the selection, starting at 0; the middle outlet will output a symbol containing the text of the menu option. The
umenu object has several interesting capabilities that are useful when working with file lists.

The items available for selection umenu object can be set in a number of ways; in the next section we'll look at how to
populated it automatically. First, however, unlock the patcher and open the Inspector for the umenu object on the left-
hand side. In the Inspector you'll see a section labeled "Items" not usually present in UI objects in Max; within this section
we can view the list of items contained in the umenu (small, medium, etc.). Click on the "Edit" button next to the list and a
window should open that will allow us to type in anything we want. Items in the umenu need to be separated by commas.
Add to the list (or create an entirely new one), click OK, and close the Inspector. You should see the umenu change to
reflect the new items we've just added.

Loading umenu with file info


The first large patch is labeled 1, and has two interesting sections: the top area is used to select movie files from a folder of
movies that ship with the Max distribution, while the bottom area is used to loop the playback of these movies within an
imovie object. Lets start by looking at the top section.

What we have here is a rather complete file selection system. A loadbang object is used to trigger a message box that sends
the message prefix ./patches/media to the umenu object. If we look at the reference material for the umenu object, we
see that prefix is an attribute that sets a menu-wide prefix that is added to the beginning of any selected item. It has a
second use as well it tells the umenu where to load files when it is told to populate (or, in our case, to autopopulate). The
umenu object has its autopopulate attribute set, so when the message is received, the umenu is loaded with the names of
every file in the folder pointed to by the prefix message.
As a result, we have a umenu loaded with file names from a folder called "media" inside of a folder called "patches" (these
folders are relative to the folder where Max is installed on your system). When we select one, three things happen, thanks to
the trigger object connected to the middle outlet of the umenu. First, the message dispose is sent to the imovie; this clears
the imovie object of any video file that is currently loaded into it. Next, the symbol (the s in trigger) containing the name of
the file with the folder prefix ./patches/media prepended to it is sent out. The read message is placed in front (via the
prepend object) and then sent to the imovie. Third, the trigger object sends a bang through a delay object, which delays
the message by 100 milliseconds; this gives the imovie object time to read in the movie. After the delay has expired, the
message box below is triggered. It contains a few initialization messages to imovie: length (to query how long the movie
is), loop 1 (to tell the movie to loop), and start (to begin playback). In this case, although we have a number box connected
to the left outlet, we arent doing anything with the umenu object's index everything is triggered by the middle (text-
based) outlet. Note how the trigger object is extremely useful in this case, allowing us to set up a complex series of steps in
the correct sequence: dispose the previous movie, read the new movie, find out its length, tell it to loop, start it.

Select a movie from the umenu, and notice that it will load and quickly begin playing, looping at the end of the clip. If you
select a different clip, the previous one with be disposed and the new one will start looping.

Using the rslider to set loop points


In addition to loading and starting the movie, that length, loop 1, start message had another consequence it forced the
movie length out the left outlet of the imovie object, and set a new chain of events in motion. This length message is used
to set up the size (i.e. the range) of an rslider, and set the object with its complete range selected (this is what the 0 $1
message does). We can easily change the contents of the rslider by clicking and dragging within it, therefore changing the
loop points that the imovie will use. To best see this in action, select the movie countdown.mov from the umenu at the
top this is the familiar movie that counts down from 10 to 1.

Now, if we click and drag in the rslider at the bottom of the patch, you can see that we change the start and end points of
the loop. The output of the rslider object is sent to a pack object and then used to create a loopset message, which changes
the looping "in and out points" honored by imovie. In addition, it rewinds the film to the start of the loop (the $1) message.
This section of the patch shows a very common use for the rslider object; it is initialized with the length of a media file, then
is used for playback start and end positions.

Setting things up: loadbang and screensize


Finally, we are going to see how loadbang (along with a few other messages) can be used to completely set up a patch for the
user when it is first opened. This patch (labeled 2, and on the right), takes the current mouse location and uses it to decide
where to place a movie within a 320 x 240 pixel display area. The mousestate is polled, and a rect message puts the
currently playing movie, in shrunken form, at the specified location within the imovie object.
To begin, one loadbang message is used to load the bball.mov movie file when the patch is first loaded. This way, you (or
your user) does not have to find the file themselves. Secondly, another loadbang is used at the top-right of the patch; it
sends a bang message to the screensize object. The screensize object outputs a list of four coordinates representing the
coordinates of your primary display. The last two elements in this list are, for all intents and purposes, going to give us the
width and height, in pixels, of our screen (e.g. 1024 and 768). The mousestate object, as we remember, puts out the
position of the mouse within that range starting at 0, so if we subtract 1 from the screensize we can properly scale the
output of mousestate into the range 0. to 1. - this is a common trick when working with mouse coordinates, as we seldom
use their actual pixel values; more often than not, we simply want to use them to control an entirely different range of
numbers.

Once the scale object has its maximum input set by the screensize object, the current mouse position will always yield
values between 0.0 and 1.0. These are then multiplied by 240 and 180 to get the upper-left-hand screen location for the
video placement within the imovie object. The 80 60 portion of the rect message sets the width and height of the rectangle
within the imovie - as a result, for a 320 by 240 window, our maximum input coordinates should be 240 and 180.
Turn on the metro object with the toggle to begin polling the mouse, and click on the start message. Move your mouse
around the display. You should see a small version of the basketball movie track your current cursors location, and always
be scaled correctly no matter what display you run it on.

Conclusion
In this tutorial, weve learned about three very important new objects: rslider for range selection, umenu for the creation
and selection of a list of items (or file names), and loadbang for initial state setup. In addition, we saw how the screensize
object can be used to find out information about the size of your display. We demonstrated them by creating some complex
video playback systems that controlled loop length and display positioning. These objects will be some of the most important
tools you will use on future patches.
See Also
Name Description
rslider Display or change a range of numbers
umenu Create and fill a pop-up menu
loadbang Send a bang when a patcher is loaded
screensize Output the monitor size
Patchers inside of patchers
Tutorial 14: Encapsulation
Introduction
This tutorial will cover the concept of encapsulation within Max. Encapsulation allows us to place sections of our patcher
within their own subpatch using the patcher object. This lets us hide parts of patcher logic that we no longer need to see, in
order to make our projects easier to read and more concise. We will examine the creation of a patcher that contains objects,
as well as using some editing tools to encapsulate parts of a patcher that no longer need to be seen.

Properly encapsulating your Max logic is important for keeping your patch files clean, easy to read and maintainable.
Encapsulated logic can be easily edited, and can also be saved off as separate files that can be reused in other patches.

Basic encapsulation
At the top-left of the tutorial, there are two small patches that do the same thing they both add 5 to the incoming number.
The patch on the left does it with a + object, while the patch on the right uses a patcher object. The patcher object (which
can be abbreviated "p", much as trigger can be abbreviated "t") is literally another patch embedded in the current patch. To
see the contents of a patcher object, you can double-click on it (when the patch is locked) to open the encapsulated patcher
object's window.

If we double-click on the patcher add5 object, a small patcher window shows the contents (in a window labeled add5 - the
name of the subpatch). It is a simple subpatch, with only three objects. The object in the middle is obvious it is the + object
that performs the addition. The objects above and below the + object are inlet and outlet objects, respectively. An inlet
object causes the enclosing patcher object to have an inlet, while an outlet object causes the enclosing patcher to have an
outlet. In this way, we can make patcher objects that act very much like built-in Max objects. Multiple inlet and outlet
objects will create corresponding inlets and outlets on the enclosing patcher object, arrayed spatially in relation to how they
are in the subpatch (e.g. the leftmost inlet object will correspond to the leftmost inlet on the patcher).
When working with inlet and outlet objects, it is useful to add assistance to them; in this way, the enclosing patcher can
display helpful information about the type of message that is expected by the inlet, or produced by the outlet. If you select an
inlet or outlet and then open the objects Inspector, you will see that there is a comment field available. Any text that you
enter in this field will show up as assistance in the patcher object during patch editing.

Performing encapsulation
Creating sub-patchers sometimes needs to happen after the logic is in place; perhaps your patcher has expanded beyond
where you originally thought it would go, or youve added logic that wasnt planned, and things are starting to get messy. In
these cases, it would be useful to be able to select a group of objects and quickly turn them into a single encapsulated
patcher. This can be done using the Encapsulate menu item.

Our example patch has an interesting drawing algorithm, where you move a puck around a rectangular area (using an object
called the pictslider), and small circles are drawn in the area randomly near the equivalent position in the lcd at the bottom
of the patch. If you need to clear the lcd, you can hit the space bar (ASCII character 32, captured by the key object and
triggered by the select object). The logic is rather messy, and it doesnt really help us to see it spread around the screen. We
are going to select a majority of the logic and encapsulate it into a subpatch.

There are two comment boxes (encapsulate from here and to here) that we will use to select our encapsulated logic.
Unlock the patcher, then select (using click-and-drag) all of the objects between and to the right of the comment boxes. 15
objects will be selected. Select Encapsulate from the Edit menu, and you will see that all of this logic is folded into a single
unnamed patcher patcher. If you lock the patch and double-click the patcher object (or command-double-click in an
unlocked patcher), it will open the subpatch and show all of the objects again, tied to the outside world using four inlet
objects and one outlet object. If, for some reason, we needed to reverse this process later, the De-encapsulate command
under the Edit menu will unravel the subpatch back into our main patcher, re-connecting everything correctly as it was
originally.

It is often useful to name our patcher objects; while this adds no particular value to the patcher, it will help you (and others)
understand the logic that is encapsulated into the object. To name it, just click inside the object, and add a first argument
that is the name youd like to use. Something like draw_logic would be perfectly useful for this example.

Creating our own subpatcher


When you know ahead of time that you want to work within a subpatch, it is easy to create a patcher object and work within
its editing window. At the lower-left is a pair of number boxes connected by nothing. We will make a subpatch here and
use it to convert one value into another.

Create a new, blank object in between the number boxes by double-clicking in the blank area and selecting the object box
(in the Basic section of the Object Explorer). In the new object box, type p mycalc - this will create a new patcher named
mycalc. A new window will appear for editing our new subpatch. Start with an inlet and outlet (both available from the
Object Explorer). Note that adding these to the patcher added and inlet and an outlet to the patcher object in our main
window. Next, connect the inlet directly to the outlet thereby making a thru object that does nothing except pass
incoming message to the outlet. Lets test this encapsulation in the main patcher window.

Now that our mycalc patcher object has an inlet and outlet, we can connect it to the number boxes. Connect the top
number box to the patcher inlet; connect the patcher outlet to the bottom number box. Lock the patch, and change the top
number box: we should see the bottom number box change to match. This shouldnt be a surprise, since our patcher object
encapsulates a straight line between the two boxes!

Lets go back to the patcher editing window and add some logic - if the window has closed, double-click the patcher object
to open it up again and unlock it. Start by selecting and deleting the patch cord connecting the inlet and outlet. Now, lets
add some math: create two new objects, a + 50 object and a / 7 object. Now, connect the inlet to the + object, the + to the /
object, and the output of the / object to the outlet. Weve changed our mycalc encapsulation from meaningless subpatch
into an (input + 50) / 7 patcher. The nice thing about doing this within an encapsulation is that we dont have to change
anything in the top-level patcher all of the connections remain as-is. Now, at our main patch, changing the top number
box will produce the new result without any further changes.

Conclusion
Encapsulation of patching logic accomplishes two things:
1. it allows us to work at higher levels without having to interact with (or even see) all of our objects; and,
2. it allows us to change our lower-level logic without having to change anything at the higher-level programming.
In working with patcher objects, you can either manually create and populate them, or you can select existing patcher logic
and use the Encapsulate menu option to automatically create a subpatch. In either case, you can further explore and
change the patcher code without any further changes to the higher level patch.

See Also
Name Description
patcher Create a subpatch within a patch
inlet Receive messages from outside a patcher
outlet Send messages out of a patcher
pictslider Picture-based slider control
Creating libraries of re-usable code
Tutorial 15: Abstractions
Introduction
In this tutorial, we will extend the concept of encapsulation to include abstraction the ability to have subpatcher logic live
in a separate, reusable file that you can then use inside of any patcher you like. Once saved outside as a separate file,
abstractions can be modified to use arguments to make a generic Max patch useful to your specific application. By using
abstraction for your most-used programming tasks, you will be able to reuse that work for future projects without any other
programming at all.

Abstractions are key to supporting your increased Max knowledge while maximizing your ability to reuse previous work. The
abstraction mechanism can make your subpatches look and act like built-in Max objects, and can also accept arguments to
further tune its functionality.

An overview of the big picture


In our tutorial patcher, you will see that there are three different patches. In this case, each of them do the exact same thing,
but at different levels of abstraction. The first section (labeled 1) is the fully-functional patch. If you turn on the metro with
the toggle, we see that the patch tracks your cursor around the screen and draws a scaled version of your mouse movements
in the lcd display. We make use of the bucket object in this patch; a simple example of the object is shown on the left next to
the lcd; in its most simple form, upon receiving a value, bucket always puts out the last value it received. This makes it
useful as a single-event delay object, which we use in the main patcher to construct linesegment messages that link the
current position of the mouse to its previous position.

In the case of section 1, we have a lot of logic on the screen, and it might be useful to encapsulate it into a subpatcher (as we
did in the previous tutorial). However, the patcher logic that polls the mouse and scales it based on the size of our screen
looks like something that could be useful elsewhere; it would be interesting to have it available for other patches without
having to copy and paste from one patch to the next.

This is where abstractions come into play. An abstraction is a subpatcher that is saved as an external file, and can be used
just like a standard Max object. As long as your abstraction can be found in the Max file path, you can type its name into a
new object box and it will be loaded directly into your patch. The abstractions used in this tutorial are in the same folder as
the patcher accessing them; a library of abstractions can easily be created by placing them in a folder (or a bunch of folders)
inside the "patches" folder of your Max installation, or anywhere else Max looks for files.

Using a simple abstraction


The second section of our patch (labeled 2) shows an abstraction at work. Turn off the metro for section 1, hit the space bar
(which will clear the lcd) and turn on the metro for section 2. You will see that the program works exactly as it did before.
The object called WTHITM (for "Where The Heck Is The Mouse?") is actually an abstraction of the scaling logic from
section 1. If you double-click on the WTHITM abstraction, a new patcher window will display the contents of this
abstraction. Notice that this looks very much like an encapsulation with one exception you cannot unlock the window to
edit the contents. This is because WTHITM exists as a separate patcher file living in the same folder as our tutorial patch.

Abstractions are meant to be shared among several patches, so you would not want to edit the contents in one patcher, since
this might break its functionality in other patchers. If you do want to edit an abstraction, you need to open the abstraction
file itself.

While there are several ways to open the abstraction file, we'll mention only two: We can open a New File Browser (from
the File menu) and type WTHITM into to the search window and then double-click on the patcher file that appears in
response to our query, or we can Alt/Command-Click on the title bar of the WTHITM patcher window - a pop-up will
appear with the patcher hierarchy from the abstraction leading up to the top. If we select WTHITM, the original file being
referenced will open within Max. However you choose to do it, open the WTHITM source file. You will again see the
abstraction contents, but now you can edit the logic. If you change something and save the file, all patchers that use this
abstraction will reflect the changes even if the patcher is currently loaded. You can see this in action by adding a second
inlet to the WTHITM abstraction and saving it. The instant that Max sees a new version of the abstraction, it reloads it and
adds a new inlet to the WTHITM abstraction in your tutorial patch.

While we have the WTHITM patch open, lets look at the documentation that has been added to the inlet and outlet
objects. If you open the inspector for the inlet, you see that there are several different types of built-in documentation. The
first is called Annotation; any text placed in the annotation field will show up in the Clue window when you hover over the
object. Text placed in the second documentation field, the Hint field, will display in a hint balloon when you hover over the
inlet object in a locked patcher. Finally, text placed in the Comment section doesnt display in the patcher; rather, this text is
shown as the assistance text when you hover over the inlet of the "object" in the higher-level patcher. It is wise to document
your inlet and outlet objects in often-used abstractions, since it can provide simple but effective documentation for your
reusable logic.

In our WTHITM abstraction, there is no logic that needs to know about the higher level patcher. However, what if we
wanted the abstraction to properly scale the output based on our lcd objects size? In this case, we would have to inform the
abstraction of the lcd display size, which we can do using arguments to the abstraction.

Using an abstraction with replaceable arguments


Section 3 of the tutorial patch is similar to section 2, but the abstraction used is called WTHITM_scaled, and includes two
arguments that represent the horizontal and vertical sizes of the lcd object. If we open the "WTHITM_scaled.maxpat" patch
(using the Open command in the File menu), we see something very interesting: the multiplication factors use #1 and #2
as placeholders for values to be provided as arguments. As you might expect, #1 is replaced with the value of the first
argument, while #2 is replaced with the value of the second.

The use of these replaceable values (called pound-sign arguments) is key to making abstractions that are flexible and
reusable. If you would have 319. and 239. hard-coded into the abstraction, you could only use 320x240 lcd objects to
display the mouse movements. On the other hand, if you forced the top-level patcher to perform the final scaling (as we did
in section 2), you are forcing the top-level patch to duplicate work that could be easily abstracted into the lower-level patch.
By using replaceable values in your abstractions, it makes the high-level patcher as simple as is practical.

Conclusion
By saving your logic in an abstraction, you can create modules that can be used in future work with little or no additional
programming. This allows you to parlay your Max knowledge into more efficient work in the future, and will help you create
programming systems that are modular and easier to maintain.

See Also
Name Description
bucket Pass numbers from outlet to outlet
Sending messages without patchcords
Tutorial 16: Remote Messaging
Introduction
So far in these tutorials, all messages between objects have been sent using patch cords. However, there is another way to
transfer messages between objects by using the remote messaging mechanism built into Max. There are specific objects for
this (called, not surprisingly, send and receive), as well as methods for sending a message box's contents to an object.
Finally, we use some objects that allow the storage of variable data, and can help use move values throughout complex
patches.

As our patches get more complex, we need to take advantage of more techniques to modularize and compartmentalize our
patches, making them easier to understand, maintain and extend. When our patches contain a lot of logic, maintaining patch
cord connections can cause unnecessary visual complexity. Using tools that allow message passing without patch cords can
clean up our patches without changing how they operate.

Playing with send and receive


The most common way to send messages without patch cords is through the use of the send and receive objects. If we look
at the tutorial patcher, the top left part of the patch shows a pairing of send and receive objects that pass an integer value.
When we change the top number box, the integer value is passed to the send fred object. This value is broadcast
throughout the Max environment, and can be received by any receive object with the name fred. In this case, the receive
fred object immediately below gets the message, and outputs it to be displayed in the attached number box.
Since a message is broadcast by name, any receive object sharing the send object's name can receive the message. Hence,
you can have more than one receive object for a message, and more than one send object sending messages using a single
name. In our test patch, the slider system connected to the send bob object does just that it sends the value (set with
either the slider or the number box) to all receive objects of bob messages. At the lower right of the patch are two different
receive bob objects: one connected to a slider system, while another is connected directly to a number box. Changing the
top slider value changes both of the receiving values simultaneously.
When working with pairs of send and receive objects, its important to realize that the message will be grabbed by any
receive object anywhere in the Max environment even in another patcher. To test this, open a new patcher (selecting New
Patcher from the File menu). Add a new object, and enter receive bob. Connect the output of the receive object to a
number box, then return to the tutorial patch. If you change our test slider, you will see the output received in the new
patch as well as all other receive bob objects in the main patcher.
When working with other peoples patches, you may see objects named s or r. Since the send and receive objects are so
popular, they have alias (or shorthand) names of s and r respectively. In addition to being easier to type, these shortcut
names also allow you to keep the object small in size!

Working with ; and forward


Another common use of remote messaging is to send the contents of a message box to one or more receive objects. Rather
than always having to connect message boxes to send objects, there is a special format of the message box that can
directly send messages to receive objects. This involves placing a semicolon (;) and the name of a receive object in front of
the message. Thus, ; bob 155 is the equivalent of sending the value 155 to any receive object named bob.
The large message box at the bottom-left of the patch is an example of direct message sending. Four messages are
generated: two are sent to lcd1 destinations, and two are sent to lcd2 destinations. If you click on the message box, you
will see that the two lcdobjects each receive the appropriate draw commands through their respective receive objects - the
top lcd (lcd1) draws a blue circle; the bottom lcd (lcd2) draws a green rectangle.
Another common need we might have is to send messages to one of several destinations based on some logical criteria. This
can be done using switching logic (e.g. the gate object connected to different send objects). However, we can also use the
forward object to route messages to selected locations. Just above our message box example is a forward object with
supporting logic.

You can select which named destination should receive the messages: the send message, sent to the forward object, will set
the destination name for any incoming messages. Once a destination has been set, you can send in messages to be routed
appropriately. If we click on the send lcd1 message, changes to the number box will cause a colored rectangle to be created
in the first lcd object. If we click on the send lcd2 message, it changes the output destination of the forward object to the
receive lcd2 object. Now, any changes to the number box will cause the creation of a rectangle in the second lcd object.

By a similar token, a receive object with no arguments can be used to receive messages from any named send or
appropriately configured forward or message box. The set message to the receive object allows it to "switch names", so to
speak, so that it can listen to different parts of the patcher. Next to our forward object is one such receive object. By
switching it between listening to bob and fred (using the message boxes) and then manipulating the number box and
slider object sending to those names, we can see how this works. Setting the receive to a name that doesn't exist (e.g. none)
will disconnect it from listening to anything in our patch. Note that in order for a receive object to be "switchable", it needs
to be created without an argument (otherwise it has no inlet).

The int, float, and value objects


Sometimes, when working with patch programming, we need a place to stash a value until we need to use it. While we
could use integer and floating-point number boxes, those objects have the possibility of having the user change the value
through their UI. In order to provide simple variable storage and recall, there are a set of objects specifically used for this
purpose. The int and float objects can act as temporary storage of values; values coming in the left inlet are stored and sent
out the outlet immediately, while values coming in the right inlet are stored without output. If you want to retrieve the value
stored in an int or float object, you need to send a bang message (such as from a button object) into the left inlet.
One of the advantages of the int and float objects is that you can initialize the value without using any other message. The
argument provided with the object gives it an initial value; there is no need to set these up with loadbang messages or other
functions. If we look at the int and float objects to the right of our patch, we can see how they work. Sending a bang into
them with the button objects outputs their initialized value. Once we start entering numbers into them from the number
boxes, those new values are stored inside the objects until we bang them again.

In our patch, just below the int and float object, we find a pair of objects called value. The value object is like a combination
of an int/float object and a send/receive pair each of the value objects has a name (in this case, joe), and any values
placed in one of the objects is shared with all of the other value objects with that name. One thing to notice is that sending a
message into a value object does not trigger output you need to explicitly force output by sending a bang message to the
object. In our test patch, change the value of one object then bang the other: you will see that the value is magically
transferred from one to the other.

Unlike the int and float objects, the value object can take messages of any type; symbols, integers and floats can all be
stored by the value object, as can a list. While this is convenient, it also means that you need to be careful about the objects
that you connect to a value object to display the output. Our test patch has number boxes connected to the value objects;
however, it might be better to connect a print object or other display object that can accept a diverse set of values.

Conclusion
Being able to send messages without having to connect patch cords can give us more flexibility in patch layout, and can also
allow us to produce and route very complex messages throughout our patches. The send and receive objects are the most
common way of passing messages around a patch, but the use of ; notation in message boxes and the use of the forward
object for routing can help minimize the visual complexity of our work. Finally, we saw how values can be stored in the int
and float objects, and how a value object can be used to both store and forward data that is sent into it. All of these objects
and techniques are important for working with complex patching systems.

See Also
Name Description
send Send messages without patch cords
receive Receive messages without patch cords
forward Send messages to specified receive objects
int Store an integer value
float Store a decimal number
value Share a number with other objects
Working with histograms and lookup tables
Tutorial 17: Data Structures And Probability
Introduction
In this tutorial, we look at using the itable object for data storage, data transformation and histogram tracking. The itable
object can be drawn into, or can be set using various formulae. We will also look at using the uzi object to quickly generate
many bang messages or streams of ascending numbers, both of which can be used to quickly create lots of algorithmically
generated data.

Using a two-dimensional data structure (like itable) gives us the opportunity to create data transformations that are easy to
set up. These transfer functions allow you to create irregular curves, probability tables that weigh the output based on the
input, and random patterns that are easy to visualize. Additionally, the introduction of the uzi object for the quick
generation of procedural messages helps us find a way to create the functions necessary to load these itable objects in
interesting ways.

The itable object used in this tutorial is virtually equivalent to the table object, which has its own window and can be typed
into a regular object box. The itable is used here simply because it appears embedded visually in a patcher, rather than in a
separate editor window.

Basic data structures with itable


In this tutorial's patcher, you will see a few display/drawing patches (labeled with numbers) and several small calculations
(labeled with letters). We will start working with the patch area labeled 1. This patch features an itable object; an object that
provides a visual interface to a two-dimensional data structure called a table. The table/itable structure gives us an X/Y
combination and a simple interface to this data: send in an number that represents an index on the X axis, and you will
receive the corresponding Y axis value.

When you first open the patch, the itable contains a random distribution of values. If we move the slider at the top of the
patch, it scans the itable values, and outputs the Y value from its left outlet for the X position represented by the slider. We
have this connected to a number box and slider, so we can see the results of the transfer function described by the itable.
Next to the input slider are a pair of message boxes with two-integer lists; these will set the location of the first integer (X)
to the value of the second integer (Y). Thus, with the first message box, the value at location 50 will be set to 80. If we click
on this message box, then move the slider (or number box) to 50, we can see that the output of the itable is 80. Likewise,
if we click on the second message box (100 20), we can see that an input value of 100 outputs a value of 20.
The clear message erases the itable view, but values are still intrinsic to the itable; when cleared, the itable simply
assigns a 0 value to every possible data point. Another way to change the values of the itable is to draw within the itable
itself. If you place the mouse inside the itable and click-drag the mouse, you can draw in the function contents you desire. If
you need to make straight lines, you can hold down the shift key while you move the mouse, and click the mouse to commit
the new line. Using these drawing commands gives you an easy way to manually create interesting transfer functions.

Below the patch are three small patches that utilize uzi objects to generate all of the points in the itable. If you click on the
A button, a function is created where the input value is the same as the output value. Clicking on B produces the opposite:
input values ranging from 0-127 are converted into a 127-0 range. The C button produces a random distribution similar
to the starting contents of the itable object.

Creating formulas with uzi


Lets look more closely at these function-generating routines, and particularly at the uzi object. The uzi object, as its name
implies, is made to rapidly fire off bang messages. A single bang to an uzi objects input will generate as many bang
messages as are specified in the object's argument; therefore, uzi 128 will send out 128 bang messages from the left outlet.
In order to keep track of the current bang number, the rightmost outlet produces a count (starting with 1) this output is
what we are using for the index to the itable object. In patch segment A, this count is decremented by 1 (so that it begins
with 0, the start of the itable range), and used for both the X and Y values, giving us the straight line output for a function.
The B segment is similar, except that the Y value uses the !- object to subtract the incoming value from 127. This results in
a similar ramp, but heading in the opposite direction the lowest X values have the highest Y values. The C segment uses a
random number generator to create random values as part of the output list. It has to use the swap object (which simply
"swaps" the left and right values it receives) to reverse the order of the list contents so that the random object's output is
used for the Y value instead of the X value.
Lets alter the B segment a little to see how different functions could be created. If we change the !- object to be a division
(/) object with an argument of 4, we will reduce the range of the Y values to only 1/4th of the vertical range. Likewise, if we
multiply (*) the value by 2, we will hit the Y range maximum halfway through the X values. Obviously, with a little
manipulation, you can use uzi and a little math to create many complex functions.

Histograms with table


The right-hand patch area (labeled 2) provides an interesting use of the itable system, as well as several formula patches
and a new object called histo. The histo object performs a histogram function: it keeps a count of how many times a number
has come into its input. Whenever a value comes into the input, the object produces the number of times it has been received
out its right outlet followed immediately by the value itself out its left outlet - it can then be fed directly into the itable
object, where the left inlet becomes the X and the right inlet becomes the Y. If you use the slider at the top of the patch to
scratch in a lot of numbers, you will see the itable object show the relative distribution of the values you have sent. If you
want to clear the itable and the histo objects, you can hit the return key on your keyboard (ASCII 13).
Turn on the metro object with the toggle at the top of the patch; this will cause bang messages to be sent to the itable
object. This produces a random quantile output to be generated a random but weighted output value from the itable
object. The result is that the lcd area below the itable will begin drawing small circles where the density is roughly
equivalent to the distribution curve shown in the itable routine. If you want to clear the lcd, you can hit the space bar (ASCII
32) to restart drawing.

As with our first drawing patch, we have a number of smaller patch areas that can be used to generate functions into the
itable object. However, instead of drawing discrete functions, these generate fuzzy distributions by sending random and
semi-random values into the histo object; this histogram is then fed to the itable to generate a probability map. Segments D
and E use random and drunk, respectively, to generate the values. Clicking on the attached button objects repeatedly will
show how each affects the distribution curve random hits all of the values fairly evenly, but drunk is much more lumpy
in its distribution. Again, we can clear the histogram at any time with the return key.

Patch segments F and G take a somewhat different approach. Segment F generates two random numbers, then uses the
minimum object to choose the lower of the two numbers. This will tend to emphasize the lower numbers in the range;
repeatedly clicking on the connected button will show the lower numbers being used more often than the higher values.
Segment G does the opposite: it uses the higher of two random numbers by putting them into the maximum object. Thus,
repeatedly clicking on the connected button will tend to generate more high numbers.
Finally, segment H creates an average of 3 random numbers by generating the numbers, adding them together, then
dividing the sum by 3. If you clear the itable and repeatedly hit the H button, you will see a bell-shaped curve being
generated, since the average of three random numbers will tend to be in the middle of the range. This is a simple type of
Gaussian (or normal) distribution, and is commonly found in statistical research when most subjects fall within the middle
of a range of possible values.

In each of these cases, having the metro running during our function generation should cause the drawing to simulate the
distribution curve in the itable object. To test more radical curves, you can draw sharp lines within the itable object to force
certain output curves; you can also use the slider to shade in parts of the equation, causing the drawing output to shade in
segments in response to the new distribution curve.

Conclusion
Many different processes depend on the ability to create functions that transform an input range into an output range. In
previous tutorials, we saw how the scale object could do this for us. However, if we want to manually change the distribution
of values, or if we want to use a formula for data transformation, we need to use a more complex system. As weve seen in
this tutorial, the table/itable objects serve this purpose perfectly, giving us the ability to either manufacture or manually
draw a transfer function.

Using the histo object, we also saw how we can generate the sort of distribution curves that serve as common random
techniques in generative art and stochastic music. Whether the fuzziness of true random generation, or the tendencies found
with more discrete math, these curves can be used to both generate and guide results to a desired outcome.

See Also
Name Description
table Store and edit an array of numbers
itable Graphic display of a table
uzi Send many bang messages
swap Swap position of two numbers
histo Create a histogram of numbers received
minimum Output the smallest value
maximum Output the highest value
Using databases
Tutorial 18: Data Collections
Introduction
This tutorial covers two of the most useful objects in the Max world: coll and route. The coll object allows for the indexed
collection of data; you can think of it as a small and fast database for message data. The route object is also tied to the
concept of indexing it will send data out of a specific outlet based on the index (first entry) of a list.

Indexed data is very useful for complex routing of information. Often data is already indexed for you: MIDI controllers
normally index the value with the controller number, while note information is often indexed by the MIDI channel. Using
indexing for data can also help when sending messages throughout a complex patch by creating an indexing system, you
can send data around indiscriminately, and have the route object find and decode the data as necessary.

Basic coll handling


There are several small- to medium-sized patches scattered throughout the interface for this tutorial. We will be starting with
the patch at the top-left side.

The first patch (labeled 1) introduces the coll object. Three message boxes are connected to it. If you click all three, you will
load the coll object with three value sets. The easiest way to see what is stored in the coll is to double-click on it; it will open
an editing window that will show you that the first number was stored as an index, and the second number was stored as a
value. To programmatically retrieve a value, you send an index value into the inlet the output will be the value (or values)
stored at that index location. If you use the number box to send a 0 to the coll object, it will output 20 (the value at index
location 0); 1 and 2 will output -50 and 33 respectively. This is the most basic, and most common, use of the coll object
as a storage mechanism for indexed value sets.

The patch labeled 2 is slightly different in that it uses symbols, rather than numbers, as the index value. Click on the three
store message boxes, and again double-click on the coll to see the stored data. The data is similar to the first coll, but the
indexes are symbols (words) rather than numbers. Now, if you click on the message boxes to the left (foo, bar, biz), the
coll object will output the correct value for each of the symbols.

The third patch (labeled 3) has already-stored data in it. If you select any number between 0 and 3, the coll will output the
data for that index. In this case, rather than a single number, the coll is storing a string of symbols (in this case, the opening
soliloquy of Shakespeare's Richard III); all of the symbols are output as a list. Prepending a set message to the list allows us
to display the value string in a message box.
In order to store the data within the patcher (as weve done with this example), you have to set an attribute in the coll
object's Inspector. Unlock the patcher, and open the Inspector for the coll in patch 3. You will notice that the attribute
labeled Save Data With Patcher is selected. When this attribute is set, any information stored in the coll will be written to
the patcher file when it is saved, and is immediately accessible when the patch is opened again.

Using coll for drawing and playing


The center section of our patch (section 4) uses a coll to control both a drawing and a MIDI playback function. In this case,
the coll is loaded with some pre-defined data; however, instead of having been stored in the patcher, this data is loaded
from an external file containing data from an EEG readout. The filename is eeg.txt, and that filename is used as the
argument for the coll, so the data is read into the coll when it is first initialized.
At the top of the patch is a simple little self-incrementing counter system. Each time a number is generated, it increments
itself by an amount determined by the upper-right number box. By default, the increment is one, since that is what the +
object contains. Playing through the data set at this speed, however, can take quite a while, as our data file contains many
thousands of lines. If you change the number box to 15 (meaning that you increment the steps by 15 at each bang
generated by the metro ), you will see the EEG pattern much more clearly. The output of this number generator is used to
retrieve the indexed data from the coll, and is sent to both the drawit subpatcher and a simple MIDI player
(makenote/noteout). The MIDI player just uses the number (scaled to the 0-127 range of MIDI) as the MIDI note, while
the drawit subpatcher uses the incoming value as the vertical offset of a scrolling drawn circle. Start the metro (with the
toggle) and notice how different "increment" values for the counting change the way the EEG data unfolds. If you need to
restart the file at the beginning, the message box labeled 0 will reset the int box to 0 again.
Storing data into a coll for later use is the best way to deal with large datasets. This EEG capture, which represents over
18,000 data points, would cause your patcher to be very large if it was stored in the patcher's file. Instead, the data can be
captured into a coll, saved in a text file (using the write message), and read into the coll at runtime (used either as an
argument, or using the read message).

The next patch segment, labeled 5, shows a few more tricks that coll has up its sleeve. This coll has a name cues that
manages 8 different cues handled by the rest of the patch (double-click the coll object to look at what's stored inside). You
can use the connected number box to fire off the messages, but you can also use the three message boxes to walk through
the cues. The start message moves you to the beginning of the coll contents, while the next and previous messages move
forward and backward through the cues. This allows you to step through the coll in sequence, even if the entries are not
numbered sequentially, and will automatically loop back to the start when the end is reached. This is the easiest way to
implement a sequential step-through of a colls contents. Without worrying about the route object just yet, step through the
sequence using the start, next and previous messages and observe how different actions are triggered by the output of the
coll object.

There is also a small patch just to the right, where another coll is also named cues. If you double-click on this coll, you will
see that it has the same contents. In fact, because it is named the same as the previously viewed coll, it is actually sharing
the contents of the coll much like the value object shared data through a naming convention. Using named colls that share
their information allows you to have easy access to a dataset in different places in your patch, or even within subpatchers.

Message routing with route


The small patch in the lower-right shows the functionality of the route object: as you click on the message boxes, the
messages are matched based on their identifier (the first item in their list); if the identifier matches one of the arguments to
the route object, the message is stripped of its identifier and the remaining data (in this case, an integer) is sent out the
outlet. The route object has one outlet for each argument, as well as a final outlet for items that don't match. This patch
shows what happens if an unrecognized message is received: the zeppo message is not enumerated in the route object, and
therefore cannot be routed. Rather than ignoring the message, it sends the entire message out the right outlet possibly to
be used by another route object, or perhaps to be sent (as we have in this case) to the Max window with the print object.
Patch segment 5 also uses the route object to take messages from the coll and parse them to perform actions on different
objects in the patch. As we saw inside the coll, the data contains a symbol (m1, m2, m3 and pick) and a data item (0/1 for
m1-m3, and bang for the pick symbol). When this message is received by the route object, it uses the first element (the
symbol) to determine the output routing, and sends the rest of the message through that outlet. Hence, a message that
begins with m1 will be routed through the first outlet, while a message that begins with pick will be routed through the
fourth.

If we use the start and next messages to walk through the cues coll, we will see that a sequence of actions is performed
based on the first segment of the message. The metro objects are started and stopped, and the random object is triggered
twice. You can see that the route object is useful for taking undifferentiated message contents and routing them where they
might be useful.

Conclusion
The coll object is a powerful way to work with indexed messages and data; the object provides way to get specific messages
or to step sequentially through the contents. You can share the contents between named coll objects letting you have
access to this data throughout your patch; coll can also read its data from external files. We also saw how the route object
allows you to track and move messages based on the contents of the message, helping you to route the data that you need to
different objects based on an index.

See Also
Name Description
coll Store and edit a collection of data
route Select outlet based on input matching
Scheduling events
Tutorial 19: Timing
Introduction
In this tutorial, we will be working with time objects that deal with time, and a set of objects that work with a metrical
timing system built into Max. Additionally, we will look at some of the decision-making object that use logic operations to
determine program flow.

As weve seen in earlier tutorials, the use of time is an important part of working with Max programs; time-based objects can
help create generative music and drawing actions, and can be used in conjunction with user actions to create playable
programs. The metrical timing system in Max provides a centralized 'musical' timing system that can provide transport
controls, bar/beat feedback and can even cause scheduled events to fire at specific points in time. Part of this is the ability to
define specific times and time durations in metrically-significant ways.

In addition to the time functions, we also cover some of the boolean comparison objects objects that create logical results
based on comparing and testing input values. These are especially useful when working with time-based objects, since you
will often want to make operational decisions based on comparisons between the current time and some desired time or sub-
time function.

Some new objects...


The left-hand side of the tutorial has five small patches that show the operation of a handful of new objects that deal with
time in Max. Patch 1 provides an example of the pipe object, which can be used to delay the throughput of any message or
list for a certain amount of time. The argument provides the default delay time in this case, 1000 milliseconds (1 second).
If you change the value of the left number box, you will see your changes reflected in the output 1 second later. The delay
time can be changed with a value sent to the right inlet an integer value is used to set the number of milliseconds of delay
time. Change the right-hand number box to 2000, then change the left input you will now see the changes occur after a 2
second delay.

The next small patch, labeled 2, is an example of the delay object. This is very similar to the pipe object, except that it is
specifically tailored to delay bang messages. Like pipe, the delay time can be changed by sending an integer value into the
right inlet.

Patch 3 shows the clocker object, which is closely related to the metro object. The primary difference between clocker and
metro is the output: while the metro object produces bang messages at regular intervals, clocker outputs the overall
elapsed time (in milliseconds) since it was started with a bang. Clicking on the stop message will stop the clocker, while
sending a new bang message to clocker will restart the timer and the elapsed time measurement.

The patch labeled 4 demonstrates another object that counts elapsed time: the timer object. This object takes bang
messages in both inlets; the left inlet starts the interval to be timed, and the right inlet stops the interval. The timer object is
therefore equivalent to a stopwatch; click the left-hand button to start the clock, wait a few seconds, and then click the
right-hand button to see how much time has elapsed. Note that timer is a slightly unusual Max object in that its right inlet
is hot (produces output), not its left inlet.

The fifth patch shows some of the most common boolean objects in action. The > (greater-than) object implements a
comparison function; it outputs a 1 if the incoming number is great than the number used as an argument, or a 0 if it is not;
the object therefore performs a test, reporting TRUE (1) or FALSE (0). The < (less-than) object is the inverse, reporting true
or false (1 or 0) depending on whether the input is lower than the object's argument. Both of these symbols are in common
use across mathematics. The remaining logical objects will probably be more familiar to programmers. The == (equals)
object reports a 1 only when the incoming number is equal to the argument, while the != (not equals) is its inverse it
reports a 1 when the incoming number is not equal to the argument. As with many Max objects, a new comparison operator
can be supplied by a number sent into the right inlet of the object.

The final two logical operators are && (logical AND) and || (logical OR). In the first case, the && object will output a 1 only
if both numbers sent into the left and right inlets are non-zero; otherwise, it reports a 0. In the second case, the || object will
output a 1 when either the left or the right inlets are sent non-zero values. In all other cases, this object will output a 0.

Change the number box at the top of the patch containing these objects and you'll see how they behave. Notice how the only
time all six operators yield a 1 is when the input value is 10.

Metrical Timing, Part 1


The large patch on the right (labeled 6) is a performance patch that uses all of these new objects (and some old ones) within
the context of the metrical timing system. Start the patch (using the large yellow toggle at the top); you will hear a steady
beat out of your default MIDI synthesizer, with variations that occur at different times throughout the performance. The
performance is looped, rerunning itself every 16 measures. In order to understand this rather complex patch, we first need to
understand the metrical time system.

Metrical timing is based on a central time-keeping object the transport and its ability to broadcast time information to
other objects that are expecting timing information. Many of these listening objects are already familiar to us (metro) or
have been introduced in this tutorial (clocker). We have used these objects in self-clocking mode, where they use a timebase
expressed in milliseconds to produce output at regular times. When used in conjunction with the transport object, however,
time is expressed using metrical notation: values such as 4n (for a quarter-note) can be used as an alternative to millisecond
timing notation.

The transport object is the central time keeper, and provides time in bar/beat/tick format all driven by a tempo and a
time signature. Hence, if a transport is set to run with a time signature of 4/4 and at a tempo of 120 beats-per-minute,
each beat will take 500 milliseconds, and a measure will take 2 seconds (2000 milliseconds). In order to see all the ways the
transport controls this patch, we need to break it down into sections.

Our big checkbox starts the process mainly because it starts the transport. The transport accepts a 1/0 message for
start and stop, which is perfect for control by a toggle. The toggle also starts the metro to the left (part of the red section
of the patch), which uses 4n as the timing argument. In the past, weve used milliseconds for the metro object's timing, but
in this case, the 4n notation means that it will send out a bang every quarter note, based on the timing broadcast by the
transport. The output of this metro goes to two places: to a message box that creates a MIDI note 70 (via makenote), and
back to the transport. Why does it get routed to the transport? Because a bang message received by the transport will
cause it to output the current time, which we display in three number boxes connected to the first three outlets of the object.
This time is displayed in bars, beats and ticks, respectively. There are 480 ticks per beat (480 pulses-per-quarter-note, or
ppq, by default).

Next, lets look at the green section of the patch. This uses the bar count (as output by the transport), and uses the > and
< objects to determine if we are between bars 4 and 8. If we are in that range, it turns on another metro that is clocked at
16n (16th notes). This generates a random number used to create one of four values (using the random and select objects);
these numbers are sent to the makenote object to generate MIDI notes. That value is also sent to a pipe object with an
argument of 4nd, which delays the values by a dotted-quarter note. This output has 7 added to it, causing output that, when
sent to the MIDI synthesizer, sounds a perfect fifth above the original. The result is a rapid-fire set of notes for a four-bar
segment of the loop.

Lets now dig into the blue section, which is the part of the patch that forces the sequence to loop. The head of this section
of the patch is a new object: timepoint. The timepoint object takes a metrical time as an argument; its sole purpose is to
generate a bang message when that metrical time is reached by the transport. In this case, when we reach the beginning of
the measure 17 (i.e. after sixteen measures), a four-note chord of numbers is sent to the makenote, then a bang message is
sent all the way back to a message connected to the right inlet of the transport. This message (0.) tells the transport to
immediately jump to tick 0. of the sequence, i.e. bar 1, beat 1 and tick 0. This is how we force the sequence to loop: every
time we hit the 17th bar, we are immediately sent back to the beginning.

Metrical Timing, Part 2


Next, we should decode the brown section of the patch. It uses key and select objects to watch for the space bar (ASCII
32) being depressed. When this happens, a timer object receives a bang on both inlets. Because Max objects transmit
messages in right-to-left order, hitting the space bar simultaneously stops the timer with a bang to the right (and outputs
the elapsed time) and restarts it for another measurement with a bang to the left. The object outputs the elapsed time in
milliseconds; we divide 60000 (the number of milliseconds in a minute) by the time to get a bpm (beats-per-minute) value.

However, we want this bpm value to fit in a sensible range, so we use the split object, and only use values that are between
30. And 200.. If we are within this range, split will output the number out its left outlet, and the value gets used to create a
tempo message that is sent to the transport. This will immediately change the playback tempo of the sequence, and will
change the relative speeds of many (but not all) of the objects used to create our sequence. If the timer outputs a value
outside of the split object's range (for example, if we haven't hit the space bar in a while), it will be sent out the right outlet
of the object and discarded.

One of the reasons that not all of the sequence is changed is because some of the patch functions use standard (millisecond)
timing rather than metrical time. The right-most (blue-and-purple) section of the patch is a good example. A timepoint
object is fired when the transport time is at bar 6, beat 3. This starts a clocker that runs for 10 seconds (10,000
milliseconds), producing a two-note chord every quarter-note (4n). The timepoint object also sends a bang to a delay 3000
object, which produces a two-note chord 3000 milliseconds after it receives the message. At a very slow tempo, this may
occur only a few beats after the timepoint is fired, while at rapid tempo, if may take many bars. This is a good example of
how metrical and standard time can be mixed and matched for interesting generative results. Note that the clocker object's
running time is compared against a > object to switch itself off after 10 seconds... a timer object tracking the interval
between the start and stop of the clocker object confirms this.

The Importance of Overdrive


Another thing that can cause variant behavior in this patch is the Overdrive setting, found in the Options menu. If
Overdrive is checked (on), event processing and calculations are given priority over screen-drawing and graphical processes.
When Overdrive is unchecked (off), drawing processes get the same priority as event handling. Depending on the nature of
your patch, Overdrive may provide better performance for time-critical event handling tasks.

Since our tutorial patch is, in fact, time-critical, it will perform best with Overdrive turned on. If Overdrive is off, you may
see that the transport output display doesnt always occur on the 0 tick, and you may find that playback gets jerky when the
density of notes is high or you perform other tasks on your computer (such as opening another patcher in Max). Modern
computers are incredibly fast, but our ears are very sensitive to timing discontinuities. Therefore, when working on patches
that sequence events in a time-critical way, it is normally advisable to turn Overdrive on.

Conclusion
In this tutorial, we covered an extensive new system within Max: the metrical timing system. This provides a centralized
timing control for your Max patch, coordinating the generation of events and easing the creation of musical sequences. We
also learned about several new time-based object, including pipe, delay, clocker, and timer, which can be used (either with
or without metrical timing) to create sequenced actions. Finally, we saw the use of boolean comparison and logical operator
objects to aid in decision making within a complex patch.

See Also
Name Description
pipe Delay numbers, lists or symbols
delay Delay a bang
clocker Report elapsed time, at regular intervals
timer Report elapsed time between two events
> Compare numbers for greater than condition
< Compare numbers for less than condition
== Compare numbers for equal-to condition
!= Compare numbers for not-equal-to condition
&& Perform a logical AND
|| Perform a logical OR
transport Control a master clock
timepoint Bang at a specific time
split Look for a range of numbers
Creating a presentation interface for a patcher
Tutorial 20: Presentation Mode
Introduction
This tutorial is about the Presentation Mode feature of Max. Using Presentation Mode, you can create a UI specific to
performance that is completely different from your programming model.

One of the difficulties of creating a good performance patch has always been hiding your programming so you would only
be presented with useful performance controls. This is especially true when it was desirable to have large controls and clear
signal routing. As we will see, many issues regarding performance layout are solved by including objects in the Presentation
Mode and arranging them separately from their role in the program.

Overview of the patch


This is a patch similar to some of the drawing patches weve recently used; it scales your mouse movements to perform
drawing on an lcd object. In this case, the "paintbrush" is a box (a framerect, in lcd terms). Rather than simply drawing
boxes in the lcd, the size, shape and color of the boxes are constantly being changed based on the settings of the one
horizontal rslider and two vertical slider objects at the top of the patch. These boxes and the state of the metro object
polling the mouse are all initialized when the patcher is opened with loadbang and loadmess objects (loadmess objects
simply transmit a message, rather than a bang, when the patcher opens). With the metro running, you move your mouse
around to see that the drawing is constantly shifting in response to your mouse movements. If you squint your eyes, it might
even seem Mondrian to you

This patch, however, also shows one of the limitations of typical Max programming. The logic for the patch covers most of
the working space, and somewhat overwhelms the result that is drawn in the lcd workspace. One option to make this more
useable would be to hide all of the logic with encapsulation and resize the user interface elements. However, this may change
the logical layout of the patch, and may make it more difficult to easily expand later. What we need is a way to create a
performance interface that doesnt interfere with our patchs logical layout.

Using Presentation Mode


Max solves this problem by providing a special user-interface view of the patch: Presentation Mode. We enter presentation
mode by clicking on the small icon at the bottom of the patcher that looks like a whiteboard on an easel. When we do this,
we will see the patcher logic disappear, and the user interface elements in the patcher move into a more convenient layout
for performance. Clicking on the icon again returns you to "patching" mode (the normal way of looking at patchers), where
we can edit the logic of the patch. Presentation Mode simplifies the process of making a user-focused view of the patch.

When we are in the normal ("patching") mode of our patch, we can define the items that will appear in Presentation Mode.
Unlock the tutorial patch; you will see that the user interface elements have a pink halo. This is the indicator that an object
will be included in the Presentation Mode. Lets add a few objects to the Presentation Mode.

Two objects that would be interesting in our performance patch are the two number boxes that display the current box
sizing. These number boxes are just below the two scale objects in the middle of the patch. Select one of the number boxes,
then choose Add to Presentation from the Object menu. If you switch to Presentation Mode, you will see this number
box, but the size and location remains unchanged from where it is in the normal mode. It would probably make sense to
move this box under the rslider that controls its range. You can click and drag the number box in Presentation Mode just
like you can in "patching" mode you can even resize it if you like. Changes in size and location will not affect the layout in
the normal patcher. You can check this by switching back and forth between the two modes.

Return to the "normal" mode and select the other number box. Again, select Add to Presentation Mode, then switch modes.
You can move and resize this number box as well, probably moving it underneath the rslideras well. When you are in
Presentation Mode, you can lock the patch (just like you can in "patching" mode) by clicking on the lock icon at the bottom
of the patcher. This way, you can move the controls without altering the screen layout.

When in Presentation Mode, you can add objects to your patcher that are then automatically added to Presentation Mode.
Unlock the Presentation Mode view, then double-click to bring up the object palette. Add a comment object, and edit it to
create a Current Size label. Move this to the area of the patch with the new number boxes are so that their use is more
obvious. If you return to Patching mode, you will see that the object exists in this layer as well, in the position that it was
originally created. It also has the reddish halo, showing that it is included in the Presentation Layer.

View changes
What do you do if you want to work on both the "patching" and Presentation view at the same time? Max has a little trick up
its sleeve it allows you to have multiple views of the same patcher open simultaneously. With the patch window selected
for focus, choose the New View option in the View menu; it will open a new window with all the same patch contents. In
fact, it is the same patcher, as you can see by the contents of the lcd object and the state of the various number boxes. If you
change the patcher on one window, they are reflected in the other. You can have one of the windows in Presentation Mode
(to tweak the performance layout) while working on the patcher's logic in the other. The use of multiple views is also useful
for working on large patches that might overwhelm your screen; instead, you can open two views and scroll to different
regions of the patch; be assured that all of your changes are occurring on a single version of the patch.

Conclusion
Presentation Mode provides the means to create easy-to-operate performance interfaces without destroying the logical
layout of your patch. Objects in Presentation Mode operate the same as outside of it, but can have different sizes, geometries
and locations whatever is necessary for making the best interface layout. Additionally, the ability to have multiple views of
a patch gives you options for more efficient programming and access to large patches even on small screens.

See Also
Name Description
Routing messages
Tutorial 21: Controlling Data Flow
Introduction
In this tutorial, we will learn some techniques for regulating data flow within a Max patch, using the gate, switch and router
to direct events. We will also examine user interface elements that can be used to manage this control, including the
radiogroup and matrixctrl objects. These objects will be used to vary the drawing commands used for an interactive
drawing routine.

Part of creating an interactive (or performance-based) Max patch is presenting options, and allowing for selection from
among these options. The gate and switch objects control event routing from and to single data sources, while the router
object performs routing among a matrix of connections. All of these routing objects are far more useful once we have a way
to simply and obviously control the routing hence, we use the radiogroup and matrixctrl objects as the visible switching
controls for the actual control objects.

The old gate and switch


Take a look at the patcher for this tutorial. This is a large-ish patch that implements two drawing routines. Lets focus on the
left-hand drawing system (labeled 1) first.

The metro at the top of the patch fires off bang messages that are sent to a patcher called mousedraw. The contents of this
subpatch should look familiar it scales the mouse movements of your screen geometry to the size of the lower-left lcd
object (using our previously made WTHITM_scaled abstraction), then describes a dimensional list +/- 6 pixels from the
calculated location. This is the sort of thing that weve done several times in previous tutorials. The output of this subpatcher
is sent into the right inlet of a gate object, where it is sent to one of four potential prepend objects. These objects determine
if a square or circle will be drawn, and if it will have a frame or a filled shape.

The purpose of the gate object is to select which of the four (if any) prepend message will receive the dimension list. The
input into the left inlet of gate will route the events coming into the right inlet to the selected outlet; a setting of 0 will turn
off output completely. Turn on the metro using the toggle object at the top. Using the number box connected to the left
inlet, you can choose a number between 1and 4 to see the result in the lcd objects display.
Connected to the input of the number box is a user interface object with five small circles; this is a radiogroup object, and it
is used to select a single number among a discrete set of options. If you unlock the patch and check the radiogroup objects
inspector, you will see the option Number of Items is set to 5. This attribute determines the number of options provided.
Returning to the patch and locking it, you can see that selecting one of the radiogroup options outputs the number of the
selection option, starting with 0. This is a perfect way to control the output of gate, and can be used for quick selection of
number of choices when doing patcher routing.

To the right of the gate-based drawing routine is a similar system based around a switch object. Stop the mouse drawing
(by setting the radiogroup object to 0 - the top selection) and clear the lcd object (by hitting the space bar). Once the lcd is
cleared, select one of the non-zero radiogroup options connected to the switch object. You will see a random-based
automated drawing routine laying in circles on the lcd object. Option 1 uses a drawing routine based on the drunk object,
while option 2 uses a routine based on the random object. If you want to stop the automated drawing, you can select the 0
option, and nothing is sent to the lcd object.
The switch object is the inverse of the gate object; where the gate object routes one input into many outlets, the switch
object is used to choose the routing of many inputs into one output. In this case, both of the patcher objects are producing
output messages, but only one subpatcher will have its messages sent to the prepend object. As with the gate object, the
selection is controlled by the value sent to the left-hand input, and a value of 0 will prevent any messages from passing
through the switch.

Using router
In some cases, you need to route many inputs into many outputs and potentially all of them simultaneously. The drawing
patch on the right hand side features a metro connected to three drawing patcher objects - the same three subpatchers from
our previous patch, in fact. The are connected to the three right-hand inputs of the router object. There are five outputs from
router object, the first four of which are attached to the familiar prepend objects that determine the drawing shape to be
used. The number of inlets and outlets are determined by the arguments used to instantiate the router object. The key to
making this patch operate is the grid-shaped user interface object connected to the leftmost inlet of router - this is the
matrixctrl object, and it allows us to specify a two-dimensional "grid" of connections using a message format understood by
the router object.

You will notice that the grid has three vertical lines (corresponding to the three inputs) and four horizontal lines
(corresponding to the four outputs). If you click on the intersection of two lines, a small puck is displayed, implying that a
connection has been made. So, for example, clicking on the top-left intersection connects the leftmost input to the leftmost
output, causing the mousedraw patcher to produce framed rectangles (when the metro is turned on).
Turn on the metro with the toggle box labeled 2 and experiment with setting and unsetting different boxes in the
matrixctrl object. Notice that one major difference between router and gate/switch is the ability to simultaneously route
several inputs to several outputs. Select the top-center connection, and you will see the drunken painting of framed
rectangles. Now, select the connection in the middle of the second row the painted rectangle has a circle inside of it. You
may need to clear the lcd (via the space bar) to see it more clearly. Try different combinations of input and output
connections to see how the matrix selection affects the painting process.

If you look in the Max window, you can see how the matrixctrl passes messages to the router. The objects communicate
using the system of inlet outlet state, where a state of 1 makes a connection and 0 breaks the connection. Unlike gate and
switch, the input and output numbering begins at 0, not 1: a connection between the left inlet and the last outlet in our
example, therefore, would be set by sending the message 0 3 1 to the router.

Conclusion
In this tutorial, we have seen a number of useful objects for routing messages within a subset of the logic in a patcher. The
switch object selects from several inputs, based on the value sent to its left inlet. The gate is switchs inverse it will take a
single input and route it to one of several outlets. If you need more complicated matrix-like routing, the router object can
pass messages arriving at multiple inlets into any (or all) of a set of outlets.

The radiogroup object allows for a visual interface to objects like gate and switch. The matrixctrl object provides a visual
interface for matrix-style routing. The combination of router and matrixctrl provides one of the most flexible (and useful)
message routing systems available in Max.

See Also
Name Description
gate Pass input to an outlet
switch Accept messages from a specific inlet
router Route messages to multiple locations
radiogroup Radio button/check box user interface
matrixctrl Matrix switch control
Creating complex mathematical statements
Tutorial 22: Designing Equations
Introduction
This tutorial covers the creation of equations: mathematical statements that evaluate an expression based on input values.
The key to equations in Max is the expr object, which provides a wealth of mathematical functions and a write your own
mechanism for developing complex statements.

To this point, we have created somewhat complex mathematical processes using individual math objects (+, *, etc.).
However, in many cases, we can collapse a number of objects into a single mathematical equation, eliminating a lot of
unnecessary complexity in our patches. The tool used for this simplification is the expr object, which uses a specific syntax
for creating an equation that accepts multiple inputs and can produce very complex results.

Overview of the drawing patch


Take a look at the tutorial patch to see the work we have ahead of us. This patch is broken into four portions of patcher logic
and an lcd object; communication between the parts is accomplished using value objects and pairs of send and receive
objects. To see the patch in action, turn on the metro at the lower left of the patcher using the toggle box, then hit the space
bar to trigger the events at the top of the patch. The result will vary from small scribbles to large-format abstract line-and-
circle drawings. Each time you hit the space bar, the lcd will clear and a new, related drawing will begin to appear.
The comment box at the top of the patch shows three lines of mathematical equations:
x = sin(A*y)-z*cos(B*x);
y = z*sin(C*x)-cos(D*y);
z = E*sin(x);
These expressions compute three values (x, y, and z) based on applying some simple trigonometric functions to their
previous states as well as five fixed values (A, B, C, D, and E). When plotted onto the lcd object (with z visualized as a circle
of variable size), we can see that a wide variety of patterns can be created. This equation generates something called a
strange attractor - in essence an iterated function where the previous outputs of the equation combine with five variables
(called coefficients) to generate a variety of shapes that exhibit chaotic behavior.

Lets examine each section of this patch. The lower-left is obviously the key to making things draw it generates bang
messages from a metro that are sent to the compute and draw receive objects, as well as into a subpatch that slowly varies
the color of the drawing (more on this later). After the subpatch is evaluated, the compute section of the patch (in the
middle) receives a bang. This section updates the equation for the next round of drawing by triggering a number value
objects, sending their output through equations encoded in the expr objects. These then update the x, y, and z values for
drawing. We'll examine how these expr objects work in a moment.
The send object named draw sends bang messages to the drawing routine at the top-right of the patch. This triggers the
newly calculated x, y and z values which are scaled, packed into command messages, and then put through a send object to
the receive object attached to the lcd. This is just a shortcut to the input of the lcd, which performs the drawing commands
that were generated above it.

Finally, the top-left section of the patch controls the action when the space bar is pressed. It is a good example of the right-
to-left execution of events in Max; when the key object outputs a 32 (meaning that the space bar has been depressed), a
button is used to generate a bang message. This, in turn, performs seven actions in order from right to left: the generation
of 5 random values (E to A) that are scaled from -4.0 to 4.0, the transmission of a clear message to the lcd object, and a
reset of the value contained in the x, y and z value objects. In essence, the space bar is the overall reset key for this patch,
in that virtually every segment of the patch is affected when that key is hit.

Using expr for equation creation


Now lets look into the expr objects themselves. While they look complicated, the argument for each of the expr objects is a
relatively simple equation. The important thing to realize is that the $ references simply refer to an incoming message, along
with its message type and inlet number. So, for instance, using a reference named $f1 means that the equation should use
an incoming message ($) that is a floating-point number (f) retrieved from inlet number 1 (1). Once you realize that the
complexity of the equation is simply its reference to incoming messages, the format of the expr statement is a little more
comprehensible.

The operations used in our expr statements are limited to the sin (sine function), cos (cosine) and * (multiply) functions;
however, there are dozens of operations available. You can use the common math operators (+, -, * and /), logic (&&, ||),
bitwise comparison (&, |) and other C language math functions such as abs, sin, cos, and pow. The documentation provides
a complete list of the available functions.

In the case of our tutorial patch, the three expr objects use eight different variables (x, y, z, A, B, C, D, E) to create the three
target values (x, y, z). There is an interesting bit of feedback here: the target variables are not only used for the drawing
routine, but are also used for the next round of computation. The five variables A through E only change when the space
bar is hit, so they provide an anchor to the drawing routine while the ever-changing x, y and z variables determine the
individual line and circle drawings for each round of computation.

Adding your own equation


In order to make the drawing a little more interesting, lets do some creative equation-making and use it to generate a
constantly shifting foreground color. We are going to tap into the x, y and z value objects that are updated each bang of
the metro.
Double-click the patcher object labeled changecolor at the bottom of the patch. We can see that the foreground color of the
lcd is being altered by a trio of drunk objects that are packed into an frgb message sent to the lcd. In here, we are going to
use an expr object compute the exp (E to the power of x) mathematical function. If you arent familiar with the properties of
E, thats OK its sufficient to know that it is exponential in nature, and that the value will rapidly increase as the input
value increases.

Delete the drunk objects, or disconnect them from the inlet and pack objects and move them out of the way. Create three
new value objects with x, y, and z as their respective arguments and connect the inlet object to their inlets.
Now create a new object and type in the following:
expr int(exp($f1)*5.)
Examining the argument/equation from the inside-out, we see that we are taking an incoming floating-point value ($f1),
using the exp function to create a new value (exp($f1)), multiplying it by 5.0 (*5.) then turning it into an integer (int). The
result will be a number that is approximately in the range of color values (0-255), but is predominantly low in that number
range. Copy this expr object two more times, then connect the output of the three value objects (x, y and z) to each of the
expr objects. Connect the outlets of the expr objects into the pack, and see what happens.

When we start the metro and clear the lcd, we will see that the drawing is colored, but tends toward the darker colors. Since
the coloring is influenced by the calculated x, y and z coordinates, the colors will tend to be brighter toward the extreme
edges of the drawing window. This is an example of calculating drawing commands that might be difficult using traditional
object-based programming, but is made quite easy using expr.

Conclusion
Using the expr object gives us the opportunity to create complex mathematical and logical equations without having to
resort to large object programming segments. The huge number of operations that can be performed, in combination with
the ability to define and use multiple inputs, allows for interesting results that might otherwise be cumbersome to create.

See Also
Name Description
expr Evaluate a mathematical expression
Working with game controllers
Communications Tutorial 1: Human-Interface Devices
Introduction
This tutorial covers the use of the Max hi object, an interface with HID devices connected to your computer. We will see how
to discover, select and process data from these common devices.

The HID (Human Interface Device) protocol allows a physical controller to connect to a computer without device-specific
drivers. The computer is able to query the device for information about itself, and can present this interface to the user. HID-
compliant controllers include joysticks, gamepads, some mice and graphics tablets, touchscreens, and a wide variety of other
interfaces designed to communicate with the computer for real-time control.

While HID devices are typically designed for use by the gaming community, they are often used by Max performers, since
they tend to be inexpensive and flexible; the most common HID device is a game-style joystick, which can provide an
extraordinary number of interface tools in a small, portable package.

Understanding the hi interface


Take a look at the tutorial. This entire patch is based around the hi object Maxs interface with HID devices. This object
provides all of the information we need to interface with joysticks, drawing pads and other controllers. In order to see the
devices that are available to the hi object, click on the info message box. The hi object will respond by listing all of your
available HID devices (as well as some information on them) in the Max Window.

The list begins with version information and a count of all the available HID devices. You will probably be surprised to see
that your computer already has a number of devices available. Each of these devices is listed by name, followed by a notation
of the number of elements for that device. Elements are the individual control parameters available from the device; for
example, a simple game controller might include four joystick elements (two joysticks with two axes each), six or more
button elements and other assorted controls. There are often more elements than physical controls these might be for
device feedback, or for communication with the connected computer.

We will want to have the hi object focus on a single device (in our tests, we used a Logitech Dual Action game controller). You
can send a message to the object with the name of the HID device, but it is easier to let the hi object propagate a umenu
with the available devices, and use that to select a controller. This is what the menu message does when you click on that
message box, the right outlet of the hi object outputs the messages necessary to load a umenu with the names of the
devices. Taking the second output of the umenu and sending it back to the hi object will allow you to select a device. When
you select a menu option, you will notice that the Max Windows says hi: focusing on your device name.

Polling and data


The hi object is similar to other system interfaces rather than producing a stream of messages, it waits to be polled (by
sending it a bang message), then outputs any changed values. In the second section of the tutorial patch, you can see that
weve set up a metro with a 20 ms interval to poll the hi object. If youve selected a device, you should now be able to move
your controller and see the results displayed in the number boxes below the hi object. The output is a pair of numbers: the
first number is the element index, while the second number contains the last value received from that element.

Another option for polling the hi object is to use its built-in timer; to do this, you send it a poll message with an argument
for the polling interval. This is a convenient way to set up the hi object with as few additional objects as necessary. Turn off
the metro, then click on the poll 20 message you will see that the values are still output, based on the objects ability to
self-poll.

While the hi object is running, lets use the output to determine the elements that are available with the device you are using.
The patch has a comment box that lists some common elements available with a game controller: in this case, a two-stick
control with a four-button game pad. Identifying the available elements is the first step to making a useful Max program for
your HID device. Operate the controls on your HID controller, and watch the element/value pair. Each move you make,
whether a continuous control or a button push, should produce output. If you are having problems seeing all of the
element/value pairs, you could connect a print object to the out of the hi object to view all of the output. If your HID device
does not match the parameters listed in the tutorial patch, you will need to determine which controllers are available and
useful to you.

Routing data for the applications


Once you have a list of controllers that work for your HID device, you can use them to control the rest of your application. In
our tutorial patcher, the route object is the perfect tool: it routes messages by the first item in a list (in this case, the element
index), and conveniently strips it off for us as well.

In this case, we use two elements (20 and 21, the joystick controller) to conduct the drawing, two elements (6 and 8, the top
and bottom gamepad buttons) for sizing the drawn circle, and two more elements (5 and 7, the left and right gamepad
buttons) for clearing and randomizing the color. If you look at the contents of the subpatchers, you will find that the
programming is very similar to what weve used in previous drawing patches. Since the hi object has turned complex game
controller movements into a simple stream of numbers, we can use it for any processing that Max can perform.

Conclusion
The HID protocol allows a standardized interface between a computer and relatively inexpensive hardware. The hi object
give a Max programmer the ability to use these devices for controlling and manipulating their performance patches. Since
there are useful HID devices for almost any task, hi provides an easy interface into physical control of your system.

See Also
Name Description
hi Human Interface (gaming) device input
Using standard serial devices
Communications Tutorial 2: Serial Communication
Introduction
This tutorial covers the the topic of using serial communication within Max. Any number of external devices use a serial
protocol (e.g. RS-232, Bluetooth) to communicate with a computer, and serial streams can even be used for low-bandwidth
communication between computers (think dial-up Internet!). Devices such as professional-level video mixers, DVD players,
and theatrical lighting systems use serial interfaces to receive commands, and microcontroller systems used by the physical
computing community rely on serial communication to transmit sensor data back to a computer.

For this tutorial we'll be using the example of serial communication with a very popular electronics prototyping platform
called the Arduino . It consists of a small microcontroller mounted on a prototyping board that is programmed by a C-like
language. It can communicate back to a host computer using a serial line over USB. Even if you don't have an Arduino, the
principles shown in this tutorial should give you enough insight to communicate with any serial device you need.

The Arduino Code


Before we look at the Max patcher, below is the code that we've used for programming our Arduino in this tutorial. In this
example, the Arduino doesn't read any sensor data or do anything particularly fancy: it just waits for any input from the
computer, then begins to stream a serial feed of numbers back. The code for the Arduino is here:

// Arduino Serial Tester


// rld, cycling'74, 3.2008

long randomvalue = 0; // random value


long countervalue = 0; // counter value
int serialvalue; // value for serial input
int started = 0; // flag for whether we've received serial yet

void setup()
{
Serial.begin(9600); // open the arduino serial port
}

void loop()
{
if(Serial.available()) // check to see if there's serial data in the buffer
{
serialvalue = Serial.read(); // read a byte of serial data
started = 1; // set the started flag to on
}
if(started) { // loop once serial data has been received
randomvalue = random(1000); // pick a new random number
Serial.print(countervalue); // print the counter
Serial.print(" "); // print a space
Serial.print(randomvalue); // print the random value
Serial.print(" "); // print a space
Serial.print(serialvalue); // echo the received serial value
Serial.println(); // print a line-feed
countervalue = (countervalue+1)%1000; // increment the counter
delay(100); // pause
}
}

Even if the specifics of the Arduino programming language are not familiar, you can look a the comments for each line and
see what's happening. The microcontroller initializes itself and opens up a serial port running at 9600 baud - this is the
speed at which it will communicate with our Max patcher. It then enters a loop in which it checks to see if we've sent it any
data and, once we do, starts streaming numbers back to the computer. It generates a number that counts from 0 to 1000
over and over again, a random number (in the same range), and an echo of the last value we've sent into the chip. These
three values are printed (as if on a terminal) over the serial line.

Looking at the serial object


Take a look at the tutorial. It consists of a serial object at the top with some supporting logic at the output that eventually
drives an lcd graph of the data coming from the Arduino. The Max serial object is used for communication with serial
devices that don't have special drivers that put them in another category (e.g. MIDI or HID). These generic devices
communicate with Max over a serial port, which is defined as the first argument to the object. In Max these ports are
lettered (a, b, etc.). Click on the print message box at the top of the patcher: the available serial ports on your computer
will appear in the Max window, along with their letter mappings. The Arduino should appear there, along with any other
serial devices you may have. If necessary, you can change the letter argument to the serial object by unlocking the patcher
and retyping the object.

In addition to the serial port, the serial object takes a number of additional arguments to set up the communications
protocol. The second argument of the object sets the baud rate, and needs to match that of the Arduino we're using. Since
we've told the Arduino to transmit data at 9600 baud, we put the same argument to our serial object. Additional arguments
to the object allow us to specify the number of data bits, stop bits, and the parity (even or odd) of the device we're talking to.
Since the Arduino is a fairly typical device, the default settings will work.

Transmitting and polling data


The serial object can both transmit and receive serial data. It transmits data by taking a byte (an integer in the range of
0-255) in its inlet and sending it over the selected serial port. These bytes can represent command values or can be
translated into ASCII (the same numbers output from the key object). In order to receive data, the serial object must be
polled (just like mousestate) - when a bang is received by the object, it empties its internal buffer of any waiting serial
messages and sends them sequentially (as bytes) out its outlet.

Assuming that our Arduino is loaded with our program (above) and connected to the computer, we should be able to talk to it
provided the serial object is set to the correct port. Turn on the metro object with the toggle box. As you can see from the
number box attached to the object, nothing will happen. This is because, in our Arduino code, we wait for the computer to
communicate with the microcontroller first.

Type the number 10 into the number box attached to the serial object and hit return. Assuming the serial object
transmitted the byte correctly, you should see numbers begin to appear out of the object. Turn on the toggle labeled 1 to
print the "raw" serial data in the Max window.

Formatting the data


You'll notice that the numbers appearing in the Max window from the "raw" serial output don't seem to make much sense.
This is because the Arduino is transmitting its values as ASCII, as if they were typed on a computer. Thus, the number 15 is
represented as ASCII value 49 ("1") followed by ASCII value 53 ("5"). Spaces between our three values are represented by
the ASCII for a space (32), and each set of three numbers is terminated by a carriage return and a line feed (ASCII 13
followed by 10). To use these values in Max, we need to first group them together and then convert them from ASCII into a
human-readable string.

Uncheck the toggle labeled 1 and check the toggle labeled 2. This prints out the output of the zl group object in the
patcher. The zl object is taking sequences of these ASCII values and grouping them into a list; the select object above the zl
forces the list to be output (and cleared) whenever a 13 (carriage return) is received. In addition, it eliminates line-feed
(ASCII 10) characters from the stream. Since the right outlet of select outputs anything not selected by the object, the rest
of the values pour into the zl. As a result, the Max window will show a list of ASCII values that should represent three
numbers separated by spaces (ASCII 32).

Uncheck the 2 toggle and turn on the 3 toggle. This shows the output from the itoa object, which takes the grouped list
and converts the integers into their relevant ASCII characters. As a result, the Max window should show something that
finally makes sense given our Arduino code: we should see a value counting from 0 to 1000 followed by a random value
followed by 10 (the byte we sent to the microcontroller earlier).

The itoa object creates a Max symbol, which is readable by us for the purposes of debugging, but not quite what we need for
our patcher. While we recognize that the message is a list of three integers, objects like unpack will not. The fromsymbol
object parses a symbol, separating different types of data based on white-space; as a result, our symbol becomes converted
into a list of three integers, which the unpack object can split apart. Note that the number boxes out of the unpack correctly
show our values. Change the number box at the top again, and you will see that the third value out of the serial object will
update accordingly.
Take a look at the drawing part of the patcher and see how it works. Like many of our lcd-based examples, it simply
visualizes the serial object's output, in this case making a graph based on the counter (x), random value (y), and echoed byte
(color). These values could easily be applied to control whatever you like.

Conclusion
The Max serial object provides the capability to communicate to and from standard serial devices within Max. It transmits
and receives data as single bytes; objects such as zl, itoa, and fromsymbol can be used to make sense of it all.

See Also
Name Description
serial Send and receive from a serial port
itoa Convert integers to ASCII characters
fromsymbol Convert a symbol into numbers/messages
Passing messages over a network
Communications Tutorial 3: UDP Networking
Introduction
This tutorial provides information on using a network for transferring Max messages. We examine the udpsend and
udpreceive objects, which provide sending and receiving of messages through the UDP networking protocol.

There are many reasons to implement computer networking in Max patchers. Often, in large projects, the work needing to be
done exceeds what a single machine can handle. In those cases, it can be useful to use an existing network to harvest CPU
cycles from unused machines, or to send synchronization messages between machines running subsections of the whole
performance patch. In addition, network protocols can be useful for sharing information among computers that are run by
multiple performers, even in separate locations. The udpsend and udpreceive messages wrap the standard UDP networking
protocol into a pair of Max objects, providing an easy way to transmit messages between two computers on a network.

General UDP Overview


The UDP protocol is a lightweight and flexible communications protocol used for Internet application-to-application
exchanges. It doesnt require a connection to be maintained between two machines; rather, the receiving application watches
a specific port for data packets (called datagrams) and treats them as incoming messages. The transmitting program is
required to specify the destination address and port of the receiver.

UDP isnt the most robust protocol: it does not guarantee that packets will arrive in any order, nor does it provide any means
of error or packet loss notification. However, it is a high-speed protocol, often used for networked audio and video content,
and happens to be easy to coerce into working with Max messages.

Sending messages of all types


Take a look at our tutorial. At the left is a udpsend object with several different Max message types connected. This is the
transmitting side of the network connection: the udpsend object takes Max messages, turns them into UDP datagrams,
and sends them to the destination specified by the machine's TCP/IP address and port (the arguments to the object). The
patcher named network_receiver is, as its name suggests, the receiving end of this patch. If you open the subpatcher, you
will see a udpreceive object watching port 7000 (you dont have to specify a network address the object assumes you are
watching the port on this computer).

When you click or change any of the messages connected to the udpsend object, you will see that they appear in the
subpatcher. Both simple and complex messages can be sent through the udpsend object; the multislider sends a 12-entry
list (prepended with the word multislider, so we can route that at the receiving end), but even the simplest message can be
packaged and sent over the network.

We should quickly discuss the network address used in this example. Since we want to test this locally on our own machine,
we need to use a network address that consistently represents the host machine. That address is the so-called IP loopback
address: 127.0.0.1. Whenever that network address is used, it means route this internally, rather than through an external
network. If you wanted to test this patch on a pair of networked machines, the udpsend object would have to be changed to
use the TCP/IP address of the receiving machine.

A basic chat program


The second segment of our tutorial patch is an example of a simple chat program. Again, there is a subpatcher that is used to
show the communications in action, although you could make some simple changes to have it work between two machines
you would only need to change the network address from localhost (the symbolic name for 127.0.0.1) to the appropriate
addresses of the connected computers. This part of the patch sends text (entered in a textedit object) on port 7003, and
receives messages on port 7002.

Unlike our first example, this shows bidirectional communication in action. When sending information between two
computers, each will need a udpsend and udpreceive object, with udpsend pointing to the other systems network address.
Additionally, by convention, bidirectional communications occur through two adjacent ports: 7002 and 7003, in this case. If
you open the chat_buddy patcher, you will see that it, too, communicates using localhost, but the port order is reversed.
Text is sent on port 7002 and received on port 7003. You can now type text into one of the chat patches (in the bottom,
white, textedit object), when you hit the return key, it will appear in the grey area of the other patch.

Conclusion
Max message handling over the network uses the udpsend and udpreceive object, taking advantage of the simple and
lightweight UDP protocol to flexibly pass any message or list type. Within a single system, the localhost network address can
be used, but the same mechanism will allow you to send messages across the network to any other reachable machine.

See Also
Name Description
udpsend Send messages over a network
udpreceive Receive messages over a network
textedit Enter text within a patcher
Visualizing data streams
Data Tutorial 1: Data Viewing
Introduction
This tutorial will examine different techniques for creating and viewing streams of numeric data in the Max environment. We
will look at the multislider object, which has modes for both creating and monitoring data values. We will also look at
monitor Watchpoints, a debugging tool that you can use to view the messages running through patch cords as they are
being generated.

When working with a modular system like Max, it is sometimes difficult to keep track of all of the messages that are being
sent between objects. Using the available tools for monitoring messages and values can help you fine tune a patch, or to track
down problems in a patchs operation. The two tools we will use multislider objects and watchpoints provide two
different mechanisms for tracking data: multislider is a good option for runtime (performance) monitoring, while
watchpoints a valuable during programming and debugging.

multislider as a data generator


Take a look at our tutorial. This patch contains a lot of objects that display and generate different types of graphs - in fact,
they are all versions of the same object, a multislider. We will start with the patch labeled 1, which contains is a sequencer
that will step through the various sliders of the multislider, and produce a note for each step using MIDI. The output of the
multislider is between 0 and 127 (the standard MIDI note range), and provides 16 steps of sequenced data. If you turn on
the metro with the toggle, you will see the step number being generated by the counter object, prepended with the fetch
message, and used to query the sixteen sliders in the multislider. This is the basis for most step-sequencing patches, with
either auto-generated contents (which is what the uzi-and-drunk-based section of the patch does), or by directly
manipulating the individual sliders in the object.

The right output of the multislider is used for this application. When used as a bank of sliders (meaning that the Slider
Style attribute is set to either Thin Line or Bar), the left outlet will send all of the slider values as a single list, and only when
a bang message or complete new dataset is received. The fetch message sends the value of an individual slider (numbered
starting at 1) out the right outlet.

Take a look at the multislider object's Inspector and note the different settings. Our object has a set of colors selected and
4 levels of alternating "candycane" colors selected. If you close the inspector and draw in the multislider, you can change
the melody that plays in the sequence. Clicking the button object connected to the uzi will generate a new drunken melody.

multislider for data viewing


Now look at the patcher area labeled 2, which is a monitoring patch for our mouse. Start the metro at the top of the patch
with the toggle, then move your mouse around the screen. You will see that the two drawing areas on the top track the
current X and Y mouse locations (output by our WTHITM abstraction), while the larger graph area at the bottom displays a
four-line running display, scaled and modified by the logic above it.

In previous tutorials, weve used the lcd object for drawing our tracking information in creative ways. However, in this case,
we are using the multislider object instead. The most common use for multislider is as a bank of sliders, but it has a few
modes that are useful for displaying information from a stream of data. These modes are listed as options for the Slider
Style attribute (in the inspector); they are the Scroll options, which accept incoming values, append them to the end of the
displayed data, then scroll the display to make them visible. It provides a simple interface to something that is similar to the
scrolling graphical displays that are commonly seen on electronic test equipment.

The two smaller multislider objects at the top of the patch display the data coming from our WTHITM abstraction (which we
used in earlier tutorials) turning our scaled mouse movements into numbers ranging from 0.0 to 1.0. This value goes into
the multislider (to be displayed), then is output from the multislider into a bit of patching that produces four values from
that data (the X position, the Y position, and a pair of polar coordinates for the distance and angle of the mouse from the
center of the screen). This is sent into the lower multislider, which is both graphically jarring (red on green!) and peculiar in
its display: it displays four data streams simultaneously.

Attempting to do something like this in an lcd object would be very difficult, but to accomplish a multiline display in a
multislider is a simple matter of saying that there are four sliders, setting the display range (in this case, from -1.0 to 1.0),
and letting the object work its magic. In this case, the X and Y coordinates of the mouse are used to create four different data
streams, each displayed in its own section of the graphic.
Watching data streams with Watchpoints
While the multislider is useful for displaying numeric data streams, Max has a number of built-in systems for monitoring
data as well. If you already have a screen full of objects and patch cords, you probably wouldnt want to use the onscreen real
estate for a large graphic display like a multislider. And if the data is being generated too quickly, or from too many
locations, you may not want to print things to the Max window either. What is a better option? Watchpoints!
A Watchpoint is an attachment that you make to a patch cord that allows you to view the messages it carries without
having to change your patch. If you click on a patch cord and bring up the patchcord menu, there are two Watchpoint
options: Add Watchpoint Monitor and Add Watchpoint Break. The first option sets a watchpoint that allows you to
monitor the message values, while the second will force the patch to stop running when ever a message is seen on the
selected patch cord - we used this in a previous tutorial to look at message order. Lets watch some values run through the
patch cords.

You can manage and view the watchpoints by selecting Watchpoints from the Debug menu. This brings up a window with
one row for each watchpoint (identified by the colored and numbered circles on the patch cords). If you start the metro
object in one of the patch sections using the toggle objects, you will begin generating messages and you will see the results
in the Watchpoints window. Both the window and the columns are resizable, so if you need to see more data than is visible,
you can make the window larger or the columns wider. You will probably need to increase the size of the Value column to see
all of the values for watchpoint 3 you can widen it by selecting the header separator between the Value and Count columns
and moving it to the right.

The columns in the Watchpoints window are mostly self-explanatory:


- The first column shows the watchpoint identifier.
- The second column displays the type of action assigned to the watchpoint.
- The third column displays the class of the object sending the message.
- The fourth column shows the name of the subpatcher containing the watchpoint (or is blank if it is on the main patch).
- The fifth column displays the value or values associated with the last received message.
- The sixth column displays the counter of messages received by this watchpoint.
- The seventh (and final) column shows a history of the last three values seen at this watchpoint.

If you start patcher section 1 and move your mouse around with the Watchpoints window visible, you will see the first three
watchpoints tracking your mouse movement. The format of the window (and the location of the watchpoints) helps you
quickly see that the X and Y coordinates, viewed with watchpoints 1 and 2, are properly scaled floating-point numbers from
0.0 to 1.0. You can also see the effect of the cartopol object and divide by pi (/ 3.1415) math objects on the X/Y
coordinates by viewing the third and fourth value in watchpoint 3 (driven by the pack object). Watchpoints can provide a
quick and easy way to verify that the results of your calculations match the ranges that you expect.

As we saw in an earlier tutorial, changing a watchpoint to either break or break/watch will have a special effect when
Debugging is enabled: any message seen by the watchpoint will cause the program to pause, and allow you to step through
the patch in debug mode. Once the patch is paused, the Debug Window is displayed and you can step through the patch
one message at a time, watching the patch operating while the Debug Window displays your patcher's stack trace.

Conclusion
While only revealing one new object (multislider), this tutorial introduced a number of important techniques for both
creating and tracking values in a data stream. We saw how multislider has built-in data display options that can greatly
simplify the tracking of live numeric data. For debugging purposes, we also saw how watchpoints can be used to track any
message on any patch cord without changing our programming.

See Also
Name Description
multislider Display data as sliders or a scrolling display
Mapping and scaling numerical information
Data Tutorial 2: Data Scaling
Introduction
This tutorial is focused on data scaling and smoothing issues. It introduces the iter object for list iterations, and the trough,
peak and slide objects for data scaling and smoothing. We will also look at additional data display options for the
multislider object in particular, the ability to set a minimum and maximum range, and using the peak-hold monitoring in
that object.

Different Max objects and physical devices produce values of different ranges and formats. One of the tasks that you will
often perform is altering the incoming format and scale of a data-set to match the format and scale needed for your output.
While earlier tutorials described using the scale object for this function, we might need to employ other objects to find out
the numerical range for our scaling first. The objects introduced in this tutorial offer new options for scaling, smoothing and
viewing data to suit your programming needs.

Examination of new objects


Take a look at our tutorial patcher: on the left side of the patcher is an overview of a few new objects (outlined in green). The
top-most patch shows the iter object in use it accepts a list, and outputs the individual values in order. When we click on
the message box, the four-value list is sent to iter, which outputs four messages each one containing one list item. This is
the simplest way to turn a list into a data stream, and (as we will soon see) is useful for atomizing the contents of a list in
order to trigger a new event from each list element.

The next subpatch has examples of both the trough and peak objects. They serve complementary purposes: both object
examine an incoming number stream, with trough capturing (and outputting) the lowest value received thus far, while peak
captures and sends the highest value. When we change the value in the number box, we see that the objects capture the low
and high values, with new output occurring whenever a new high or low is reached.

Finally, the bottom subpatch shows three uses of the slide object. The slide object is used for smoothing out data based on a
smoothing factor, with separate factors for upward and downward movements. The function of the smoothing factor is
rather simple it is used to divide the difference between the last received message and the current one, thereby reducing
the amount of swing in any value transition. The smoothing factors are provided as two arguments to the object: the first
argument is the factor for upward movement, and the second argument is the factor for downward movement.

For example, when you first start the patch, the last value is 0.0. If you make an immediate transition to 0.5 (which you
can do by entering a value into the number box connected to the slide objects), you will see that the first slider moves to
0.01. This is because there was an upward transition in value, so the first factor (50.) was used: the difference between the
initial value of 0.00 and 0.50 is 0.50; this difference is divided by the factor (50.) to yield 0.01.

The three slide objects show different smoothing factors: the first provides even factors for both upward and downward
movement, the second has no upward smoothing (a factor of 1.0), and the third has a small downward factor (a factor of
10.0). As you move the input slider - actually a multislider with only one slider set to have a floating-point range, you will
see that each output multislider responds differently smoothing the output in relation to the upward and downward
smoothing factors of each slide object.

The main patch overview


The main patch uses weather data as source material; it drives the display in our multislider, and is also used to create four-
note chords for playback on the computers internal MIDI synthesizer. Double-click the two coll objects in the patch to
become familiar with their contents - both contain twelve lines of data, where the output of one serves as the index of
another. When you start the metro (at the top of the patch) with the toggle object, the bang messages are used to generate
calendar information specifically, the output of a counter (which is counting days) is used to query a small coll database
that outputs the months based on what days in the calendar year they start - e.g. day 90 of the year is the first day of month
4 (April). This month value (in the range 1 to 12) is then used to query the coll loaded from the file weather.txt, which
contains the average monthly temperatures in four cities (New York, Paris, Buenos Aires, and Tokyo). This data is unpacked
(since it comes out of the coll in the form of a list) and is sent to four float objects. The metro then bangs the float objects
to create a stream of output. This is a good technique for use in systems where you require something to happen on a regular
clock but the incoming data is not produced at a constant speed - in our example, the list of temperatures only come out of
the coll object when the month changes.
The output of the float objects are sent to slide objects with a smoothing factor of 15.0 for both upward and downward
movement. This means that, while the same value may be sent as many as 31 times (since there are up to 31 days in a
month), the value will still change as the smoothed output catches up to the actual value. The output of the four slide object
are packed together and sent into the multislider, where they are displayed. This newly created dataset is also output from
the multislider, where it is split apart (by the iter object) and used to make four notes for synthesizer playback.
This multislider uses a few new techniques for data display. Open the object inspector for the multislider, and you will see
that the Slider Style attribute is set to Bar, which gives us the filled bar. The Candycane option is also activated, so that the
bars are colored based on the colors in the inspector. Finally, there is a Peak Hold option set, which causes a small bar to be
located at the top of the highest point that the value reaches. This gives us a visual indicator of the peak value seen for each
of the four cities.

There is a toggle connected to a message box that can turn off or turn on the peak hold function; this is a good example of
using inspector-type messages to control the function of an object. Since any change to the peakhold attribute should reset
the peak tracking, a companion message (peakreset) resets that value any time the toggle is changed.

The min/max section


The other part of this patch worth examining is the setup performed just to the left of the main patch. This patch section has
a singular purpose: to set up the multislider for proper display scaling. A bang message (either sent by clicking the button,
or generated by a loadbang) starts by setting the trough and peak objects with very high and very low thresholds,
respectively - this guarantees that any new value sent to them will automatically set a new standard within the object. The
bang then triggers a dump message to the coll object, which causes all of the entries to be sent from the object, one list at a
time.

As the lists are output, they are processed by an iter object, that splits the lists into single-value messages. These are
examined by the trough and peak objects, which find the lowest and highest values in the data set (32 and 81,
respectively). When a value is found, it uses the pak object to generate a value list, prepends the message setminmax to the
list, and sends it to the multislider. This changes the display range that will be shown, causing the multislider to limit its
display to the actual range of high and low temperature that will be output by the coll. In this way, the multislider display is
automatically calibrated to the temperatures stored in the weather.txt file.

Conclusion
In this tutorial weve seen how to analyze data streams (using iter, trough and peak) and smooth their output (using slide).
Weve also seen some programming patterns that can be useful for automatically setting up UI elements, and for outputting
data when new data is sent less frequently than it is needed. Finally, we further explored the flexible multislider object,
using it for a bar display with peak hold values and full-color display.

See Also
Name Description
iter Break a list into individual messages
peak Output larger numbers
trough Output a number if it is less than previous numbers
slide Smooth values logarithmically
Recording and playing back captured input
Data Tutorial 3: Gesture Capture
Introduction
This tutorial focuses on data capture and playback in essence, we will be performing sequencing. However, unlike the
sequencing found in the MIDI Tutorials, this is sequencing of arbitrary data (mouse movement, in this case). We will be
expanding on our use of coll, this time collecting as well as reproducing data for an interesting drawing patch.
The heart of many performance tools is the ability to capture and play back movement, whether motion capture data, sensor
data or mouse movement. This tutorial will present the basis for capture and playback systems, and will introduce a few
interesting design patterns as well.

Run the program, view the data


Take a look at the tutorial patcher. This is a fairly complex patch, and the whole thing serves one purpose: capturing mouse
movement and turning it into an interesting drawing. The interesting thing is that while receiving mouse movements and
drawing the picture, the patch is also recording the movements. Because this patch depends on regular timing regardless of
other computer activity, you may want to turn on Overdrive under the Options menu.

An important hint: you dont want to interact with this patch using the mouse, since it will tend to mess up your drawing.
Rather, notice the key object-based section just above the lcd object: this maps three keys (space, r and p) to three patch
functions (clear, record and playback). To begin, hit the r key (lower-case is important!) to begin the recording
process. Now, move you mouse around the screen looping and large movements are especially effective. When you are
done, hit the r key again to turn off recording.

Now you have an interesting, script-like drawing on the lcd display. Hit the space bar to clear the display, then hit the p
key to begin playback. You will see the drawing occur: not only was the drawing captured, but the actual mouse movement
(and timing) were captured and reproduced.

There are three coll objects in this patch, but all of them refer to the same data: the data in a coll named thegest. The copy
at the right is most convenient to access, so double-click on it to reveal the captured data. The contents of the coll shows our
movement being tracked and captured in 20 millisecond intervals. Lets look at how this capture happened.

The recording part


The RECORD section of the patch, at the top-left, is all started with the big red toggle object. When it is turned on, it
resets the patch (via the sel 1object connected to the right outlet of the trigger), then starts a metro that fires every 20
milliseconds. This determines the sampling rate of the mouse tracking, and also serves as a trigger for the other objects.
The metro sends a bang message to two objects: a subpatcher (the scaled version of WTHITM that we've been using) and
an int (abbreviated "i") object.
The WTHITM abstraction should be familiar by now it tracks the current mouse position, and outputs a value set (X and
Y coordinates) scaled to the range given as arguments. In this case, it means that the output of the subpatcher will be in the
range of 0-320 and 0-240, and the subpatcher will output a value any time it receives a bang message. In order to provide
immediate feedback, the output of the subpatcher is sent to a drawing subpatcher that generates drawing commands for the
lcd object.

The int object, and the + object connected to it, performs a useful function. Incoming bang messages will output the current
value (as seen by the number box). However, the output value will also go to the + object, which will add one to the value
and store it in the right inlet of the int, waiting for the next bang message. The result is that every bang message will output
a value, but also increment it by 1 sort of like a counter object, but with no upper limit. This is a useful way to get an ever-
increasing number for situations where you dont know what the limits might be.

The values from these two objects (the current count and the scaled X and Y positions) are assembled with a pack object and
then sent to the coll object - the first value in the list (the current count) acts as an index, telling coll to store the remaining
values at that position. As a result, the coll acts as a data recorder, taking the indexed values and storing them for later use.
The collection of data continues until the record function is turned off, either by clicking on the red checkbox, or by hitting
the r key.

Take a moment to look at what the select object connected to the recording trigger does. When the recording is begun, a
bang gets sent to a second trigger object that, from right to left, turns off the "play" toggle box (stopping any playback),
sends a clear message to the lcd, erases the contents of the coll (with another clear message), and zeroes the int object to
reset the index counter.

The playback part


The playback part of the patch, at the lower-left, mirrors much of the recording section, except it doesnt to any mouse
tracking. Rather, it just requests indexed values from the coll named thegest, and uses the same drawing patch to recreate
the mouse drawing movements. It is able to use the same incrementing integer technique used in the record section; this has
the benefit of not requiring an upper limit to be defined, but a downside of never stopping or looping on its own.

Since the record function didnt timestamp the captured data (it just indexed it with the output of the integer object), it
means that we can manipulate the playback of the drawing by altering the speed at which we request the colls content. The
easiest way to do this is to change the speed of the playback metro.
Unlock the patch and add an integer number box in the area of the playback section. Connect its output to the right inlet of
the metro (which controls the output interval). Enter 2 into the number box, then hit p for playback. The drawing will
occur as before, but will run 10 times as fast. Stop the drawing (hit "p") and change the number box to 40, hit the p key
again, and the drawing will run at half speed. As you can see, this data capture technique gives you a lot of flexibility at
playback time.

Once you have an interesting data capture, you will probably want to save it for later use. The coll at the far-right (outlined
in blue) shows the simple method for saving and retrieving coll contents; a read message will allow you to import data from
disk files, while a write message will take your captured data and store it to disk. You can append an actual file name and
path to the message if you have a specific file to read or write, while a read/write message with no arguments will open a file
dialog for file selection.

Make a few drawings and save them using the write message to the coll on the right. If you read them back in (using the
read message), you will be able to play back your saved drawings. Notice that the data files created by coll objects are simply
text files; you can open then in any text editor or import them into another program for viewing or manipulation.

Conclusion
In this tutorial, weve seen how to use the coll object as a data collection device; we've also learned how to design a counter
with no upper limit. Weve also seen how the coll can be used for disk storage and retrieval, allowing us to save and reuse our
captured data. Finally, this patch is a good example of a single data set being used by three coll objects, a method for data
sharing that becomes very useful with large patches.

See Also
Name Description
coll Store and edit a collection of data
Working with a visual spreadsheet interface
Data Tutorial 4: Cellblock
Introduction
This tutorial focuses on the jit.cellblock object (commonly referred to as cellblock). The jit.cellblock object provides a
visual interface to a 2-dimensional matrix of data, where each data point (or cell) can contain any of the data types used in
Max. This data can be changed and edited, and selected either by the user or by the patch.

The jit.cellblock object fills a special need in Max an space-efficient display of Max values, with the ability to select or edit
them visually within the patch. This object, like the lcd object, supports a very large number of messages and attribute
settings; in this tutorial, we will cover some of the most useful ones, but there are many more options available for advanced
use.

Structural messages and setup


Take a look at the patcher for this tutorial. You will see a grid-based display, along with three sets of message boxes. The
grid in the middle of the patcher (which resembles a spreadsheet) is the jit.cellblock object; it provides a two-dimensional
display of data stored in an internal structure.

Many of the structural settings of the jit.cellblock are available for programmatic control. For example, there are two
number boxes connected to rows and cols messages. These number boxes can be used to manually change the number of
rows and columns stored in the jit.cellblock. If you add more rows or columns than can be displayed in the available area,
scrollbars will automatically appear.

Another type of structure can be implied by changing the color of the first column or row with the object. When this is done,
it make it clear that this row is an index or identifier for the remainder of the row. Using the rowhead and colhead
messages, you can change the perceived use of this first value. Its important to note that, while there is a visual change to
the header area, there is no change in your use of the data, or your ability to add or change it.

There are other visual attributes that can be changed that have no effect on the underlying data. An example is the grid
attribute. When the grid is on, we get a familiar spreadsheet-like display of the data. When it is off, however, the display of
the values is not delineated by the drawn grid; this is especially handy if you want a less distinct grid layout that uses either
text or background colors to distinguish data subsets.

There are more structural settings available for manipulation, and opening the object inspector gives access to most of them.
If we open the object inspector for the jit.cellblock object in the tutorial patch and select the Structure section, we see
attribute settings that match the patch-based messages we just used. Additionally, there are settings for the default column
and row sizes: the width and height of these elements if they are not specifically set. If you adjust these settings, you will see
the cells in the jit.cellblock dynamically change to match.
Other visual settings are available under the appearance section of the inspector. The colors of the various jit.cellblock
elements can be set using the color picker; click on the color that you want to alter, and a standard color selector will be
displayed. Select the Default Background Color, and change the color to a bright red. You will notice that the background
of all of the cells will be changed, but the other elements (like the color of the grid, or the currently selected cell) remain
unchanged.

Familiarize yourself with the different settings on the left side of the patcher (labeled 1), as well as some of the values in the
Inspector for the jit.cellblock object.

Storing and retrieving values


Beyond setting up the structure of the jit.cellblock object, we will need to select cells, store data in them, and retrieve the
data again. First, lets look at choosing a cell. The easiest way to select a cell is to click on it much like you would with a
spreadsheet. You will notice that selecting a new cell outputs the coordinates (in column/row order) from the left outlet of
the object (this is printed into the Max window for us). Since you may want the program to control the current selection, the
jit.cellblock object will also respond to a select message, with arguments that choose the column and row to select. Using
the two number boxes attached to the select message, you will be able to control the current selection of the jit.cellblock.
Notice that both the row and column number is zero-based, meaning that the first row and first column is selected by
sending the message select 0 0.

The current selection can be referred to as current in certain messages. So, the next number box is routed through a set
current message; this will take the incoming value and change the current cells value to this integer. Test this out by
selecting several different cells and changing the value. Now click on any cell with a value: you will see that the output of the
object has changed, with the Max window displaying not only the column and row numbers, but also the data that is in the
cell.

You dont have to select a cell to change the data it contains. The next message box uses the set x y value... syntax for
setting contents in the object. The two integers following the set message represent the column and row that will be
changed. All data following these coordinates will be stored. If the data is an integer or floating-point number, that single
entry will be stored. Symbols and lists can also be stored as values for a cell. Clicking on the third message box will force cell
2 2 to contain the text Here I am!. Of course, we also have to be able to remove data, which is the function of the clear
message. The next message box generates the clear 2 2 message, which will erase the text that we just set.
The jit.cellblock object is useful partly because it provides a large set of user options for selecting and manipulating data in
a cell. Of course, if weve gone through the trouble of setting the values of the cells, we wouldnt want the user (or the
program, for that matter) to change these values. Setting the readonly attribute to 1 will prevent the values from being
changed. When this is set, you can use the jit.cellblock without worrying about the values being changed.

Selection and output options


In order to be as flexible as possible, jit.cellblock has several selection and output modes. The selection mode (set with the
selmode attribute) defaults to selecting a single cell (known as one cell select mode). If we look at the left umenu of
section 3, we will see that there are six different options for cell selection.

The first option (option 0, no selection) prevents any cell selection. This can be useful if you want the jit.cellblock object to
act like a large set of labels. Option 1, single cell select, is the default selection handler, where only one cell can be selected
at a time. The next two options (2 and 3) all you to select a large number of cells with a single click. Option 2 (column
select) will select all cells in any column that you select. Option 3 (row select) does the same for row values.

The fifth option (option 4, header select) is more involved. If you have column or row headers turned on, and if you click
on a header cell, the entire column or row will be selected. Otherwise, only a single cell will be selected. This is very similar to
the way a spreadsheet works, where the headers have special selection rules that are different from standard cells.

The last option (option 5, in-place edit) provides an easy way to enter data into the jit.cellblock. Double-clicking on any
cell will allow you to edit or add information into the selected cell. This may be more convenient than using select and set
messages, although it cannot be controlled with your patch.

Since several of these modes will select multiple cells, it begs the question What format will the data be in? The
jit.cellblock object provides three output modes as an answer - these are set with the outmode attribute. Mode 0, or
individual output mode, will send each selected cell in its own message, and will output a message for cells that may not
have any data value. Mode 1, or output as one list, will combine all non-blank cell values into a single list, and output it in
a single message. Mode 2, or output as one symbol, will combine all of the non-blank cell values into a list, then turn the
list into a single text symbol. This is most useful if you have filled your jit.cellblock with textual values, and want to combine
them into larger phrases.

To see the output mode in action, click on the button attached to the loader subpatcher. This will format and load the
jit.cellblock object with numbers from 0 to 99. The jit.cellblock is also flipped into row select mode, so we will be
selecting many cells with each click. Click on a cell to select a row; you will notice that 10 messages appear in the Max
window sequentially, one for each cell that is selected. Now, change the output mode to output as one list, and click on the
sixth row. The Max window now shows a single line result, meaning that only one message was produced. The first two
numbers are the column (irrelevant, in this case) and row (5, since jit.cellblock is zero-based), then a list of all the values in
that row.

If we change the output mode to output as one symbol, the results in the Max window seem no different. However, if you
look at the output of the zl len object (covered in depth in another tutorial) connected to the jit.cellblock object's outlet, you
will see that our message only has 3 elements, rather than the 12 elements we saw in the previous mode.

Conclusion
The jit.cellblock object is a robust tool for dealing with 2D data of any type, and for the presentation of data in a grid-like
format. We have only touched on a few of the most useful commands; for more information, review the help files and
reference documentation on this object.

See Also
Name Description
jit.cellblock Two-dimensional storage and viewing
Manipulation of lists of data
Data Tutorial 5: List Processing
Introduction
This tutorial is a large one, because it covers a big topic: list processing. We cover several of the available modes of the zl
object, which provides a central clearinghouse of list processing functions. We also see how we can perform mathematical
expressions against lists with the vexpr object, and how to use the prob object to create a table of probabilities for music
creation.

Within Max, the list is one of the most powerful data structures available. You can define any combination of values in a list,
then have them sent as messages, get processed by objects or get treated as small tables. Much of this is made possible by
the zl object, which give you the ability to query, reorder and access any of the elements in a list. Adding vexpr into the list
processing mix allows you to process list elements mathematically without having to break them into their individual
components.

The use of the prob object is integral to many generative programs. The prob object allows you to easily create a weighted
probability table, with only a bang required to generate the expected data. In our tutorial, we will see how the prob object is
used to seed a basic sequencing application.

Running the sequencing patch


Take a look at our tutorial. This is the quintessential Max patch the step sequencer. When you open the patch, the first two
multislider objects (labeled A and B) are seeded with values, while the third (labeled C) is empty. These objects contain
sequences for a MIDI playback system fed by the two noteout objects to the right of them. Double-click the noteout objects
to select an available synthesizer. Turn on the metro at the top-left by clicking the toggle, and the sequence will begin
playing, as driven by the A and B multislider contents. Click on the C multislider and drag your mouse to set values for the
melody line the result will play back using from your computers synthesizer.

If you are using a General MIDI-compatible synthesizer, you should hear the top two multislider sequences as drums, and
the bottom (C) sequence as a melody played on a piano. This is because, according to General MIDI rules, MIDI channel 10
(the argument to the upper noteout is the drum channel, while the other fifteen channels play melody instruments. Most
synthesizers enable you to configure this behavior, but the built-in synthesizers on both Macintosh and Windows machines
behave in this way.

At the right of the patch are a number of editing routines using the zl object, which we'll look at in depth in a minute. You
can rotate the sequence stored in multislider A, reverse the contents of multislider B, and perform several different
functions against the melody contained in multislider C. Click on the button objects that activate the editing routines, and
see that the changes are immediately applied against the multislider contents.
The basic function of the step sequencer should be familiar: the metro drives a 32 position counter, whose output is turned
into a fetch message for the three multislider objects. The output of the multisliders are sent to two different
makenote/noteout combinations; the two drum multisliders are sent to a noteout object assigned to MIDI channel 10
(the drum channel), while the melody is sent to a noteout object assigned to MIDI channel 1 (a general instrument channel,
which defaults to a piano sound).

The two drum channels provide a simplified way of selecting drums the top two multislider objects are limited to only
three values each. The select objects used with these objects are a way of remapping the multislider contents (0, 1 or 2) to
an instrument (none, kick/closed hi-hat and snare/open hi-hat, respectively). In this way, the full range of the multislider
has significance, and the output value is easy to work with.

Set the entire sequence in the A and B multislider objects to 0 (drag the mouse across them towards the bottom. The drums
in the sequence will stop. Try adding different patterns to get a sense of how the numbers in the object map to the different
sounds you get.

Working with prob (probabilities)


The initial setup of the drum sequences is done using the generate new patterns section of the patch, found below the
multislider objects. If you want to see it in action, click on the button connected to the hi-hats uzi object. You will see that
the A multislider will get scrambled, but that the contents tend to emphasize the 1 value (which corresponds to the closed
hi-hat). This occurs because of the probability table set up and enforced by the prob object.
The setup of the probability table is done through the large message triggered when the patcher opened by the loadbang.
The way that our probability table works is based on transition: a weighting value is used to determine how likely a
transition is from the current value to another value. So, for example, 0 1 2 means that the probability applied to a
transition from 0 to 1 is 2. What does 2 mean? It doesnt really mean anything specific it only has a defined value in
relation to all of the other probabilities for that transition. As a result, we consider it the weight of that transition.

The message box used for the hi-hat probability tables sets up all of the possible transitions within a single three value
(0-2) set. Since you can only be at one current location at a time, the probabilities are dependent on the current value state.
Lets look at probability calculations is the current step is 0:
Next Step: 0; Weighting: 3; Probability: 3/8 (37.5%)
Next Step: 1; Weighting: 3; Probability: 3/8 (37.5%)
Next Step: 2; Weighting: 2; Probability: 2/8 (25.0%)

In order to understand the calculation of the weighting value, you need to add up all of the weights for the current step, then
use that to divide the individual values for a weighting factor. In this example, the total weighting values for all cases where
the current step is 0 add up to 8. This gives us the denominator for the calculations we made. Therefore, a quarter of the
time, we will go from no hi-hat sound to an open hi-hat; 75% of the time, we will split going to a closed hi-hat or no sound at
all.

If you look at the cases when the current step is 2 (an open hi-hat), you will see that the transition to 0 and 1 both are
weighted at 4, while the transition to 2 (a repeat of the open hat) is given a weight of 0. This means that the prob objects
table will prevent an open hi-hat from ever being repeated, since there is a 0% chance that a current value of 2 will be
allowed to repeat as a 2.

The prob object is driven by an uzi object, set to output 32 bang messages (and therefore 32 values). However, these are
presented as individual values, and the multislider is expecting a 32-value list for setup. How do we combine all these
messages efficiently?

Working with zl
A key object when working with lists is the zl object: it is a single object that works in almost 20 different modes (set by the
object's first argument), all of which perform useful list processing functions. In the case of the sequence generators for the
drums, the zl object is used in group mode, with an argument of 32. This means that the object will collect 32 values, group
them into a single list, and then output the list from its left outlet. This is a quick and very efficient way to pack a stream of
data into a list of predefined, and turns an otherwise onerous task into a job for a single object.

The tutorial patch shows many uses of the zl object particularly in the editing functions. All of these editing routines start
with the zl object in reg mode. In this mode, the zl object will accept a list into its right inlet, and store it until it receives a
bang in the left inlet. The zl reg object is, in essence, the equivalent of the int, float or value objects, but is designed for list
storage.

When you click on the button for each editing routine, it outputs the list from the zl reg into another list processing object.
Several of the editing routines use zl (in another mode) for the list manipulation; for example, the rotate A routine uses zl
in rot mode (with an argument of 1) to rotate the values by one entry everything moves one position to the right, and the
last entry becomes the first. The reverse B routine uses zl rev to reverse the order of an incoming list, while the sort parts
of C combines three zl processing objects to split (iter), sort and reassemble (group) a list. Most zl modes take a second
argument or allow a number in the right inlet to change a parameter - for example, the zl iter object breaks a list into sub-
lists of a size set by the argument (in our case, 4) that can also be changed by sending a number into the right inlet. If we
change the number box connected to the zl iter object to 32 (the entire length of the sequence) and then click the button,
the melody stored in multislider C will become sorted from low values to high values.
Perhaps the best way to see all of the zl operating modes is to look at the zl help file. Unlock the patcher, select a zl object
and choose Open zl help from the contextual menu or from the application help menu. The help file is broken into three
segments, since there are so many modes but you will be able to see all of the ways that zl can be used to bend, fold and
mutilate Max lists.

Working with vexpr


When working with lists, there are times when you want to perform mathematical expressions against all of the elements in a
list. Using standard Max math objects (+, etc.) would require splitting, processing and reassembling a list not the most
efficient way of dealing with the problem. There is a solution: the vexpr object.
As you can tell by the name, the vexpr object is very similar to the expr object we learned about earlier, with the exception
that it is made specifically to process lists. If we look at the use of vexpr in the transpose C routine, we see that the
familiar $i1 syntax is used to reference the individual integer values of the list, and that we will add (or subtract) the
number 1 from each entry. Therefore, when the zl reg object outputs a 32-value list (sent originally from multislider C),
each of the entries will be incremented or decremented, and will be output as a 32-value list.

The randomize C routine shows the use of vexpr with two lists used for input. The right-hand side of the routine will
generate a 32-value list of random numbers varying from -1 to 1 (the result of the uzi, random 3 object and the 1 objects
sent into a zl group). This is input into the right inlet of vexpr. The left inlet receives the 32-value list from multislider C
being held by a zl reg. The vexpr object iterates through the two lists, adding the elements from the right inlet (identified as
$i2) to the elements from the left inlet (identified as $i1). This means that each of the list elements will be altered by a
different random element, giving a small randomization to the multislider contents. NOte that this randomization can be
done multiple times to gradually morph the melody into a new pattern altogether.

Conclusion
We started this tutorial by learning about probability tables, and their use in seeding a multislider object's content. From
there we covered several ways that a multislider object's content (provided as a list) could be processed using the zl and
vexpr objects. Since lists are an integral data structure in the Max environment, these objects will become an often-used
part of your programming toolkit.

See Also
Name Description
prob Create a weighted transition table
zl Process lists in many ways
vexpr Evaluate a math expression for a list
Working with inlined patchers
Interface Tutorial 1: bpatchers
Introduction
This tutorial looks at a useful object for embedding subpatchers within a patcher so that their interface is visible. The
bpatcher object is superficially similar to making any abstraction: we create a patcher file (with inlets and outlets, as
necessary) and save it to disk. Rather than instantiating it with an object box, however, we use the bpatcher object to
'embed' it visibly inside another patcher. This allows us to construct a library of interface elements - pieces of patcher logic
that show an interface that we can re-use multiple times.

Overview of the tutorial patcher


Take a look at the tutorial patcher. The reasonably sparse window contains a toggle labeled "Start", three button objects
("draw", "see", and "clear"), and three identical-looking interface areas.

Click on the toggle labeled "Start". Move the mouse over to the left-hand interface area and draw in the blue rectangle that
contains the small yellow ball. This is a jsui object loaded with a two-dimensional user-interface that simulates a two-axis
slider of sorts that will track our mouse when clicked. As you "draw" by dragged in the jsui, the gesture of your drawing will
be traced in red in the lcd object below. The lcd object has its border turned off, so you won't see anything until you draw
something in the jsui. If you clear the lcd (with the "erase" button) you should see your gesture draw again.
Go to the second and third jsui objects and "draw" in them with the mouse. Notice that they generate tracings in the lcd
object in green and blue, respectively. Hit the "erase" button to clear the lcd and see them redraw.
Turn up the slider objects next to the jsui objects and you will see that the tracings become slightly "noisy" - the "gestures"
recorded from the jsui are now being randomized a bit to add more texture to the drawing. Click any of the button objects
labeled "clear" to erase the captured gesture. You can then redraw a new gesture in the appropriate jsui.
With some gestures "loaded", click on the button labeled "see" at the top of the patcher. Notice that the three interface areas
suddenly look different - a new set of jsui objects appear that "trace" the gestures as you entered them. Where did the
original jsui, slider, and "clear" button for each interface go?

The bpatcher object


Unlock the tutorial patcher. Notice that a number of "hidden" objects appear; moreover, light blue boxes appear around the
three interface areas. The blue boxed areas are in fact bpatcher objects containing an abstraction patcher saved on disk.
These patcher files have parts of their interface shown inside the main tutorial patch.

Click on any of the three interface areas and notice that, rather than being able to edit the objects within, you can merely
move and resize the blue box area. This is because, as we mentioned, the patcher logic inside that area is saved in a separate
file. Control-click (Mac) or right-click (Windows) on one of the blue boxes to get its contextual menu. From the menu, go
down to the Object submenu and select "Open Original doodlepatch.maxpat". The master copy of the three interface areas
will open. Let's take a look at that patcher.

Unlock the "doodlepatch.maxpat" abstraction. Notice that all we see is the interface elements of the patcher, regardless of
whether the patcher is unlocked. This is because the patcher is in Presentation Mode - we can set any patcher to open in
Presentation Mode by checking "Open In Presentation" in the Patcher Inspector. From the View menu, uncheck
Presentation and the patcher will morph back to its original view and a bunch of patcher logic will appear.

Take a look at the code in the patcher. It uses a coll object as well as some supporting logic to take the drawing data from
the jsui object and record it (this is a form of "gesture capture", as seen in a previous tutorial). The second jsui (to the right)
immediately reanimates the data from the coll based on bang messages coming in from the inlet and driving a counter
object.

Offsetting a bpatcher
Without closing the "doodlepatch.maxpat" file, switch back to the tutorial patcher and look at the "draw" and "see" button
objects when the patcher is unlocked. Notice that they trigger message boxes containing the messages offset -60 0 and
offset -360 0, respectively, sent into the second inlet of the bpatcher objects.
Look in the bpatcher patch and see what the second inlet is connected to. Notice that it talks to a thispatcher object. The
thispatcher object provides functionality for controlling the appearance of a patcher file, including its size, position on the
screen, and whether the title bar is visible or not. When used within a bpatcher file, the thispatcher object can "scroll" the
interface of the bpatcher object based on coordinates provided with the offset message. This allows our master tutorial
patcher to "switch" between two different viewpoints on the same bpatcher file - in this case, the "draw" view and the "see
view".

Arguments for bpatcher objects


Look a the patcher logic attached to the outlet of the bpatcher file. There is an append object with three pound-sign
abstraction arguments (#1 #2 #3). These arguments would normally be provided in the object box if we were to load
"doodlepatch.maxpat" as a normal abstraction in our patcher. In order to set these arguments within a bpatcher object, we
have to use the object's Inspector.

Close the bpatcher abstraction file and go back to the tutorial patcher. Click on one of the bpatcher objects and open its
Inspector. Notice that at the bottom we can find the name of the Patcher File loaded by the object. Directly under this is
the Argument(s) field, which contains three numbers. These numbers are substituted for the patcher arguments for each
bpatcher independently, allowing us to differentiate multiple copies of them in our patch.

The arguments for our bpatcher in this tutorial control the three colors drawn by the gesture capture system in the lcd (in
short, they provide the last three numbers for the frameoval commands sent to the lcd). Open the Inspector for each
bpatcher and change those values to a different color value in RGB form (0-255). When you record new gestures, you will
see them appear in the lcd using the colors you selected.

Conclusion
The bpatcher object provides an extremely useful way to embed visual interfaces within a larger project. An interface can be
designed (with whatever supporting logic is required), saved, and displayed in another patch. The offset message to a
thispatcher object within a bpatcher allows us to "scroll" the viewing rectangle of the object to reveal different portions of
the interface. This, combined with the use of Presentation Mode, allows us to customize the interface further. Just as with
other types of abstractions, patchers made for use with the bpatcher object can process arguments, set through the object's
Inspector.

See Also
Name Description
bpatcher Embed a subpatch with a visible UI
thispatcher Send messages to a patcher
Designing user interfaces with custom image elements
Interface Tutorial 2: Picture UI Elements
Introduction
This tutorial covers the creation of custom controls using your own pictures. This function is provided by the pictctrl and
pictslider objects, which use specially formatted pictures to give you customizable user interfaces.

Changing the colors and sizes of user interface elements can only get you so far when creating custom interfaces. The pictctrl
and pictslider objects take it to the next level: virtually any graphic can be used to create switches, sliders and state
indicators. However, in order to get the best possible result, you will have to format the images to make them conform to the
objects requirements.

Overview of the tutorial patcher


If you take a look at the tutorial patcher, you will see four rather silly pictures. In order to see the patch at work, click on the
cellphone it starts the metro, which animates all of the other graphics. The cellphone is obviously acting like a momentary
switch, the ring is a slider (following the output of a drunk object), the thumb is a yea/nay indicator (another type of
switch), and the eyes are a multi-state indicator (jumping to the value of the random object's output). Click on the cellphone
again, and the whole operation will cease. Lets look at each of these controls to see what is causing it to work.

The cellphone image, our momentary button, is made of two images the plain cellphone and one with the backlight turned
on. If you watch the toggle object connected to its output, you see that the output is 1 when you click the control, and 0
when you release the mouse. Using the select object at the output allows us to trigger the toggle controlling the metro.
While the metro is off, lets look at some of the other controls. They are all being driven by random-like object, but they can
be manually changed as well. Click and drag on the ring, and you will see that it acts like a horizontal slider the output
connected to the number box provides a current value output when manually changed. In this case, there are 128 steps
tracked by the object.

The thumb image can also be controlled manually: When you click on it, it becomes neutral. When you release the mouse
button, it reverses state. The eyes are similar, but change when you drag and click on the image. There are only a few frames,
so it might be convenient to use the number box above it to change the value in a more controllable way.

Swapping images and settings


Lets play with some of the setting of the cellphone switch. Unlock the patch, select the cellphone and open the object
Inspector. You will see a large number of attributes available for this object; lets start by playing with the object sizing. As
provided in the patch, there is no way to change the object size: you can mouse around the bottom-right of the object, but
the grow box will never be displayed.

In the inspector, you will see that an attribute named Snap Size to Picture Size is turned on. This attribute defeats user-
based sizing; rather, it forces the object to be the size of the source image. If you turn off this attribute, the object can be
resized, and the image will scale to match the sizing of the image.

Sometimes you will want to try certain images for buttons, but you may have to try several images for it to be right. You can
change the image file by looking in the image section and clicking on the Choose button for the Image File attribute. As
an example, click on Choose, navigate to the Max folder on your disk, then go to the patches/picts folder and select the
boring button.pct image. This is more of a stock button image, and it replaces the cellphone button completely.

Click on the ring finger slider object, and look at the changes in the inspector. This is a different object (the pictslider
object), and it has a different set of attributes; most notably, two different images are used for the display. The background
image (in this case, the finger) can be used to set the size of the object, while the ring image can be scaled or replaced
separately. Click on the Choose button for the Knob Image File of the pictslider, move to the patches/picts folder, and
select the smiley2.pct file. It will immediately show both smiley faces; one of these is the clicked image, so you need to
click on the Has Clicked Image attribute to make it look right. Now, instead of moving a ring around the finger, you are
sliding a face. You may want to try changing the Bottom Margin attribute to center the face correctly for this image.

Resizing and reformatting


There are a variety of object attributes that require specific image formatting. For example, attributes such as Has Image
Mask and Has Clicked Image require that the source file be specially formatted to support those options. If you have an
image editor available, you might want to open the thumbtoggle.pct and eyedial.pct files to see how the complexity of a file
increases when certain options are selected. The eyes pictctrl, which supports dial mode, also provides an example of
attributes that are only able in dial mode.

To get more information about the image formats for the pictctrl and pictslider object, open the help file for each and select
the picture_format tab to see how an image has to be created for it to be a valid controller. If most of the special features
are not used, the image can often be fairly simple, but more robust controls require more complex images especially if a
mask is used to provide transparency.

Conclusion
Covering all of the custom UI options made available by pictctrl and pictslider is beyond the scope of this tutorial. However,
you should be able to see how the user interface of a patch can be completely altered by using custom image-based elements.
While proper creation of the images can be difficult, the effort allows for complete control of the visual control environment.

See Also
Name Description
pictctrl Picture-based control
pictslider Picture-based slider control
decide Choose randomly between 1 and 0
Using JavaScript in a patcher
JavaScript Tutorial 1: Basic JavaScript
Introduction
This tutorial introduces the use of JavaScript within a Max patcher. JavaScript is an object-oriented scripting language
originally developed to facilitate the use of embedded software in websites. The Max js object allows you to use JavaScript as
a language within the Max environment, writing program code for your own object without the need for external developer
tools (compilers, debuggers, etc.). In this tutorial, well show a simple example of how you would use the js object to create
an object in JavaScript to respond to simple numerical input from Max and return a number to the patcher.

The js object gives Max users the powerful ability to write an object using an embedded programming language directly
within Max. In a nutshell, it allows us to:
Design and program procedural operations that may be difficult or impossible to implement using Max objects by
themselves. These may include operations that require recursion or respond to messages with an unknown number of
arguments, to give two examples.
Create objects that respond to customizable messages and rely on their own internal data structures.
Schedule timed events in response to messages.
Manage global variables for use among multiple js objects or between js objects and the Max patcher.
Interface to Maxs powerful scripting architecture.
Access the file system of your computer to look for files by name and types.

In order to develop a Max object using a programming language other than Max itself (i.e. subpatchers) you have several
options. You can develop your own external object in C using the Max Software Development Kit. You can also develop
objects in Java using the mxj object. Both of these solutions require that the code you write be compiled into a format that
Max can execute (either directly by loading a shared library or by executing Java code through the Java Virtual Machine).
With the js object (and its graphical cousin, jsui), code is evaluated as a script directly by the computer as you run your
patch, allowing for more immediate feedback on how the mini-program written for your js object will behave. That isnt to
say that js doesnt check for mistakes first; it does, and well look at some of the ways in which the js object can help you
catch mistakes in your program.

The Max js object uses version 1.6 of the JavaScript language developed by Netscape. While we dont presume specific
knowledge of JavaScript in these tutorials, the better you understand the language, the easier it will be for you to develop
code. The definitive reference for the version of JavaScript we use in Max can be found at the following URL:

http://developer.mozilla.org/en/docs/JavaScript

It's worth noting that there are many variations on the JavaScript language, as well as a number of extensions to the
language specifically designed for its use with web browsers. The Max js object supports only the core JavaScript language
(as outlined at the URL above) as well as some extensions added to the language to support interfacing with Max.

JavaScript in Action
Take a look at the tutorial patcher. If you want to hear the MIDI playback from the patch, select a valid MIDI output device
by double-clicking on noteout object on the lower-left of the patcher.
Click on the toggle at the top of the patch to start the metro object. The float object sends a value into the js object at every
tick of the metro. Slowly increment the floating-point number box attached to the right inlet of the float object. The output
of the js object will change in response. The output number is displayed using the multislider object in the patch and
generates MIDI notes.

As you increase the value going into the js object above 3.0, the value generated by our js object will begin to oscillate
between a high and a low value. At higher values (e.g. above 3.5), the output of will become chaotic.

The js object in this patch simulates a simple chaotic function called the logistic population equation. The basic formula for
the function is:

f(x) = rx(1-x)

where r is the current input value, and x is the previous output value.

Double-click the js object in the tutorial patch. A text editor will appear, containing the source code for the js object in the
patcher. This code is saved as a file called popu.js located in the same folder as the tutorial patch.
The Max js object allows you to edit JavaScript code directly within Max through a basic text editor (the same text editor, in
fact, that you use when editing the contents of a coll or text object). The source code that the js object loads is determined
by the first argument to the object, which specifies a text file in the Max search path. If you dont give js an argument, you
can still write a JavaScript program from scratch in the editor, but youll have to save the file in order to use it.

The Global Code


When you open the js objects editor youll see some JavaScript code. The code begins with a comment block that tells us the
name of the file, what it does, and who wrote it. The js object ignores these lines because they are prefaced with a double
slash (//), commonly used in C++ (and other programming languages) to define a comment. C-style comments (/* to start,
and */ to end) are also allowed in JavaScript.

The programming after the initial comment block defines some global code for the js object. This is code that will let us
define variables and run any part of the program we need to execute before anything happens to the object within the Max
environment. In our example, we use the global code to tell Max how many inlets and outlets we need for our js object and to
define and initialize a variable (called x):

// inlets and outlets


inlets = 1;
outlets = 1;
// global variables
var x = 0.66;

The keywords inlets and outlets tell Max how many of each well need our js object to have. Unlike most other changes we
make to our JavaScript code, if you change the number of inlets and outlets, you will need to manually recreate the js object
in order for it to reflect those changes. You can do this by closing and reopening the Max patch containing the js object, or
by retyping the object box.

The var keyword tells JavaScript that the label following it is to be declared as a variable, which we then assign to any value
either in the declaration itself (as we do here, by saying that x equals 0.66) or later on in the code. Our new variable, x, is
global in scope; well investigate exactly what that means later on.

In order to make any changes in our JavaScript code permanent, we need to save the code in the text editor. When you save
changes (by selecting Save from the File menu with the text editor in the front), Max will tell you that it has updated the js
object, and will report any problems it may have had with your code.

Type the following line underneath the outlets = 1; statement in the code:

post(Hi There!!!);

Save the code in the text editor. The Max window should have printed the following:

js: Compiling Functions and Executing Global Code...


Hi There!!!

The first message tells us that the js object has reloaded our (changed) JavaScript code. The second line shows the output
from the post() statement we put in. The post() statement prints its arguments into the Max window, letting you do exactly
what the print object does from within js.
Add the following line right underneath where we initialize x to equal 0.66:

post(x);

When we save the code, our Max window now tells us:

js: Compiling Functions and Executing Global Code...


Hi There!!! 0.66

If you give post() a text string (enclosed in double-quotes) it will print it. Other letters are interpreted as variable names. In
this case, we asked js to tell us the value of the variable x, which we had initialized on the previous line to 0.66. Note that
post() does not put a carriage return at the end of the line; to do this, we can place a post() statement with no arguments.
Add this line somewhere in between the two post() statements weve added:

post();

Our Max window now tells us this when we save the code:

js: Compiling Functions and Executing Global Code...


Hi There!!!
0.66

Handling Mistakes
Remove the closing parenthesis ()) from any of the post() statements weve added so far. Save the JavaScript code. The Max
window should print an error:

js: Compiling Functions and Executing Global Code...


error: js: Javascript: SyntaxError: syntax error, line 15
source line: post(;

This tells us that weve made a type of mistake called a syntax error. This means that we wrote something illegal from the
point of view of JavaScript syntax; in this case, we broke the rule that says that parentheses must be balanced. Mismatched
parentheses, brackets, and braces are common causes of syntax errors. Helpfully, js attempts to isolate which line the error
occurred on (the line cited to you may be slightly different, depending on where you placed your post() statements).

Go to the offending line in your JavaScript code and close the parentheses correctly. When you save the code, all should be
well again.

Misspellings are another common cause of mistakes in JavaScript. Rewrite one of your post() statements so that the word
post is spelled wrong (feel free to be creative here). Save your script. Something like this will appear:

js: Compiling Functions and Executing Global Code...


Hi There!!!
error: js: Javascript: ReferenceError: pst is not defined, line 15

A reference error means that we told JavaScript to execute a command that it simply didnt understand. While post() is in
its vocabulary of legitimate commands, pst() is not.

Note that JavaScript stopped executing our global code at the point where the error occurred. In the case just cited, the
words Hi There!!! were printed in the Max window, but the value of x (0.66) was not. This gives us an important clue as to
where the error lies (i.e. somewhere between the two). Using post() statements liberally in the development phase of your js
code is just as important as using print objects and Wiretaps for debugging in Max. You can always take them out later.
Correct your spelling and save your code. Lets move on to the rest of the script.

Defining Functions
Max objects interface with one another through the use of methods, which are routines of code that are executed in response
to messages received at the inlets of the object. In JavaScript, these methods are defined as functions within our code, each
of which responds to a different type of incoming Max message. In our example js object, we have two functions defined.
These functions (msg_float() and bang()) contain the code that js executes when our object receives in its inlet a floating-
point number and a bang, respectively.

Take a look at the bang() function first. The code looks like this:

function bang()
{
post(the current population is);
post(x);
post();
}

This function tells js what to do if we send it a bang from our Max patch. It will print out the current value of x in the Max
window with an explanatory preface. The post() statement at the end of the function tells Max to put a carriage return in the
Max window so that the next message printed there will begin on a new line. Note that our function is enclosed in curly
braces. Removing one of these braces will result in a syntax error.

In the tutorial patch, click on the button object connected to the js object. Our bang() function should be working correctly.
Look at the msg_float() function. Here is the code:

function msg_float(r)
{
x = r*x*(1.-x);
outlet(0, x);
}

Our msg_float() function executes the most important part of our JavaScript code, which is to run a single iteration of our
cool formula. Note that, unlike our bang() function, our msg_float() function has an argument (stated within the
parentheses as r). This argument tells the js object to assign the floating-point value coming into our objects inlet to the
variable r. We can then use this value in the rest of the function.

Generally speaking, the name of the function in JavaScript will correspond directly to the name of the message that you
want to call it. For example, we respond to a bang message with the bang() function in our js object. A function called
beep() would respond to a Max message that began with the word beep. Since float and int are reserved words in
JavaScript, however, we use msg_float() and msg_int(), respectively, to define the functions which respond to floats and
ints.

The main body of our msg_float() function sets x to the result of the multiplication of r (the value coming in the inlet), the
old value of x, and the old value of x subtracted from 1.0. This statement:

x = r*x*(1.-x);

is an example of a powerful feature of using an embedded programming language within Max. To accomplish this with the
expr object, for example, we would have to take the output of the object and feed it back around to an inlet in such a way as
to prevent a feedback loop in Max, probably through the use of a number box.
Double-click the patcher called done_with_expr to see how you would do this using normal Max objects. Note that because
the expr object has no knowledge of its previous output value, we have to store it manually and enter it again using a second
inlet to the object.

The second line of code in our msg_float() function takes our new value of x and sends it out the js objects outlet to Max.
The outlet() function takes as its arguments the number of the outlet to use and the information to send out. The outlet
numbering starts at 0 for the leftmost (and, in our case, only) outlet.

Try running the patch again, knowing how the code works. See if you can work out at what point the equation becomes
chaotic, and why.

Variable Scope
The key to the success of our JavaScript code resides in the use of x as a global variable. JavaScript, like many scripting
languages, will dynamically allocate variables as you use them, allowing you to use new variable names as you go without
having to predefine them all ahead of time. These dynamic variables, however, are local to the functions within which they
are used. For example, if we had a variable i in our msg_float() function, our bang()function would not be able to use it.
Similarly, we could use i as a variable in both functions independently of one another. Because we explicitly defined x as a
variable in our global code, both msg_float() (which evaluates x, sets it to a new value, and sends it out to our patch) and
bang() (which prints the current value of x in the Max window) are talking about the same thing when they refer to x.

Comment out the line:

var x = 0.66;

by placing two slashes (//) at the beginning of it. Save your script, and either recreate the js object or reopen the tutorial
patch. Try to run the patch.

With xundefined, our js object reports reference errors when you send it a float or a bang. This is because it is trying to
access a variable that has never been initialized. We could remove these errors by setting x to some value within each of our
functions, but we would then be using x locally. Not only would this prevent us from sharing the value of x between our two
functions, it would also reinitialize xevery time we sent a float into js, preventing our object from maintaining x over
multiple iterations of the function.

Uncomment the variable declaration for x. All should be well again when you save your script.

Conclusion
The js object is a powerful tool that lets you write code using a standard programming language within Max. You define
inlets, outlets, and global variables in the global code section of the script (which resides outside of any specific function).
Methods that respond to particular messages (floats, bang messages, etc.) are written as functions below the global code,
and are executed in response to the relevant messages from the Max environment. You can use the post()function to print
information in the Max window (much as youd use the print object in a patch), and you can use the outlet() function to
send messages out of your js object back to the Max patcher containing it. You can write JavaScript code directly into the
text editor for the js object; when you save a modified script, the js object will scan your code for programming mistakes
such as syntax and reference errors, allowing you to program and debug your code from within Max.

Code Listing

// popu.js
//
// simulates the logistic population equation:
// f(x) = rx(1-x)
//
// input is r. output is current x.
//
// rld, 5.04
//
// inlets and outlets
inlets = 1;
outlets = 1;
// global variables
var x = 0.66;
// float -- run the equation once
function msg_float(r)
{
x = r*x*(1.-x);
outlet(0, x);
}
// bang -- post the current population to the max window
function bang()
{
post(the current population is);
post(x);
post();
}

See Also
Name Description
js Execute Javascript
Using JavaScript to create patcher elements
JavaScript Tutorial 2: JavaScript Scripting
Introduction
With the Max js object, its possible to use JavaScript code to perform patcher scripting, where you can create Max objects in
a patcher dynamically, setting their properties, sending them messages, and making connections between them. JavaScript
allows you to use procedural code to generate patcher elements in ways that may be more difficult to do through messages to
the thispatcher object (the other way to automatically create Max objects in a patcher). This Tutorial covers how to create
and delete objects and connections in a Max patch through custom methods written in JavaScript, as well as to show how to
use methods to handle custom messages coming from the patcher.

Patcher Scripting with JavaScript


When you initially open the tutorial patch, you will see a largely empty patcher with a js object in the lower part of the
patcher window. The js object has loaded a JavaScript source file called autosurface.js, which is located in the same folder
as the Tutorial patch.

The js object is configured to send numbers to a MIDI output device (using the makenote and noteout objects). It also has
a right outlet sending values to the right inlet of the pack object driving messages to a multislider object. In addition, our js
object has a number of objects connected to its inlet. A metro object is connected to our js object, as are two message boxes
that will send the messages sliders $1 and reverse $1, where $1 in each case is the value present in the number box
connected to them.

From the patch layout, we can infer that the JavaScript code in our js object should have at least three functions, for bang,
sliders, and reverse. It actually has one more, which will become apparent when we use the patch.

Patch Auto-Generation
Select the number box attached to the message box containing the sliders $1 message. Type in or scroll to the number 5,
and watch what happens. Change the value in the number box. Try setting it to a large number (like 50).
Set it to 0, and see what happens.

In response to our sliders $1 message, our js object dynamically creates Max objects and connections through scripting. It
creates pairs of ctlin and slider objects to match the number of sliders you request through the message to the js object.
Furthermore, it creates a funnel object with the appropriate number of inlets for the slider objects and makes the
appropriate connections between them. The funnel object is then connected to our js object, allowing the values generated
by the sliders to be used by our JavaScript code as well.

As you create sliders, note that the ctlin objects are automatically numbered to listen to incrementing MIDI controller
numbers. As a result, a MIDI control surface that sends MIDI continuous control values on multiple controller numbers will
send values to independent slider objects. Also, note than when you decrement the number of sliders, the excess objects will
disappear (actually, everything disappears and is recreated again). If you set the number of sliders to 0, all the script-created
objects (including the funnel) will be deleted from the patch.
Set the number of sliders to something modest, such as 5. Change the values in the slider objects, either by clicking on them
or by using a MIDI controller input. Turn on the metro object by clicking the toggle attached to it. The values in the slider
objects should come out of the js object in turn, creating a sequence of MIDI notes. Double-click the noteout object to select
a valid MIDI synthesizer, and you should hear them.

The multislider object to the right of the patch will give you a running display of the current note out of our sequencer, set at
its appropriate position in the sequence.

Click the toggle attached to the message box containing the message reverse $1. Note that the order in which the slider
values are sequenced is now backwards. Our multislider display runs backwards as well.
In brief, our js object dynamically creates a scalable MIDI control surface (with ctlin and slider objects), and uses those
objects values to create a simple MIDI step sequencer. The number of sliders created by our JavaScript code determines the
length of the sequence.

Turn off both toggle objects, stopping the sequence and putting the sequencer transport back into forward mode. Lets look
at the code for our js object.
The Global Block: Arrays and Maxobjs
Double-click the js object in the Tutorial patch. The code for autosurface.js should appear. At the top of the code should be
the familiar comment block, explaining what the script does. Below that we should see our global code statements:

// inlets and outlets


inlets = 1;
outlets = 2;
// global variables and arrays
var numsliders = 0;
var seqcounter = 0;
var thereverse = 0;
var thevalues = new Array(128);
// Maxobj variables for scripting
var controlin = new Array(128);
var thesliders = new Array(128);
var thefunnel;

As we saw in the previous tutorial, our inlets and outlets at the top of the code tell js how many inlets and outlets we want in
our object.

The following block of code defines some variables that our JavaScript code will need to use globally. These variables include:
numsliders: Stores how many sliders (ctlin and slider pairs) we have in our patch. This is set by the sliders message to our
js object. seqcounter: Stores the current point in our sequence. This is driven by the metro object in our patch, and
therefore is changed by a bang() method in our code. thereverse: Sets whether or not our sequencer is running backwards.
This is set by the reverse message to our js object. thevalues: An array (see below) of values reflecting the state of the
slider objects in our patch. The funnel object in our patch sets these values by sending lists to our object.

The new Array() constructor creates arrays in JavaScript. The array variable thevalues, above, has 128 elements, which are
accessed by bracket notation following the array name, e.g.:

k = thevalues[5];

will set the variable k to the value of the sixth element (starting from 0) of the array thevalues.

thevalues[n] = 55;

will set the element n of the our array thevalues to 55.


Note that JavaScript treats Arrays as objects, so that:

k = thevalues.length;

will set the variable k to the number of elements in the array thevalues. For more information on this, consult any good
JavaScript reference.

After our variable declarations, we have variables that we will use to reference dynamically created objects in our Max patch.
These variable names are used internally in our JavaScript code so that we can create, connect, delete, and modify objects all
through properties to these objects. Objects in js that refer to Max objects in a patcher are referred to as Maxobjs. We have
the following Maxobj variables in our script: controlin: An array of Maxobjs that refer to the ctlin objects in our patch.
thesliders: An array of Maxobjs that refer to the slider objects in our patch. thefunnel: A Maxobj which references the
funnel object in our patch.

Note that there is no difference in JavaScript variable declaration with relation to the type of value that the variable stores;
integers, floats, strings, and objects are all considered equivalent when declaring a variable. Similarly, arrays are defined
simply to refer to quantity of information, rather than what type of information will be stored in them. Similarly, JavaScript
will correctly type variables following a calculation, e.g.:

x = 4/2;
will set the variable x to 2 (an integer), whereas:

x = 3/2;

will set the variable x to 1.5 (a floating-point value). Variables can switch types dynamically throughout their existence. This
use of untyped variables only exists within the JavaScript environment, however, which is why we still need independent
methods (msg_int() and msg_float()) to deal with differently typed numbers coming in from Max.

We will use various properties of the Maxobj object class to perform our scripting, all of which is accomplished by a single
function: our sliders() method.

Arguments, Agreements
Our js object responds to the sliders message via a method contained in the sliders() function (remember that the function
name typically matches the message you want to trigger that function). Examine the code for the sliders() function. The
comments at the top of each section explain whats happening at each step in the process:

// sliders -- generates and binds the sliders in the max patch


function sliders(val)
{
if(arguments.length) // bail if no arguments
{
// parse arguments
a = arguments[0];
// safety check for number of sliders
if(a<0) a = 0; // too few sliders, set to 0
if(a>128) a = 128; // too many sliders, set to 128
// out with the old...
if(numsliders) this.patcher.remove(thefunnel); // if we've done this before, get rid
of the funnel
for(i=0;i<numsliders;i++) // get rid of the ctlin and slider objects using the old
number of sliders
{
this.patcher.remove(controlin[i]);
this.patcher.remove(thesliders[i]);
}

// ...in with the new


numsliders = a; // update our global number of sliders to the new value
if(numsliders) thefunnel = this.patcher.newdefault(300, 300, "funnel", a); // make the
funnel
{
controlin[k] = this.patcher.newdefault(300+(k*50), 50, ctlin, k+1);
thesliders[k] = this.patcher.newdefault(300+(k*50), 100, slider);
this.patcher.connect(controlin[k], 0, thesliders[k], 0);
this.patcher.connect(thesliders[k], 0, thefunnel, k);
}

// connect new objects to this js object's inlet


ourself = this.box; // assign a Maxobj to our js object
if (numsliders) this.patcher.connect(thefunnel, 0, ourself, 0); // connect the funnel
to us
}
else // complain about arguments
{
post(sliders message needs arguments);
post();
}
}

In pseudo-code, our sliders() function performs the following steps: Check to see if the arguments for the sliders method are
valid. If true Make sure the number of sliders requested are in a reasonable range (0-128) Delete any objects previously
created by our js object. Make the new objects and connect them to one another. Find our js object (see below) and connect
our new funnel to it. If false Post an error message in the Max window and exit the function.
Our JavaScript code takes advantage of two important features of procedural programming, namely conditional statements
(ifelse) and iteration (for() loops). If youve used another programming language such as C or Java, you should find these
constructions familiar. A JavaScript reference will help you with the specifics.

One of the first things we do in our sliders() function is check to see what the arguments were to the sliders message sent in
from the patcher. We do this by checking the arguments property of the function itself, e.g.:

if(arguments.length) {
// some code here
}

will execute the code between the braces only if there are a non-zero number of arguments to the message that called the
function. Otherwise, that part of the code will be ignored. Similarly, you can access the arguments by number as an array:

a = arguments[0];

will assign the variable a to the value stored in the first argument of the message. In our case, this refers to the number of
sliders we want to create.

Object Creation and Maintenance


From the perspective of using js for object creation in Max, the Maxobj class allows us to use our object variables to create,
connect, and destroy objects. This is done by first accessing the Patcher object, which is a JavaScript representation of our
Max patch. The statement:

this.patcher.remove(thefunnel)

tells js to find a Maxobj called thefunnel in the Patcher called this (which is always the patcher containing the js object) and
delete it. The this in the statement is actually optional, but its worth noting that you can use JavaScript to control objects in
patches other than the one in which the js object resides.
To create an object, we assign a variable to a new Maxobj created by the Patcher:

thefunnel = this.patcher.newdefault(300, 300, funnel, a);

In this case, the Maxobj thefunnel is created to be a default object at coordinates 300 by 300 on the patcher window. The
objects class is set to funnel, with the objects arguments set to whatever is contained in the variable a.
Note: the newdefault() method to the Patcher object creates a new object just as if you had created it manually from the
palette or patcher contextual menu. This simplifies scripting substantially. If you wish to specify all the object parameters
(object width, flags, etc.) you can use the newobject() method instead.

Connections are made by taking two Maxobjs and linking them using the connect() method to a Patcher object, e.g.:

this.patcher.connect(thesliders[5], 0, thefunnel, 5)

will connect the leftmost (0) outlet of the sixth Maxobj in the array thesliders to the sixth inlet of the Maxobject thefunnel.
Remember that numbering starts at 0 for both arrays and inlet/outlet numbers.

We use iteration and arrays to create multiple objects at once, for example:

for(k=0;k<8;k++)
{
controlin[k] = this.patcher.newdefault(300+(k*50), 50, ctlin, k+1);
thesliders[k] = this.patcher.newdefault(300+(k*50), 100, slider);
this.patcher.connect(controlin[k], 0, thesliders[k], 0);
this.patcher.connect(thesliders[k], 0, thefunnel, k);
}

will automatically generate 8 ctlin and slider objects spaced 50 pixels apart on the patcher window (starting at horizontal
coordinate 300), connect them to one another, and then connect them to the funnel object referenced by thefunnel. Note
that the variable k in our JavaScript code is never declared, since we only use it as a local variable (in the sliders() function)
and re-initialize it every time that function is called. In our actual JavaScript code in the Tutorial patch, the number 8 is
replaced by the local variable a, which represents the number of sliders we want to create.

Finding Ourself in All of This


One important thing we accomplish in our sliders() method is the connection of the JavaScript-created funnel object to our
js objects inlet. However, our js object was created by hand, not by our JavaScript code (this would be impossible, if you
think about it). How do we bind a Maxobj to an object that was created independently of a JavaScript program?

ourself = this.box; // assign a Maxobj to our js object

The box property of our patcher returns a Maxobj referring to our js object itself! We then take the variable ourself and
assign it to our js object. This allows us to make connections to the object containing our JavaScript code.
We then connect our funnel object to our js object using our newly assigned Maxobj ourself:

this.patcher.connect(thefunnel, 0, ourself, 0);

Other Methods
The js object in this Tutorial doesnt just create and connect a MIDI control surface; it also reacts to messages from the
control surface as well as other messages from the Max patcher. Open up the source code for the js object in the Tutorial
patch again, and look for the function called list():

// list -- read from the created funnel object


function list(val)
{
if(arguments.length==2)
{
thevalues[arguments[0]] = arguments[1];
}
}

As with our sliders() function, our list() function first checks out how many values weve sent in from Max, e.g.:

if(arguments.length==2) {}

The funnel object puts out a list corresponding to the number of the inlet receiving the value followed by the value received.
For example, the number 55 arriving at the second inlet (which is really inlet number 1) will trigger the list 1 55 from the
funnel object. We check to make sure we have two arguments in our message before we proceed in our list() method, as we
use both the values in the list in the function. We use the first argument (which slider we moved) to determine which
element of the array thevalues we set to the second argument (the value).

Look at the bang() and reverse() functions in the JavaScript code.

// bang -- steps through sequencer


function bang()
{
if(seqcounter>=numsliders) // reset sequencer
{
seqcounter = 0;
}
if(thereverse) // read from the array backwards
{
outlet(1, numsliders-seqcounter-1); // send out our location in the sequence
outlet(0, thevalues[numsliders-seqcounter-1]); // send out the current note
}
else // read from the array forwards
{
outlet(1, seqcounter); // sound out our location in the sequence
outlet(0, thevalues[seqcounter]); // send out the current note
}
seqcounter++; // increment the sequence
}

// reverse -- changes sequence direction


function reverse(val)
{
if(arguments.length)
{
thereverse = arguments[0]; // flip it
}
}

Our bang() method (which in our patch is triggered by a metro object) steps through a sequence of values in a manner
analogous to the counter object. The maximum count is set by the number of sliders we have in our patch (defined by
numsliders). The direction of the counting is always upwards, snapping back to 0 when we exceed the number of sliders.
The reverse() function sets a variable (thereverse) based on the arguments for a reverse message sent in from Max. This
changes the way in which the bang() method reads from the array (thevalues) storing the numbers from our control surface
of slider objects. Our two outlet() functions send our current index value out our js objects right (1) outlet, followed by the
value at that index in the sequence out our js objects left (0) outlet. Note that we follow the important Max convention of
outputting values from outlets in a right-to-left order. Otherwise, our pack object would be triggered by its left inlet before it
receives the value it needs in its right inlet.

The outlet() function outputs the value at the current index in the sequence out our js objects left (0) outlet.
Now that you know how the JavaScript code is working, play with the patch some more. Think about how you would
recreate the sequencer using the normal Max table and counter objects.

Conclusion
The js object offers you a powerful way to create Max patches dynamically in JavaScript. Object creation is accomplished
through the assignment of variables to Maxobj objects created by a Patcher object, which represents the patch in JavaScript.
The newdefault() and newobject() methods allow you to create objects, which can be destroyed by a remove() method. The
connect() method lets you make patcher connections between Maxobjs in your script. A Maxobj can be assigned to the js
object itself through the box property to the patcher. When designing JavaScript functions to act as methods for Max
messages, the arguments passed with the messages are available through the arguments array from within the function.

Code Listing

// autosurface.js
//
// automatically generate a MIDI control surface with
// visual feedback (sliders), hook it up to a funnel
// object, and use it to drive a simple sequencer.
//
// rld, 5.04
//
// inlets and outlets
inlets = 1;
outlets = 2;
// global variables and arrays
var numsliders = 0;
var seqcounter = 0;
var thereverse = 0;
var thevalues = new Array(128);
// Maxobj variables for scripting
var controlin = new Array(128);
var thesliders = new Array(128);
var thefunnel;

// methods start here


// sliders -- generates and binds the sliders in the max patch
function sliders(val)
{
if(arguments.length) // bail if no arguments
{
// parse arguments
a = arguments[0];
// safety check for number of sliders
if(a<0) a = 0; // too few sliders, set to 0
if(a>128) a = 128; // too many sliders, set to 128
// out with the old...
if(numsliders) this.patcher.remove(thefunnel); // if we've done this before, get rid
of the funnel
for(i=0;i<numsliders;i++) // get rid of the ctlin and slider objects using the old
number of sliders
{
this.patcher.remove(controlin[i]);
this.patcher.remove(thesliders[i]);
}
// ...in with the new
numsliders = a; // update our global number of sliders to the new value
if(numsliders) thefunnel = this.patcher.newdefault(300, 300, "funnel", a); // make the
funnel
for(k=0;k<a;k++) // create the new ctlin and slider objects, connect them to one another
and to the funnel
{
controlin[k] = this.patcher.newdefault(300+(k*50), 50, ctlin, k+1);
thesliders[k] = this.patcher.newdefault(300+(k*50), 100, slider);
this.patcher.connect(controlin[k], 0, thesliders[k], 0);
this.patcher.connect(thesliders[k], 0, thefunnel, k);
}

// connect new objects to this js object's inlet


ourself = this.box; // assign a Maxobj to our js object
if (numsliders) this.patcher.connect(thefunnel, 0, ourself, 0); // connect the funnel
to us
}
else // complain about arguments
{
post(sliders message needs arguments);
post();
}
}
// list -- read from the created funnel object
function list(val)
{
if(arguments.length==2)
{
thevalues[arguments[0]] = arguments[1];
}
// bang -- steps through sequencer
function bang()
{
if(seqcounter>=numsliders) // reset sequencer
{
seqcounter = 0;
}
if(thereverse) // read from the array backwards
{
outlet(1, numsliders-seqcounter-1); // send out our location in the sequence
outlet(0, thevalues[numsliders-seqcounter-1]); // send out the current note
}
else // read from the array forwards
{
outlet(1, seqcounter); // sound out our location in the sequence
outlet(0, thevalues[seqcounter]); // send out the current note
}
seqcounter++; // increment the sequence
}

// reverse -- changes sequence direction


function reverse(val)
{
if(arguments.length)
{
thereverse = arguments[0]; // flip it
}
}

See Also
Name Description
js Execute Javascript
Scheduling events and sharing data in JavaScript
JavaScript Tutorial 3: JavaScript Tasks, Arguments, and Globals
Introduction
The js object allows you create JavaScript functions that use the Max scheduler. These functions can be triggered by Max
messages to the js object. The timing interval at which the function is called, how many times it repeats (including whether
it repeats indefinitely), and whether it begins executing immediately or at some point in the future can all be determined by
your code.

In this Tutorial, well look at how scheduling works in JavaScript. Along the way, well look at two other important features
of the JavaScript implementation in Max: js object arguments (which allow you to pass arguments directly to your
JavaScript from the object box) and Global objects (which allow you to share data between internal js data structures and
Max).

Scheduling in JavaScript
Take a look at the tutorial patcher. Youll see four js objects, all of which use the same JavaScript source file (called
globaltask.js), which is saved on disk in the same folder as the Tutorial patch.

Click the button object at the top of the patch labeled send a bounce. The four js objects should begin to generate numbers
that are then sent downstream to your MIDI synthesizer output (via the makenote and noteout objects). Double-click the
noteout object and select a valid output synthesizer, and you should begin hearing notes. Additional button objects are
connected to the left outlets of the js objects to provide visual feedback on when a number is being sent. In addition, a
patcher object called view receives the bang messages from the button object and creates a scrolling visual feedback of the
generated rhythm with a multislider object.
Note that the specific timing of the four objects, as well as what pitches they generate, are different; these are determined by
the arguments to the js objects (more on this later).
The JavaScript code used in the js objects is a simple mock-up of an exponentially decaying timing function (analogous to a
rubber ball being dropped onto a hard floor). Notes are sent at an exponentially increasing rate, until the speed at which
they are sending exceeds a threshold value (five milliseconds, in the case of our script). Upon exceeding that threshold, the
function stops and a bang is sent out of the right outlet of our js objects to notify that the timing function has ceased. The
use of a done bang is a common convention among Max objects to signify the completion of a task (c.f. line, uzi, coll, etc.).
Click on the toggle labeled repeat and click the top button again. Notice that the cycle of bouncing notes repeats, as the
bang from the js objects cause them to retrigger themselves. The difference in the timing acceleration of the four js objects
will cause them to phase over multiple iterations of the cycle (note how this is displayed in the multislider). If you click the
toggle again, the current cycle of bounces will complete in each object and then stop. Double-click any of the js objects in
the patch; lets examine their code.

Right on Schedule
Examine the global code for our script:

// inlets and outlets


inlets = 1;
outlets = 2;
// define global variables and set defaults
var tsk = new Task(mytask, this); // our main task
var count = 0;
var decay = 1.0;
// defaults for arguments
var dcoeff = -0.0002; // decay coefficient
var note = 60; // note to trigger upon bounce
// process arguments (decay coefficient, note to trigger)
if(jsarguments.length>1) // argument 0 is the name of the js file
{
dcoeff = jsarguments[1];
}
if(jsarguments.length>2)
{
note = jsarguments[2];
}
// Global (Max namespace) variables
glob = new Global(bounce);
glob.starttime = 500;

The global code section of our JavaScript file, which defines the familiar inlets, outlets (we have two this time), and variables,
has a number of things that we havent encountered before. The first is a variable assigned to a special object called Task:

var tsk = new Task(mytask, this); // our main task

This creates a new Task object in JavaScript referred to by the name tsk. When we call methods for tsk, they will relate to
the scheduling of a function called mytask(). The controlling object for the Task will be our js object (which we refer to as
this). If we would like to execute our task once, we would write:

tsk.execute(); // run our task function once

If we would like to make our task repeat every 250 milliseconds for 20 repetitions, we would write:

tsk.interval = 250;
tsk.repeat(20);

If no arguments are given to the repeat() method, the Task will be scheduled indefinitely, until we cancel it as follows:

tsk.cancel(); // cancel our task

The execute(), repeat(), and cancel() methods give us all of the flexibility we need to schedule repeating events in
JavaScript. In addition to the interval property of the Task object, we can also find out whether a task is running or not
(running) and how many times it has been called (iterations), for example.

One important thing to keep in mind is that all methods in the js object (whether triggered by Max messages or scheduled
internally through tasks) are executed at low priority in the Max scheduler. This means that, while they will always execute
and send data to Max in the correct order, they cannot be relied on for critically accurate timing if the scheduler is
overloaded with other actions.

Once weve defined our Task tsk, we trigger it through the bang() method to our js object:

function bang()
{
tsk.cancel(); // cancel the bounce, if it's going already
count = 0; // reset the number of bounces
decay = 1.0; // reset the initial decay
tsk.interval = glob.starttime; // set the initial task interval
tsk.repeat(); // start the bouncing
}

When any of our js objects receive a bang, they cancel any previously scheduled tsk tasks, reset some variables that are
relevant to the task function, set an initial timing interval for the task, and then start it going again.

Start a bounce in the Tutorial patch by clicking the button at the top. Click the message box labeled stop. The notes should
cease. Our stop() function will cancel our previously scheduled task simply by calling the cancel() method to tsk:

function stop()
{
tsk.cancel(); // cancel our task
}

The Task at Hand


Our Task object, once set in motion by our bang() method, calls the function defined in its initial declaration.
Peruse the code for the mytask() function:

// mytask -- the scheduled task - output number and reschedule next task
function mytask()
{
if(arguments.callee.task.interval>5) // keep bouncing
{
outlet(0, note); // send a note value
decay = decay*Math.exp(++count*dcoeff); // increment the decay variable
arguments.callee.task.interval=arguments.callee.task.interval*decay; // update the
task interval
}
else // bounce interval is too small, so consider it 'floored'
{
arguments.callee.task.cancel(); // cancel the task
outlet(1, bang); // send a bang out the right outlet to signify that we're done
bouncing
}
}

Unlike the other functions weve used in our JavaScript tutorials, we dont intend our mytask() function to be triggered by a
Max message from outside the js object. By default, any declared function in a js object will respond to an appropriately
named message from the Max environment. Since we dont want mytask() triggerable by a mytask message from our
patcher, we place the following line of code after the function ends: mytask.local = 1;

This statement makes mytask() local to the js environment, and inaccessible from outside.
Our Task function accomplishes two things: it sends out an integer to Max (triggering a MIDI note), and increments its own
timing interval so that the next run of mytask() will happen a little bit sooner. Outside of the task function, we can change
our timing interval by setting the interval property to the task (e.g. tsk.interval = 250). Properties and methods of a Task
object can be modified within the task function by referring to the Task as the callee, e.g.:

arguments.callee.task.interval=250; // adjust timing of task to 250


arguments.callee.task.cancel(); // have the task cancel itself

We use this reflexive capability to change our Task objects timing interval from within the Task function. When the timing
interval decreases to a suitably low value (5 milliseconds in our case), we also use this feature to have our Task function
cancel the Task that called it in the first place.

Using a Math Object


Look at the code for mytask() again, paying attention to the line that changes the decay value with every bounce:

decay = decay*Math.exp(++count*dcoeff); // increment decay variable

In addition to the objects that allow for interaction between JavaScript and Max (Maxobj, Task), JavaScript has a number
of core objects that can be useful when writing programs for js. The Math object has a large library of built-in properties
and methods that allow you to perform commonly needed mathematical functions. In our code, we use the exp() method to
the Math object, which returns the value of E (the base of the natural logarithm: roughly 2.71828) to the power of its
argument (in this case, our decay coefficient multiplied by the next ball count). This is crucial to the modeling of the
exponentially increasing rate of the bounce event.

The Math object in JavaScript is roughly analogous in features to the math library in C or the expr object in Max (which is
itself based on the C math library). A number of other predefined core objects (e.g. Date, String) provide similar extensions
to the language that more-or-less match their C equivalents (e.g. time, string).

Arguments to the js Object


Two of our scripts variables (dcoeff and note) are determined by the arguments given to the js object. These arguments are
parsed in our global code block by checking the jsarguments property of our js object:

if(jsarguments.length>1) // argument 0 is the name of the js file


{
dcoeff = jsarguments[1];
}
if(jsarguments.length>2)
{
note = jsarguments[2];
}

Note that argument 0 is the name of the JavaScript file (e.g. globaltask.js), so, realistically, we will usually start looking at
the arguments starting at 1. The above code checks to make sure that the arguments exist before we attempt to assign their
values to variables.

The Global Object


Close the js objects editor and return to the tutorial patch for a moment. In the lower-left hand corner, look at the number
box connected to the message box containing the text ; bounce starttime $1. Type 2000 into the number box and enter
the value. Send a bounce by clicking on the button at the top. Notice that the timing between bounces in all the objects is
wider than before. Try changing the number box to a small value. The timing interval should start out quicker.
We would expect our message box to have sent the message starttime 2000 to a receive object somewhere in our Max
patch called bounce. In fact, it sets the starttime property of a Global object (assigned to respond to the name bounce) to
2000 within our js objects. We accomplish this be declaring a Global object in our global code:

// Global (Max namespace) variables


glob = new Global(bounce);
glob.starttime = 500;

In our code, weve created a variable (glob) and assigned it to a new Global object. The argument to the global object
(bounce) is the name in the Max namespace that will be tied to the object. Any message sent to bounce within Max will
attempt to set properties of the Global object using that name. Note that internally, we refer to the Global object by a variable
name of our choosing (glob), not by the symbol with which Max and our js object communicate.
Weve added a property (starttime) to our object simply by assigning it in our global block. Now, any message beginning
with starttime sent to bounce in our Max patch will set that property to its arguments.

Furthermore, this object is truly global, in the sense that not only can Max set it from outside of a js object, multiple js
objects share the specific instance of this object and its properties. You could use this feature to have multiple js objects
share information, as well as have Max broadcast information to multiple js objects.

Conclusion
JavaScript allows you to schedule events dynamically using the Task object. You create a Task and bind it to a function that
gets called by the Task. You can activate and cancel the task and set the Tasks timing interval and how often it repeats.
Furthermore, by using the callee property of the function called by the Task, you can set these things from within the
scheduled event itself. All methods in js objects (whether called internally or by Max messages) are executed at low priority
in the scheduler.

JavaScript has a number of core objects that provide functionality for common programming routines that you may find
necessary. The Math object, for example, gives you access to a variety of mathematical functions that you would find in the
C math library or in the Max expr object.
Arguments to the js object are handled by the jsarguments property to the object. The object starts numbering its
arguments at 0, but the first argument to js is the name of the source file it had loaded.
Global objects in JavaScript allow communication between js objects, and allow for object properties to be set directly from
the Max environment.

Code Listing

// globaltask.js
//
// generate a stream of numbers timed to an exponentially
// decaying time curve. arguments set the curve and the
// value to output.
//
// rld, 5.04
//
// inlets and outlets
inlets = 1;
outlets = 2;

// define global variables and set defaults


var tsk = new Task(mytask, this); // our main task
var count = 0;
var decay = 1.0;
// defaults for arguments
var dcoeff = -0.0002; // decay coefficient
var note = 60; // note to trigger upon bounce
// process arguments (decay coefficient, note to trigger)
if(jsarguments.length>1) // argument 0 is the name of the js file
{
dcoeff = jsarguments[1];
}
if(jsarguments.length>2)
{
note = jsarguments[2];
}
// Global (Max namespace) variables
glob = new Global(bounce);
glob.starttime = 500;

// bang -- start the task


function bang()
{
tsk.cancel(); // cancel the bounce, if it's going already
count = 0; // reset the number of bounces
decay = 1.0; // reset the initial decay
tsk.interval = glob.starttime; // set the initial task interval
tsk.repeat(); // start the bouncing
}

// stop -- allow the user to stop the bouncing


function stop()
{
tsk.cancel(); // cancel our task
}
// mytask -- the scheduled task - output number and reschedule next task
function mytask()
{
if(arguments.callee.task.interval>5) // keep bouncing
{
outlet(0, note); // send a note value
decay = decay*Math.exp(++count*dcoeff); // increment the decay variable
arguments.callee.task.interval=arguments.callee.task.interval*decay; // update the
task interval
}
else // bounce interval is too small, so consider it 'floored'
{
arguments.callee.task.cancel(); // cancel the task
outlet(1, bang); // send a bang out the right outlet to signify that we're done
bouncing
}
}
mytask.local = 1; // prevent triggering the task directly from Max

See Also
Name Description
js Execute Javascript
Designing graphical user interfaces with JavaScript
JavaScript Tutorial 4: Designing User Interfaces in JavaScript
Introduction
The jsui object allows you use JavaScript to design graphical user interface objects for use in the Max environment. The
JavaScript implementation for the jsui object is similar to that used in the js object, with an added API that supports two-
and three-dimensional vector graphics drawn with OpenGL commands. It also includes methods for handling mouse
interaction in the jsui object window.
In addition to the advantages provided by JavaScript, jsui provides a number of built-in features that make UI development
flexible:
jsui objects draw their geometries relative to the size of the jsui object box; resizing a jsui object will correctly resize all
of the drawn elements inside of it.
jsui objects work with a vector graphics language (OpenGL) that supports a wide variety of simple shape and drawing
primitives. In addition, a number of higher-level graphics functions are available. The jsui object can also perform anti-
aliasing on the image to give you as smooth an object as possible, though this comes with a decrease in performance.
The jsui object allows you to draw a scene that exceeds the boundaries of the object box. By adjusting the camera
orientation in the OpenGL space, you can create and manage different views of the same UI object. In addition to
using the jsui object for user-interface design, one could use the object simply as an OpenGL graphics engine built into
the Max patcher for algorithmic drawing operations.

This Tutorial assumes that youve already looked at the other JavaScript Tutorials. The jsui object bases most of its graphics
language on OpenGL functions, the specifics of which are beyond the scope of this Tutorial. The OpenGL Redbook is the
standard reference for these functions. An online version is available at:
http://www.opengl.org/documentation/red_book/

The OpenGL API supported by jsui is contained in an object called jsui sketch. This object understands most OpenGL
commands and symbolic constants. Converting between OpenGL code (e.g. as given in C in the Redbook code examples)
and sketch methods and properties for jsui JavaScript code is quite straightforward if you observe the following guidelines:
All OpenGL commands are lowercase in the jsui sketch object, e.g. glColor() becomes sketch.glcolor().
OpenGL symbolic constants, in addition to being lowercase, lose their GL_ prefix, so that GL_CLIP_PLANE1 becomes
clip_plane1(), for example.

A number of higher-level drawing and shape commands are available which may speed up user interface development. The
jsui sketch reference found in the Javascript in Max manual (and the help patch for the jsui object) contain lists of these
commands.

jsui in Action
Take a look at our tutorial patcher. You will see a jsui object containing a grid of light red circles against a green background.
Clicking on a circle inside the object will change the circles color to a darker red. Clicking on the same circle again will
change the color back to light red.

Click on some circles so that they are highlighted (in dark red). At the right of the patch, manipulate some of the slider
objects above the router object. Note the correspondence between which circles are clicked and which slider objects below
the router echo the values from above. Click on the message box labeled clear attached to the jsui object. The circles should
all go to light red and the router object will no longer pass messages from the slider objects above. Click on the message
box containing the list 0 0 1, 1 1 1, etc. The jsui object should update to show a diagonal row. The router object will now
pass messages from the first slider above to the first slider below, and so on.
Our jsui object uses JavaScript code to emulate some of the functionality of the Max matrixctrl object. The columns
represent the input to the router object; the rows specify the output. Our jsui communicates with the router object by
sending lists (in the format input output state) that tell the router object to pass messages received at an inlet to all the
appropriate outlets given the jsui objects current configuration.
Like the js object, the jsui object gets its program from a file written in JavaScript saved somewhere in the search path.
Because it is a graphical object, there is no object box to type in the name of the file. Instead, we set the JavaScript source file
using the jsui objects Inspector.
Unlock the tutorial patch and highlight the jsui object. Under the Object menu, select Get Info. An Inspector should
appear with the name of our jsui source file (mymatrix.js) in the text field labeled JavaScript File.

You can also set the size of the object in the Inspector, as well as turn on or off a border around the object. Disabling the
object border, combined with setting the background color of your Max patch to match that of your jsui object, can help you
design a seamless user interface.

The Drawing Code


The jsui object is graphical, so double-clicking the object will not open the text editor as it does with the js object. Instead,
click the message box labeled open. The text editor containing our JavaScript file (mymatrix.js) will appear. Our
JavaScript file is saved on disk in the same folder as the tutorial patch.

As with a js script, our code for the jsui object starts with a global block that allows us to define inlets and outlets for the
object and global variables for our code. It is also where we type commands that we want to occur when the object is
initialized:

// inlets and outlets


inlets = 1;
outlets = 1;
// global variables
var ncols=4; // default columns
var nrows=4; // default rows
var vbrgb = [0.8,1.,0.8,0.5];
var vmrgb = [0.9,0.5,0.5,0.75];
var vfrgb = [1.,0.,0.2,1.];
// initialize state array
var state = new Array(8);
for(i=0;i<8;i++)
{
state[i] = new Array(8);
for(j=0;j<64;j++)
{
state[i][j] = 0;
}
}
// set up jsui defaults to 2d
sketch.default2d();
// initialize graphics
draw();
refresh();

Our JavaScript code defines two global variables (ncols and nrows) which can be accessed by all functions, as well as a
number of global Array objects that define colors for the drawing and a state array that we will use to hold information
about which circles are on and which are off in our user interface.

Multi-dimensional arrays in JavaScript are allocated by an Array object in which each element of the Array is itself an
Array object (and so on, if more than two dimensions are needed). This may seem somewhat unusual if youve worked in
other programming languages where multi-dimensional arrays can be declared directly (e.g. C). The for() loops in our global
block accomplish this allocation and initialize all the elements of the state array to 0. Once a multi-dimensional array is
created, it can be referenced using common bracket notation, e.g. state[4][2].

Following our variable and array declarations, we find three commands that refer to the graphical behavior of the jsui object.
The first, sketch.default2d(), tells our jsui object to initialize a number of default behaviors with the assumption that we
will be giving it graphics commands for a two-dimensional scene. It sets a default view upon the OpenGL rendering context
and performs a number of utility routines to make it easy for us to simply start placing graphical elements in the window.
The draw() command (which could be named anything) refers to our main graphics function which we write to contain all
the commands needed to draw the user interface of the jsui object. The refresh() command copies the OpenGL backbuffer
(where the drawing is done initially to prevent flicker) to the actual screen display. Commenting out the refresh() command
will prevent our jsui object from ever showing us anything.
Below the global block, examine the draw() function. This is the function that provides jsui with all the commands it needs
to draw our screen interface:
// draw -- main graphics function
function draw()
{
with (sketch)
{
// set how the polygons are rendered
glclearcolor(vbrgb[0],vbrgb[1],vbrgb[2],vbrgb[3]); // set the clear color
glclear(); // erase the background
colstep=2./ncols; // how much to move over per column
rowstep=2./nrows; // how much to move over per row
for(i=0;i<ncols;i++) // iterate through the columns
{
for(j=0;j<nrows;j++) // iterate through the rows
{
moveto((i*colstep + colstep/2)-1.0, 1.0 - (j*rowstep + rowstep/2), 0.); // move
the drawing point
if(state[i][j]) // set 'on' color
{
glcolor(vfrgb[0],vfrgb[1],vfrgb[2],vfrgb[3]);
}
else // set 'off' color (midway between vbrgb and vfrgb)
{
glcolor(vmrgb[0],vmrgb[1],vmrgb[2],vmrgb[3]);
}
circle(0.7/Math.max(nrows,ncols)); // draw the circle
}
}
}
}

The graphics commands (everything beginning with gl, as well as the circle() command) are all methods and properties of
the sketch object, which encapsulates most of the OpenGL API, much as the Math object encapsulates most common math
functions.

The JavaScript with() statement allows us to use properties and methods belonging to an object (in this case the sketch
object that provides us with our OpenGL functionality) without having to reference sketch in every command. Without the
with(), we would have to write sketch.glcolor() instead of glcolor(), sketch.circle() instead of circle(), etc. This useful trick
could also be implemented in functions that rely heavily on other objects (e.g. Task or Patcher).

Our draw() function sets some default drawing behaviors and clears the window with the color defined by the vbrgb array.
It then iterates through our state array based on how many columns (ncols) and rows (nrows) weve defined for our object.
If a particular state element is 0 (off), it draws a circle in the color defined by vmrgb. If an element is 1 (on), the circle is
drawn in the vfrgb color. The position of the circles is determined by the number of rows and columns, and is based on
boundaries of our OpenGL world, which are set to be between 1.0 and 1.0 on both axes (i.e. the middle of our jsui window
in OpenGL coordinates is 0, 0).

The size of the world is not limited to coordinates in the range of 1.0 to 1.0; our default viewport merely sets us at the
center of the scene whose y range is 1.0 to 1.0 and whose x range is scaled based on the aspect ration of the object.
Because our object box happens to be square, our ranges are the same on both axes. Changing the viewport (by manipulating
the position of our virtual camera, for example) will change what coordinates are visible in the jsui objects box.

Setting Parameters
In the Tutorial patch, change the number box objects that set the rows and columns. Note that the object will dynamically
add up to eight rows and columns of circles based on those values. Look at the rows() and cols() functions in the JavaScript
code. Note that they call a bang() function after setting their variables.

// rows -- change number of rows in jsui


function rows(val)
{
if(arguments.length)
{
nrows=arguments[0];
bang(); // draw and refresh display
}
}
// cols -- change number of columns is jsui
function cols(val)
{
if(arguments.length)
{
ncols=arguments[0];
bang(); // draw and refresh display
}
}

The bang() function, which we call after nearly every change made to the object from Max (including mouse events), simply
calls draw() and refresh() as we did in our global block, causing the jsui object to update its window to reflect any graphical
changes.

// bang -- draw and refresh display


function bang()
{
draw();
refresh();
}

By only doing the drawing when necessary, we are able to reduce the amount of processor time the object uses.

In the tutorial patcher, change the swatch objects that set the frgb and brgb messages to our jsui object. Look at the
corresponding functions (frgb() and brgb()) in the JavaScript code. Note that the array for the off circles color (vmrgb) is
midway between the colors set by frgb and brgb messages:

// frgb -- change foreground (clicked) circle color


function frgb(r,g,b)
{
vfrgb[0] = r/255.;
vfrgb[1] = g/255.;
vfrgb[2] = b/255.;
vmrgb[0] = 0.5*(vfrgb[0]+vbrgb[0]);
vmrgb[1] = 0.5*(vfrgb[1]+vbrgb[1]);
vmrgb[2] = 0.5*(vfrgb[2]+vbrgb[2]);
bang(); // draw and refresh display
}
// brgb -- change background color
function brgb(r,g,b)
{
vbrgb[0] = r/255.;
vbrgb[1] = g/255.;
vbrgb[2] = b/255.;
vmrgb[0] = 0.5*(vfrgb[0]+vbrgb[0]);
vmrgb[1] = 0.5*(vfrgb[1]+vbrgb[1]);
vmrgb[2] = 0.5*(vfrgb[2]+vbrgb[2]);
bang(); // draw and refresh display
}

Color in OpenGL is represented as four floating-point values in the range 0.0-1.0, corresponding to the red, green, blue,
and alpha (transparency) amounts, respectively. This is in contrast to many video systems that commonly refer to color in
the integer 0-255 (with no alpha value). Most of the work in our frgb() and brgb() functions is to convert from the latter
(used by the swatch object) into the former (understood by the jsui object).

Mouse Interaction
Unlock the tutorial patcher and resize the jsui object (the circles should resize dynamically). Lock the patcher and notice
that the mouse clicks still change the states of the correct circles. Lock the patch again and look at the onclick() function in
the JavaScript code.
The onclick(), ondblclick(), and ondrag() functions, when defined, tell our jsui object what to do when a user clicks,
double-clicks, or drags the mouse across the object. The function is called with arguments for where in the objects window
the action occurred, as well as a number of flags (such as whether the mouse was depressed, the state of the shift key, etc.).
In our onclick() function, we only use first two arguments, corresponding to the x and the y of the mouse click.

// onclick -- deal with mouse click event


function onclick(x,y)
{
worldx = sketch.screentoworld(x,y)[0];
worldy = sketch.screentoworld(x,y)[1];
colwidth = 2./ncols; // width of a column, in world coordinates
rowheight = 2./nrows; // width of a row, in world coordinates
x_click = Math.floor((worldx+1.)/colwidth); // which column we clicked
y_click = Math.floor((1.-worldy)/rowheight); // which row we clicked
state[x_click][y_click] = !state[x_click][y_click]; // flip the state of the clicked
point
outlet(0, x_click, y_click, state[x_click][y_click]); // output the coordinates and
state of the clicked point
bang(); // draw and refresh display
}

Our OpenGL graphics world is defined in terms of floating-point coordinates (in our case, between 1.0 and 1.0). The jsui
mouse functions return coordinates based on which pixel (counting away from the upper left-hand corner of the object box)
the mouse event occurred. We need to convert between these two systems (of world coordinates and screen coordinates,
respectively) in order to properly evaluate the mouse events for our grid of circles. The sketch methods worldtoscreen() and
screentoworld() perform these conversions for us:

worldx = sketch.screentoworld(x,y)[0];
worldy = sketch.screentoworld(x,y)[1];

Once we know the width and height where we clicked, we can subdivide it based on how many circles we have on each axis:

colwidth = 2./ncols; // width of a column, in world coordinates


rowheight = 2./nrows; // width of a row, in world coordinates

We can then plug in the coordinates of the mouse click to figure out which circle we clicked nearest to:

x_click = Math.floor((worldx+1.)/colwidth); // which column we clicked


y_click = Math.floor((1.-worldy)/rowheight); // which row we clicked

We then reverse the element of the state array corresponding to the circle we clicked:

state[x_click][y_click] = !state[x_click][y_click];

After weve set the state array correctly, we send out a list corresponding to the change out our jsui objects outlet into Max.
We then bang our own jsui object, updating the graphics to reflect the change:

outlet(0, x_click, y_click, state[x_click][y_click]);


bang();

Note that we have set our onclick() function to be local, so that it cant be triggered from an onclick message sent from our
Max patch.

Familiarize yourself with the JavaScript code and how it relates to the behavior of the jsui object in the patcher. Click on the
toggle object to activate the metro object at the right of the patch. This will simulate some input from the slider objects.
Place post() statements in the JavaScript code to help navigate the values as they are passed from mouse click to list output.

Conclusion
The jsui object is a powerful tool to allow you to design and implement customizable user interfaces using JavaScript as a
programming language. The key points in the program involve the main drawing function (which defines a sequence of
commands to describe the jsui objects graphical display) and the mouse interaction functions onclick(), ondblclick(), and
ondrag(). Important things to note are the differences in color representation (floating point vs. integer) and spatial
coordinates (floating-point world coordinates vs. Cartesian pixel coordinates) between the OpenGL API used in the jsui
sketch object and the Max environment, respectively.

Code Listing

// mymatrix.js
//
// simulates a simple grid of clickable widgets (a la matrixctrl)
//
// rld, 5.04
//
// inlets and outlets
inlets = 1;
outlets = 1;
// global variables
var ncols=4; // default columns
var nrows=4; // default rows
var vbrgb = [0.8,1.,0.8,0.5];
var vmrgb = [0.9,0.5,0.5,0.75];
var vfrgb = [1.,0.,0.2,1.];
// initialize state array
var state = new Array(8);
for(i=0;i<8;i++)
{
state[i] = new Array(8);
for(j=0;j<64;j++)
{
state[i][j] = 0;
}
}
// set up jsui defaults to 2d
sketch.default2d();
// initialize graphics
draw();
refresh();
// draw -- main graphics function
function draw()
{
with (sketch)
{
// set how the polygons are rendered
glclearcolor(vbrgb[0],vbrgb[1],vbrgb[2],vbrgb[3]); // set the clear color
glclear(); // erase the background
colstep=2./ncols; // how much to move over per column
rowstep=2./nrows; // how much to move over per row

for(i=0;i<ncols;i++) // iterate through the columns


{
for(j=0;j<nrows;j++) // iterate through the rows
{
moveto((i*colstep + colstep/2)-1.0, 1.0 - (j*rowstep + rowstep/2), 0.); // move
the drawing point
if(state[i][j]) // set 'on' color
{
glcolor(vfrgb[0],vfrgb[1],vfrgb[2],vfrgb[3]);
}
else // set 'off' color (midway between vbrgb and vfrgb)
{
glcolor(vmrgb[0],vmrgb[1],vmrgb[2],vmrgb[3]);
}
circle(0.7/Math.max(nrows,ncols)); // draw the circle
}
}
}
}
// bang -- draw and refresh display
function bang()
{
draw();
refresh();
}
// rows -- change number of rows in jsui
function rows(val)
{
if(arguments.length)
{
nrows=arguments[0];
bang(); // draw and refresh display
}
}
// cols -- change number of columns is jsui
function cols(val)
{
if(arguments.length)
{
ncols=arguments[0];
bang(); // draw and refresh display
}
}

// list -- update our state to respond to a change from Max


function list(v)
{
if(arguments.length==3) // bail if incorrect number of arguments
{
state[arguments[0]][arguments[1]]=arguments[2]; // update our internal state based on
the list
outlet(0, arguments[0], arguments[1], arguments[2]); // echo the list out the outlet

}
bang(); // draw and refresh display
}
// clear -- wipe the state clean
function clear()
{
for(i=0;i<ncols;i++)
{
for(j=0;j<nrows;j++)
{
state[i][j]=0; // wipe the state
}
}
outlet(0, clear); // clear the router or matrix~ downstream
bang(); // draw and refresh display
}
// frgb -- change foreground (clicked) sphere color
function frgb(r,g,b)
{
vfrgb[0] = r/255.;
vfrgb[1] = g/255.;
vfrgb[2] = b/255.;
vmrgb[0] = 0.5*(vfrgb[0]+vbrgb[0]);
vmrgb[1] = 0.5*(vfrgb[1]+vbrgb[1]);
vmrgb[2] = 0.5*(vfrgb[2]+vbrgb[2]);
bang(); // draw and refresh display
}
// brgb -- change background color
function brgb(r,g,b)
{
vbrgb[0] = r/255.;
vbrgb[1] = g/255.;
vbrgb[2] = b/255.;
vmrgb[0] = 0.5*(vfrgb[0]+vbrgb[0]);
vmrgb[1] = 0.5*(vfrgb[1]+vbrgb[1]);
vmrgb[2] = 0.5*(vfrgb[2]+vbrgb[2]);
bang(); // draw and refresh display
}
// onresize -- deal with a resized jsui box
function onresize(w,h)
{
bang(); // draw and refresh display
}
onresize.local = 1; // make function private to prevent triggering from Max

// onclick -- deal with mouse click event


function onclick(x,y)
{
worldx = sketch.screentoworld(x,y)[0];
worldy = sketch.screentoworld(x,y)[1];
colwidth = 2./ncols; // width of a column, in world coordinates
rowheight = 2./nrows; // width of a row, in world coordinates
x_click = Math.floor((worldx+1.)/colwidth); // which column we clicked
y_click = Math.floor((1.-worldy)/rowheight); // which row we clicked
state[x_click][y_click] = !state[x_click][y_click]; // flip the state of the clicked
point
outlet(0, x_click, y_click, state[x_click][y_click]); // output the coordinates and
state of the clicked point
bang(); // draw and refresh display
}
onclick.local = 1; // make function private to prevent triggering from Max
// ondblclick -- pass buck to onclick()
function ondblclick(x,y)
{
onclick(x,y);
}
ondblclick.local = 1; // make function private to prevent triggering from Max

See Also
Name Description
jsui Create user interfaces with Javascript
swatch Select and display RGB colors
Getting MIDI input and output
MIDI Tutorial 1: Basic MIDI
Introduction
This tutorial will cover some of the basics of using the MIDI (Musical Instrument Digital Interface) communications
protocol. We will see how to receive MIDI information from input devices, send it to other hardware or software and select
the device that will get the sent information.

While the prevalence of software-only music systems have reduced the need for MIDI devices, the MIDI protocol is still
necessary for working with both hardware and software synthesizers and samplers. MIDI is also becoming more widely used
by artists working with physical interfaces, since it provides a compact and easy-to-use communications protocol for
receiving sensor information and producing control messages for motors and other controllable devices.

The midiin and midiout objects


The tutorial patcher contains a number of small MIDI-specific patches. The left-most patch changes a number box anytime
information is received from a MIDI input device (via the midiin object), then sends that information out to another MIDI
device (through the midiout object). However, you need to select which device will be used for MIDI input and output. A
simple way select a MIDI device is to double-click on the MIDI object you want to assign. Double-clicking on the midiin
object produces a menu of available MIDI inputs, while double-clicking on the midiout object will display a menu of MIDI
outputs.

In addition to the physical MIDI devices that are connected to your computer, you will also see some virtual MIDI ports,
depending on your operating system and how it's configured. One of the most useful virtual ports is the built-in synthesizer
output it allows you to generate sounds from MIDI messages without having to connect a physical synthesizer or sampler.

If you select a MIDI input keyboard for the midiin object, and the built-in synthesizer for output, you have a simple MIDI
thru application with very little patching. The midiin and midiout objects pass out and expect unformatted raw MIDI
messages if you route the output of the midiin object to a print object, you will see that you have a serial stream of
numbers that can be difficult to interpret. Max contains a number of objects that give us a little more control how we use
MIDI data inside out program by selecting which types of MIDI events (notes, continuous controllers, etc.) we want to work
with.

All about notes: the notein and noteout objects


The notein and noteout objects are an example of message-specific MIDI objects. They accept the input of a MIDI stream,
and ignore all message types other than note messages - those traditionally caused by playing keys on a MIDI keyboard or
pads on a drum trigger. As with the midiin and midiout objects, we can select the MIDI port by double-clicking on the
object.

The second patch shows a basic note display; we can select a MIDI port, then view the notes that are received on that port.
The notein object displays three pieces of information for each incoming note message: the note number (or pitch), the note
velocity and the MIDI channel it was transmitted on. Play a MIDI keyboard or other controller that creates MIDI note
messages, and see how the note information is displayed by the number boxes.
You will notice that there is no on or off display to differentiate keys being played (a "note-on") and keys being released (a
"note-off") rather, a note-off message is displayed as a note with a velocity of zero (0). This is a common MIDI convention,
and it is used by many Max objects as the preferred way of displaying a note-off message. We have also used a number box
with the Display Format attribute set to MIDI. This provides us with an easily-read cue as to the pitch of the note that is
being played.

The next patch is a simple example of the reverse process: generating note messages to be played by a MIDI device. The
noteout object expects pitch, velocity, and channel numbers to be received in its left, center, and right inlets, respectively.
The left inlet (pitch) is hot, while the others are cold. In this case, we use Maxs ability to decode a list of messages as the
input to all of the inlets of an object. Thus, the message box labeled 64 100 0 is treated like three separate messages to
each inlet: they are channel 0, velocity 100 and note 64. This will send a note-on message for pitch 64 (E3) at a
velocity of 100 to channel 0. The second message box is almost the same, but uses a velocity of 0 which is the equivalent
of a note-off message. Double-click on the noteout object, and select a valid MIDI output device. Then click on the first
message box. You should hear the device sound the note. It should sustain until you hit the second message box, which
will turn it off. This is a basic MIDI note event structure, and can be used as the basis for generating MIDI messages that
play music.
Controllers and port selection: ctlin and ctlout, and midiinfo
The right-most patch is a simple version of an application that remaps MIDI controller data: it changes any modulation
wheel control value (by convention, MIDI controller 1) into a pan control value (controller 10). In this case, the ctlin and
ctlout objects are used for receiving and sending MIDI continuous controller messages. These objects are message-specific
MIDI object dedicated to MIDI controller values which are often sent by MIDI fader boxes and knob/rotary controllers, as
well as more music-centric interfaces such as keyboard sustain pedals. As with the other objects, you can double-click them
to set a MIDI port for use.

The incoming values are used to set up the control system. The patch uses the incoming controller number (the middle outlet
of ctlin) to determine the routing of a graphical gate (gswitch2) object. When controller 1 is seen, the == object outputs a
1, which sets the the switch to allow the controller value (the left outlet) to go into the subsequent message box. This value
is then assembled into a valid message for ctlout, which will send the value (assigned to MIDI controller 10 on channel 0) to
the selected MIDI output.

There is a little extra programming attached to the ctlout object: a button is connected to a midiinfo object, which loads a
umenu object with some data when it receives a bang message. This data is fed into the ctlout object. What is this about?

Sometimes, you dont want the end user of your patch to have to double-click the MIDI objects to set a port, or you may
want to set the port on many objects simultaneously. The midiinfo object provides a lot of information on your current
MIDI setup, which you can use to set the port information on your MIDI objects. In this case, when the midiinfo object
receives a bang message in its left inlet, it produces the names of the available MIDI output ports currently defined on your
system. This is used to load the umenu object with your current MIDI setup. When you select an item from the menu, it is
sent to the ctlout object as an identifier of the port you want to use.
This is just one of the uses of the midiinfo object; we will see other uses in upcoming tutorials. If you want to query your
computer for information about available MIDI ports and available controllers, review the midiinfo help files and reference
pages.

Creating a basic MIDI monitor


In order to exercise the MIDI message tools, lets create a basic MIDI monitoring application. We can start by creating a
version of the midiinfo/umenu combination that will show available MIDI inputs. In order to see the inputs, we need to
send a bang message into the right inlet of the midiinfo object. You can do this with a button object, or use a loadbang
object so the menu will be loaded each time the patch is loaded.

In order to track both note and controller information, we can send the output of the umenu to both a notein and ctlin
object. This sets up the two objects to receive MIDI information from the same MIDI port. Now, connect number boxes to
each of the outlets of the notein and ctlin objects. We can probably have a single number box share the channel messages,
since we wont have notes and controllers being generated at the same time. Finally, changing the note number box to use a
Display Format of MIDI will allow us to easily see the key of the depressed note.

While this is a fairly simple MIDI monitor application, it is the sort of application that can help you debug a complex MIDI
setup. You can expand this patch by using other MIDI message-specific objects, such as pgmin (MIDI program changes) and
bendin (MIDI pitch bend messages), to see even more of the received MIDI data stream.

Conclusion
The basic contents of an incoming MIDI stream can be retrieved using the midiin object, and a MIDI stream can be sent
using the midiout object. However, in most cases, it is easier to deal with individual message types using their message-
specific objects. The notein/noteout and ctlin/ctlout objects provide an easy way to deal with messages without having to
decode the raw MIDI input or create raw MIDI output.

The midiinfo object, is a powerful tool for examining the current state of your MIDI setup. Using it to load a menu of
available MIDI ports can help make your patch easier to use and is also the best way to set a number of objects
simultaneously.

See Also
Name Description
midiin Output raw MIDI data
midiout Transmit raw MIDI data
notein Receive MIDI note messages
noteout
Transmit MIDI note messages
ctlin Output received MIDI control values
ctlout Transmit MIDI controller messages
midiinfo Fill a pop-up menu with MIDI device names
gswitch2 Send input to one of two outlets
Generating and managing note events
MIDI Tutorial 2: MIDI Note Management
Introduction
In this tutorial, we will look at several ways to deal with one of the more difficult issues in MIDI note generation and
manipulation: dealing with pairs of note-on and note-off messages. We will use makenote to generate properly formed pairs
of a specific duration, use stripnote and flush to control incoming pairings, and use the sustain object to handle situations
where a sustain pedal-like action is required.

When working with MIDI synthesizers and samplers, one of the most distracting situations is when a note-on message is
sent to a device, but no note-off message is sent. This results in stuck notes, where the note is sounded but never turned
off. This is never a good result, and may be seen as a bug by anyone that uses your patch.

In this tutorial, we will look at different ways of maintaining an appropriate pairing of note-on and note-off messages. By
using some of the Max objects that can help manage this situation, we can prevent the types of mistakes that come from
unpaired note messages.

Controlling note-off with makenote


One of the most popular uses of Max is to create generative music using a variety of Max objects. Obviously, this would
include the creation of note messages that are played by connected samplers or synthesizers. If you are creating a lot of note
messages, maintaining the proper pairing of note-on and note-off messages can require a lot of extra programming.

One of the objects included with Max is the makenote object, which will create a pitch/velocity combination of your
choosing, then will generate a matching note-off message after a duration you set. The leftmost patch shows the makenote
object in action you can select a pitch, velocity and duration using the supplied slider objects; the object will generate a
note-on message, followed automatically by a note-off (actually, a note-on with velocity of 0) after the selected duration. The
two arguments for makenote are the default velocity and duration values, but these are changed when new values are
received in the inlets. As with most Max objects, only the left inlet of makenote is hot; dragging the leftmost slider will cause
a ripple of MIDI events, wherease the middle and right slider objects only set up the parameters.
Double-click on the noteout object in the lower-right, and select a valid MIDI output destination. Then adjust the pitch,
velocity, and duration values. You should hear notes being generated, then turned off, based on the selected duration.
We've also sent the note events to a print object; if you look in the Max window, you can see how each note-on is followed
by corresponding note-off messages, and that the object will correctly queue this messages even with multiple notes
sounding at the same time. Using the makenote object is the simplest way to generate note playback within Max without
having to program the tracking and generation of note-off messages.

Controlling note-off with stripnote and flush


The second patch in our tutorial deals with eliminating the note-off messages received from a MIDI device and then
controlling them explicitly from a patcher. In many cases, we may want to prevent a keyboard (or other MIDI input device)
from turning off a note, preferring to generate the note-off programmatically. In the second patch, we route received MIDI
notes from the notein object through the stripnote object, which will eliminate all note-off messages that are coming from
our MIDI device. As a result, the remainder of the patch will only see note-on messages, and we will be responsible for
turning the notes off when necessary.

One of the most useful tools for maintaining note-on tracking is the flush object. It will create an internal table of note-on
messages that have not yet received a corresponding note-off; it can then generate note-off messages for all sustained notes
whenever a bang is received in its left inlet. In this case, we are stripping all of the note-off messages, so this table will
contain all of the notes that we play on our MIDI device. When we want to turn these notes off, we can hit the button object,
which will send a bang message to the flush object. This will generate note-off messages for all of the played notes, then
clear the internal table of notes in preparation for the next set of events. Double-click the notein object to select a valid
MIDI input device; using your MIDI keyboard source, generate some notes - they will continue to sound until you click the
button to flush them. We've also routed the notes to the Max window (using the print object) so we can see what's going
on.

Using the stripnote object to control the use of MIDI notes is useful when our playback engine needs to be sensitive to
controllers other than the keyboard. Combining stripnote with flush allows us to be certain that MIDI note-off messages
will be generated for any notes that were not specifically turned off.
Controlling note-off with sustain
The third patch features a similar function sustained notes are held until specifically released. However, this patch will
only perform this function when a toggle is turned on; in all other instances, the functionality is normal, and note-off
messages pass without change.

This functionality is very similar to a sustain pedal on a piano: whenever the sustain pedal is on, the notes will ring even if
we remove our fingers from the keys. When the pedal is released, the notes stop ringing, thereby giving us a secondary level
of control. The sustain object simulates this process: when it receives a non-zero value in its right inlet, it holds all note-off
messages until it receives a 0 message in that same inlet. In this way, you can simulate the action of a sustain pedal without
having to programmatically maintain the note-on/note-off pairings. It is often useful to combine the use of the sustain
object with MIDI controller 64 (the sustain pedal controller), so that pedal control messages from a keyboard will react
appropriately within your patch.

As with the previous example, set the notein on the right to your MIDI input device (if necessary, disengage your input
device from the middle notein). Play some notes normally, then check the toggle box - notes should no longer turn off.
When you uncheck the toggle, all your sounding notes should stop.

Conclusion
Most MIDI synthesizers and samplers demand note-on and note-off messages in pairs; failure to do so will result in stuck
notes. There are several Max objects that help maintain the note-on/note-off pairings, and allow you to control the
generation and playback of MIDI notes programmatically. The makenote object is perfect for generating MIDI notes when
you know the planned duration of the note. The stripnote/flush combination is better when you want to specifically control
note-off generation, but want a backup in maintaining notes that have not been sent a note-off. Finally, the sustain object
allows you to simulate the use of a sustain pedal on a standard keyboard, saving you from having to program functionality
for this specific MIDI control situation.

See Also
Name Description
makenote Generate a note-on/note-off pair
stripnote Filter out note-off messages
flush Output MIDI note-offs for held notes
sustain Hold note-off messages for release
Decoding and encoding MIDI streams
MIDI Tutorial 3: MIDI Parsing
Introduction
This tutorial dives into a few MIDI-based objects that provide extended functionality for MIDI programming. The midiparse
object can be used to examine the components of a raw MIDI stream, while midiformat is used as a one-stop shop for
creation of most commonly supported MIDI messages. We also use the xbendin object to see the extended values provided
by many MIDI controllers for the pitch bend value.

Because of the nature of these objects, this will be a show tutorial rather than a build tutorial. However, please take the
time to understand the data flow through these patches, since they are the basis for much of the handling of a complicated
MIDI setup.

When creating any significant MIDI-controlled patch, we may need access to all of the notes, controller changes, and other
messages generated by a MIDI device. Rather than using many individual objects (such as notein, ctlin, pgmin and others),
we can use the midiparse object to parse the incoming MIDI stream. We can also use the midiformat object to generate a
MIDI stream that can contain a wide variety of MIDI messages. Both of these objects are very useful for complicated MIDI
control patching.

We also take a look at the extended values provided for certain message types specifically, the extended (14-bit) values
provided by most MIDI keyboards for the pitchbend wheel. Since these messages can be produced very rapidly, we will also
use the speedlim object to slow down the display of the values, preventing overload of our patch during high-speed message
generation.

Viewing midiparse in action


In the patcher for this tutorial, we are using a midiin object to grab the raw MIDI input stream from a MIDI input device,
and using midiparse to split the data into the various supported message types. The outlets of midiparse issue different
types of messages depending on the type of MIDI input: notes, poly key pressure and control changes are lists, while the
program change, aftertouch and pitch bend outlets put out single integers. Weve routed these outputs to slider objects in
order to display the various messages as they are received. If you have a MIDI controller that can generate these messages,
select its MIDI port (by double-clicking on the midiin object) and play it you should see the slider objects respond to
incoming messages. Note that the MIDI channel is not attached to the individual messages; the MIDI channel is sent from a
shared outlet that will always display the channel of the most currently received message.

The midiparse object is used whenever you are creating a MIDI-driven patch that has to respond to a large number of
message types. Rather than using all of the different message-specific objects (notein etc.), you can use this single object to
track the various messages. MIDI sequences being played into Max from an external hardware or software sequencer, for
example, will contain much more than just notes; the midiparse object lets you see the full range of information present in
the sequence.

Viewing midiformat in action


A complementary object to midiparse is midiformat, which allows us to create many different message types and turn them
into a MIDI stream that is acceptable to the midiout object. The lower half of our test patch shows all of the messages that
can be created, and provides sliders that can be used to generate these messages. To test the result, double-click on the
midiout object, and select an appropriate MIDI output device. Then move the sliders connected to the midiformat object
you should hear the results (when they are audible) from your MIDI device.

Some care needs to be taken when creating messages for midiformat. As with any other note-based device, you should pair
MIDI note-on messages with MIDI note-off messages. You should also limit the number of controller messages that are sent
to any device, since too great a density of controller messages can potentially confound a MIDI synthesizer, depending on its
capabilities. Finally, you should make sure that the MIDI channel you are using is appropriate (and, in the case of
multitimbral synthesizers, the active channel) for the device that you are attempting to control.

Tracking extended MIDI controllers using xbendin


In most cases, the 7-bit values (0-128) sent and received from MIDI controllers are sufficient for dealing with synthesizer
and sampler control. However, in a few cases, 7-bit values are insufficient for nuanced information. The most common
example of this is the pitchbend control. When a synthesizer is set to bend +/- one octave, the individual steps of the
pitchbend control might correspond to coarse and unmusical pitch steps. The MIDI specification allows for pitchbend to
occupy 14-bit values, providing values from 0 to 16383. This allows use to have much finer pitch control, and offers a better
likelihood of achieving musical results.

We can track extended pitchbend information using the xbendin object, which takes raw MIDI input and outputs pitchbend
messages that include this extended range. Even if your MIDI controller does not send true 14-bit messages, they will be
parsed as if the full 14-bits were available. Unfortunately, even the most stable MIDI controller can produce an excessive
number of MIDI pitchbend messages when tracking the extended value the hardware is unable to stabilize on a single
value, and may produce a greater-than-acceptable number of very small changes. While this may not affect any connected
hardware, it can cause a Max patch to behave erratically, or at least make it difficult to properly debug a complex patch.

The solution for this is the speedlim object, which will take the output of any object (in this case, xbendin), and will limit
the output to only one message in any given timeframe. In the example patch, the argument 250 tells speedlim to output a
message at most every 250 milliseconds (one-quarter second). The object will discard all but the last message in that
timeframe, giving us a less dense set of messages to manage in our patch. When you send pitchbend information to the
example patch, you will see that the button and number box connected to xbendin update much more often than those out
of the speedlim; the number box connected to the output of speedlim will always updated within a quarter-second to show
the most recently passed value.

Conclusion
When creating a complicated MIDI-controlled patch, we will often want to use all of the available MIDI messages. Rather
than have a large number of message-specific objects, we can use the midiparse and midiformat messages to stream MIDI
data from and to the devices while having access to all the message types. Using midiparse and midiformat is at the heart
of any large and complex MIDI-based patching system.

Having access to extended control information can allow us to make more musically sensitive patches. Using xbendin to
receive the extended pitch bend information can help us create more stable-sounding synthesizers within Max. However,
since some of this information might be received too quickly, using speedlim to slow down the receipt of these messages
can help us control the amount of overhead built into our patches.

See Also
Name Description
midiparse Interpret raw MIDI data
midiformat Prepare data in the form of a MIDI message
xbendin Interpret extra precision MIDI pitch bend values
speedlim Limit the speed of message throughput
Playing back MIDI sequence data
MIDI Tutorial 4: MIDI Basic Sequencing
Introduction
This tutorial covers sequencing topics using the Max seq object. We will cover basic sequence setup, and the ability to start
and stop playback. We will also examine a few ways to control the playback speed of a loaded sequence.

MIDI event recording and playback (generally called sequencing) is an important task for many MIDI-based Max programs.
There are several objects within Max that can accomplish MIDI sequencing tasks, but the seq object provides the easiest
interface while still allowing for the recording and playback of notes, controllers and all other MIDI messages.

One of the things that makes MIDI sequencing so useful is that you can change playback speed with little effect on the output
sound; the MIDI recipient is responsible for sound creation, and merely responds to the data stream provided by the
sequencer. Thus, playback rate change is an important part of MIDI sequencing, and is covered in depth with this tutorial.

Basic sequencing using seq


Our tutorial patcher contains three regions containing patcher logic routed through a single seq object. The leftmost area
(labeled 1) shows the most basic of MIDI sequencing setups. The seq object is initialized with a MIDI sequence name as its
argument. This sequence is loaded when the patch is opened, and is available for playback. The left output of the seq object
is the playback output it sends raw MIDI data into a midiflush object, then to a midiout object.
The midiflush object is used to maintain the note-on/note-off pairings of a raw MIDI stream, and will send note-off
messages when it receives a bang. Using midiflush, we can stop all sounding notes even if the sequence is only half-way
through its playback. Clicking on the stop message at the top of the patch will not only stop the sequence, but will send a
bang to midiflush to stop all sounding notes on your synthesizer.
Double-click on the midiout object and select a valid MIDI output device for your system. Then click on either the button or
the start message to begin sequence playback from the start of the sequence; the MIDI sequence loaded into the seq object
will play back at its natural speed. When the sequence is done playing, a bang will be sent out the right outlet of the seq
object. We have this connected to a button object, giving us a visual indication of sequence completion.
Try each of the messages attached to the seq object, and stop it during playback to hear the results of the midiflush object.
Also notice that playback always starts at the beginning of the sequence.

Changing playback speed


The next area (labeled 2) contains a bit of programming that changes the playback speed of the sequence. It is based on the
argument to the start message: an integer appended to the start message will change the playback rate. A playback rate of
1024 represents normal speed; hence, 512 is half-speed, and 2048 is double-speed. While this may seem convoluted (in
comparison to using a floating-point "rate" from the start), it is easy to calculate the proper value for playback.

In this case, we use a floating-point number box for playback speed, and multiply it by 1024 to get the number expected by
seq object. The number is stored in an int object; then, hitting the Go! message box, we trigger a button that sends the
number through a start message, with the properly formatted message sent to seq. Remember that, since the button
object converts any message into a bang, the text in the Go! message is arbitrary.
To test this, change the floating-point number box to 0.5and hit Go!. Change it to 2.0 and hit Go! again. You will hear the
sequence play at the suggested speed. Using an argument to the start message is an easy way to control playback, but this
method can only be used to change playback speed at the start of playback. To change the rate during playback, you need to
work with the tick message.

Using tick messages for playback


The rightmost area (labeled 3) shows how to change the speed of the sequence during playback. Two messages are
responsible for this: a variation on the start message (with the argument of -1) and the tick message. The seq object has an
internal timer that is used by default for playback. However, when the start message has the -1 argument, the transport of
the seq object is disengaged from an internal clock and depends on incoming tick messages to advance the sequence.
In our example, we are using a tempo object to transform a bpm (beats per minute) value into the appropriate ticks. The
arguments to tempo set a default rate (in this case, 120 bpm), a default beat multiplier (1) and the number of pulses for
each whole note (96, the equivalent of 24 pulses per quarter note). If you click on the start -1 message and then turn on
the tempo object with the toggle box, you will hear the sequence play back at 120 bpm. Next, change the tempo to
something faster (say 200 bpm) with the number box connected to its second inlet; if you restart the sequence you will hear
it play much more quickly. Turn the tempo object's speed down (to 50 bpm) and you will hear very slow playback. You can
also change the tempo object while the sequence is playing, and the playback will change to match your selected speed.
There are many creative options when using the tick message for playback clocking. Using a line object to alter the tempo
object would allow you to ramp up playback speed for the duration of the sequence; alternatively, you could create an curve
that would cause the playback speed to wobble while it plays. You can also stop the tempo object (using the checkbox) to
temporarily pause playback when you start it again, playback continues from the point at which you stopped. Using your
own clocking provides much more flexibility than simply changing the arguments to the start message.

Conclusion
The seq object is a robust sequencing tool, allowing you to play back MIDI sequences at a variety of speeds. This is especially
true when you override the internal clock and use the tick message to alter playback in real time. The output of the seq
object should be routed through the midiflush object, so that stopping playback will also stop any currently sounding notes.
The seq object is perfect for playback of short loops, note/controller phrases or even complete sequences.

See Also
Name Description
seq Sequencer for recording and playing MIDI data
midiflush Send MIDI note-offs for hanging note-ons
tempo Output numbers at a metronomic tempo
Recording and manipulating MIDI sequences
MIDI Tutorial 5: MIDI Advanced Sequencing
Introduction
In this tutorial, we will expand on our use of the seq object by recording new MIDI data, loading existing files and writing
sequences to disk. We will also use the second outlet of the seq object to provide looped playback of the current sequence.
Working with existing sequences is useful, but being able to record new sequences within Max allows us to create and store
sequences and phrases for later use. This sequencing tutorial is focused on recording, the use of the file input/output
functions, and the ability to use the seq object output to loop playback.

Recording a sequence
Our tutorial has a number of regions with different patcher logic in each. The leftmost region (labeled Recording) shows
the basic setup for selecting MIDI input that we saw in earlier MIDI tutorials. The seq object expects a raw MIDI stream, so
our recording input comes directly from a midiin object.
Select a valid MIDI input device from the umenu so we can record MIDI data into our own sequence. In addition, double-
click the midiout object and select a valid MIDI output device. In addition to feeding the seq object, the midiin object is also
sending data to the midiout, so you should be able to test your connections by playing on your MIDI controller.
Clicking on the red record message will start the recording of MIDI data. Click on this message box, then play some MIDI
data in from a connected controller. Clicking the stop message will stop recording; we can then hit start to hear the playback
of the MIDI we just recorded. Since the seq object is recording the complete MIDI stream, we can also send continuous
controllers, pitchbend messages, program changes or any other MIDI data it will be recorded and played back just like note
messages. As in the last tutorial, we use the midiflush object in between seq and midiout to silence any remaining note-on
messages when we stop our sequence.

Loading and saving a sequence


Once weve recorded a sequence, we may want to save the results. This is where the file-handling messages come into play.
The top-right area (labeled File Handling) shows three messages that seq understands for saving and loading files; in this
case, the write message is our friend. Clicking on the write message will open a Save dialog that allows us to store the
sequence to disk. Click on the write message, and save your newly recorded sequence to disk.

Reading the file from disk can take two forms: we can explicitly choose a file to read, or open a dialog to select from any
MIDI file stored on disk. Explicit selection is done using a file name argument to the read message. Sending the read
message without an argument will provide an Open dialog for selecting any available MIDI file. Click on the read
seq_sc.midi message to load our test sequence file; to prove that we have changed the current sequence, play it using the
start message. Click on the no-argument read message and select your saved sequence. Clicking the start message should
play back our sequence as we performed it earlier.

Looping playback
In the previous tutorial, we saw that the right outlet of seq produces a bang message when a sequence is done with
playback. Using this information, we can perform a common sequencing task: looping playback of our sequence. The
bottom-right area (labeled Loop Playback) shows a gswitch2 (Graphical Gate) that will route the bang message back to
the start message whenever the toggle object is checked. This is a simple use of the right-hand output for sequencer
control; it could also be used for loading another sequence, starting a second seq object or even starting another process in
Max entirely.

Conclusion
Recording a raw MIDI stream is one of the strengths of the seq object; it can grab and store almost any type of MIDI
message. Using the read and write commands, we can save and then restore any recorded MIDI data, whether received from
a MIDI controller or generated from Max. We can also use the right outlet of seq to control playback parameters or even
start completely new Max processes. The seq object should be seen as a robust, useful tool for many sequencing tasks.

See Also
Name Description
seq Sequencer for recording and playing MIDI data
midiflush Send MIDI note-offs for hanging note-ons
Introduction to state management
pattr Tutorial 1: Patcher Storage
Introduction
Max has a wide variety of objects for storing and managing data. Objects such as table, funbuff, coll, and umenu all store
information that you can set manually or via a mechanism within a patch itself. The preset object, which also stores data, is
useful for capturing and recalling the states of user-interface objects within a patcher, giving you the ability to rapidly
restore settings to multiple parts of your patch in one step.

What is pattr?
Often a project in Max will require a more sophisticated state management system than the basic data structures objects
allow for. The pattr family of objects (pattr, pattrhub, autopattr, and pattrstorage) provides the functionality of the
preset object and adds a more extensive set of state management features:
We can maintain sets of data from objects throughout a Max patch hierarchy. For example, with pattr you can control
the state of objects inside of patcher and bpatcher objects all from the top level of the patch.
We can store any type of data used by any type of object (including data simply stored inside a pattr itself, without any
other objects involved).
We can use pattr objects to remotely set and query the state of objects controlled by the pattr system from anywhere
within the patch.
The pattr objects store groups of settings as XML files, allowing us to easily read and edit saved data outside of Max.
The pattr objects can recall the state of objects in a specific order, avoiding difficulties with, for example, the recalling
of a toggle object that starts a process before all the variables are in place for the process to function correctly.
Not only can we store the states of many objects under a single address, we can also interpolate between these states,
allowing for a seamless crossfade between multiple settings.
The pattr objects feature a high-level interface for viewing and managing the current state of controlled objects and the
states that have been saved.

In this tutorial, well look at some of the basic features of pattr and pattrhub, showing how the objects can be used to
communicate remotely with objects anywhere in a Max patch.

Object Binding
Take a look at the tutorial patcher. Turn on the metro object with the toggle object box labeled start. You should hear some
music if you double-click the noteout object and select a valid output synthesizer. The number box attached to the metro
object controls the speed of the generated pattern. Click on the colored message boxes to the right of the patch and note
that they change the value of that number box even though there are no patch cords or send, forward, or receive objects in
the patch.

Clicking in a colored message box changes the metro objects time value.
The pattr object to the right of the metro object is controlling the value in the number box above it. In the language of
patcher storage, we say that our pattr object is bound to the number box. When we send messages to that pattr object, it
will at all times refer to the data stored in the number box, allowing us to ask the pattr object what the number is currently
set to, as well as tell the pattr object to set the number to a specific value remotely.
Our pattr object has a name - speed - which is set by the objects argument and allows other pattr-family objects to
communicate with it. The pattrhub object at the bottom of the patch can receive messages and forward them to any pattr
objects in the patch. By sending the message speed 125 to the pattrhub, we are telling the object to find the pattr with the
name speed. If it finds the relevant pattr object, it will instruct the object to send the message 125 to whatever object it is
bound to (in this case, our number box).
Unlock the patch and click on the number box attached to the metro object. Select Name from the Object menu.

Our pattr object is bound to our number box because the bindto attribute of our pattr object is set to the name of our
number box (temponum). The act of naming Max objects allows us easier access to them via the pattr system. Note that
the pattrhub object controls our number box via the name of the pattr object to which it is bound (speed), not the name of
the number box itself (temponum).
Rename the number box to something else and close the Inspector. Try changing settings for the patch by clicking on the
message boxes again.

Note that if we rename our referred object, our pattr object can no longer bind to it. In order to rebind it, we need to tell
pattr to bind to our number box again.

Open the Inspector for the number box and name it back to temponum. Close the inspector and recreate the pattr object
binding to temponum (either delete the object and undo the deletion, or create a new pattr object). Verify that it is
receiving updates from the pattrhub object by clicking on the message boxes again.
Instead of recreating the pattr object, we could have sent our newly unbound pattr object a bindto message with the name
of the number box, setting the bindto attribute to a valid object.

More Ways Than One


Naming a Max object and explicitly binding a pattr to it with its bindto attribute is only one way to get a pattr to refer to an
object in our patch. It has the advantage of requiring no connecting patchcords between the two objects, allowing them to
communicate from spatially disparate parts of the patcher.

Open the subpatch notes by double-clicking the patcher object containing it. This subpatch contains eight pattr object-
bound number box objects that define the four pitches in our pattern generator, as well as the number of beats between
each trigger of the pitch. This is the part of the patch that allows us to construct a polyrhythmic pattern off of a single
counter object (driven by the metro object in the main patcher).

Click on the message boxes back in the main patcher with this window open and notice that the number box objects in the
subpatch update correctly when you click on the different patterns. Clicking on the message box updates the subpatch
values, too!

In addition to binding objects to pattr through explicit naming and the bindto attribute, pattr objects can control other Max
objects through patchcord connections.

The notes subpatch shows two possible ways to do this:

1. Using the pattr object itself to store the data


2. Automatically binding a pattr object to an object using the pattr objects middle outlet.

Internal Storage
If a pattr object is unbound, it will store any messages sent in its left inlet and recall them from its left outlet. Messages sent
to an unbound pattr object from a pattrhub object will echo out of the left outlet as well.
Unlock the notes subpatch and attach an slider object to the left outlet of one of the pattr objects named val_a, val_b, val_c,
or val_d. Recall the pattr objects states by clicking on the message boxes in the main patch. Scroll the number box
attached to the pattr object. The slider object should move as well.
The pattr objects controlling our pitches are not bound to any single object, and are maintaining the values of the number
box objects attached to them not by referring to the objects directly, but by receiving their values as messages. As a result,
the number box objects attached to these pattr objects can be deleted and replaced with other objects (or more than one
object). Because the pattr object outputs its values when changed (either directly or remotely) we can easily attach multiple
objects to the pattr object to set and display values stored in the object.
The use of the prepend object with set argument in pattr connections is to prevent the triggering of MIDI events when we
recall the pattr objects state. Unlike most Max objects, pattr objects can be connected to other objects that are directly
connected to them in turn without causing a stack overflow.

Automatic Binding
In the same subpatch, try to connect a slider object to the middle outlet of one of the pattr objects labeled mod_a, mod_b,
mod_c, or mod_d. The Max window should print an error message and the program should prevent you from making the
connection.

The middle outlet of pattr allows for the automatic binding of the pattr to a single object in the same patcher. The number
box objects controlling the % objects are communicating with their respective pattr objects just as if we had named them and
bound the pattr objects to them manually.
Look at the names for the number box objects by selecting Name from the Object menu.
The bindto (middle) outlet of pattr objects automatically gives the referring object a name if it doesnt have one already. The
name is based on the class of object attached, and multiple objects of the same class in a patch will be given incrementing
notation to uniquely identify them (e.g. number, number[1], number[2], etc.).

Back in the main patch, open the durs subpatch of the main patch by double-clicking the patcher object containing it.
Observe that the two pattr objects in there (min and max) have been bound to two number box objects through their
middle outlets.

One Hub to Rule Them All


Close the subpatchers and go back to the main tutorial patch. Look at the message boxes again and notice the notation used
in them to refer to pattr objects inside subpatchers.
Because most of our pattr objects are inside subpatchers, the pattrhub object refers to them using a colon-separated
notation that takes the form

subpatcher:pattr_name

We can communicate to pattr objects in nested subpatchers by the same convention, e.g. a pattr named yikes in a patcher
called stuff in a bpatcher called things would be accessed through pattrhub with the name:

things:stuff:yikes

Using the umenu object in the main tutorial patch, select one of the pattr objects in the patch.
In addition to setting the state of pattr objects through pattrhub, we can also query the state of pattr objects, which will
then tell pattrhub their internal state or the value of the object to which theyre bound. We do this by sending pattrhub the
message get followed by the name of the pattr object we want to query, with no space in the message, e.g. getspeed will poll
the state of the pattr named speed.
The number box to the right of the umenu reflects the current value of the selected pattr, output by the second outlet of
pattrhub as a message beginning with the name of the queried pattr.

Change the value of the selected pattr by changing the number box next to the umenu. Check to see that the value changed
by looking at the number box controlled by that pattr. Select some other pattr objects and change their values, familiarizing
yourself with how the system allows you to query and set the states of objects anywhere in the patch.

Conclusion
The pattr objects provide a powerful way to manage data from multiple objects in a Max patch. The pattr object can
maintain its own internal information (sent and returned through its leftmost inlet and outlet), or it can bind to a Max user
interface object either by naming that object and using the pattr objects bindto attribute, or by using the middle outlet of
the pattr object to automatically name and bind to an object. Each pattr object can only bind to one object at a time. The
pattrhub object allows you to control the state of all pattr objects within a patch, including those within subpatchers, which
can be accessed through a hierarchical notation system of successive patcher names separated by colons (:) followed by the
name of the appropriate pattr object. By sending a get message (followed by the name of a pattr with no intervening space)
you can query the state of any pattr object within a patch from a pattrhub.

See Also
Name Description
pattr Provide an alias with a named data wrapper
pattrhub Access all pattr objects in a patcher
patcher Create a subpatch within a patch
preset Store and recall settings
Advanced patcher storage
pattr Tutorial 2: Automatic Bindings and Storage
Introduction
The Max pattr object can be used to help you manage data, either by binding to an object and referencing its data or by
storing the data itself. The pattrhub object allows you to remotely query and set the data stored in pattr objects throughout
a patcher hierarchy. In this tutorial, well look at two powerful extensions to the pattr family: autopattr, which simplifies
the binding of large groups of objects to the pattr system, and pattrstorage, which provides an extensive system for storing
and recalling states of data stored in multiple pattr objects.

Automatic Binding
Take a look at the tutorial patcher. Start the patch by clicking the toggle box attached to the metro object in the upper-left
corner of the patch. The patch creates an algorithmic drawing based on the parameters stored in the rslider object and
number box objects attached to the patcher named drawing. The message box that sends a bang to the receive object
named reset allows you to clear the lcd display and reset the counter objects in the drawing subpatch.
The object called autopattr in the lower-right corner has a number of message box objects connected to it that contain
different example settings for the drawing controls.

The autopattr object has much of the same functionality as pattrhub, allowing you to send and query values from objects
exposed to the pattr system within a patch.
Unlock the patch and select one of the drawing interface controls other than the toggle object (i.e. the rslider or number
box objects at the top). Under the Object menu, select Name.

Note that our four control objects in the patch have names (range, angle, offset, and desynch). If you create a group of
user-interface objects and give them names, an autopattr object will automatically expose those objects into the pattr
system, exactly as if they had pattr objects all bound to them individually. In this sense, autopattr also functions as a set of
pattr objects, allowing you to include multiple objects for patcher storage with one object.

The default behavior of the autopattr object is to expose only named user interface objects in a patcher when the object is
created. The autoname attribute to autopattr, when set to 1, will automatically name all user interface objects in the
patcher and expose them to the pattr system. Like the Max preset object, the autopattr object will exclude any objects
connected to its second inlet or, if objects are connected to its left inlet, allow you to only specify a few objects explicitly for
naming and binding into the pattr system.
Because the autopattr object combines many of the features of the pattr and pattrhub objects, it allows you to rapidly
include large numbers of Max objects with a single object, while allowing you to query and set their data through the same
object.

Storing States
Click on the message box labeled clientwindow attached to the pattrstorage object. The window that appears gives you a
tabulated list of all the pattr objects exposed in the patch, as well as some information about them. Change the settings in
some of the control objects for the drawing machine and watch the window update to reflect the new settings.

The pattrstorage object provides a number of features for high-level parameter management. The client window shows the
names of all the objects exposed to pattr in the patch (including those controlled by pattr objects or autopattr objects). It
shows their current values in the last column. The middle two columns show the recall priority and interpolation mode for
the objects, which can be changed to fine-tune the order in which the objects are recalled to a saved state, and how objects
respond to an in-between state (see below).

Click on the message box labeled storagewindow attached to the pattrstorage. A window with a list of the control objects
should appear. Create a setting you like with the four objects that control the drawing machine. Once you have a setting
youre happy with, click the button object attached to the int object above the pattrstorage. This will send the message
store 1 to pattrstorage.
Sending a store message, followed by an integer value, tells pattrstorage to capture the current state of all exposed objects
and save them as a preset (or state) in a numbered slot inside the object. The slot will then receive a column in the storage
window, showing us the number of the slot as a column header, with all the appropriate values tabulated below it. State 0 is
a special slot that allows you to save a state temporarily without having it save in a file (see below).
Now that youve saved a preset, change one of the pattr-exposed objects. Watch how the storage window responds. When
you make a change to an object that deviates from the most recently saved or recalled preset slot, the value for the
appropriate object becomes italicized in the storage window.

Create some more preset states by making changes to the control objects, then storing their settings in pattrstorage by
incrementing the number box attached to the int object and clicking the button. Note that if you re-use a slot number (e.g.
you save a state under slot 2, then save again) the old settings are overwritten. Also note that the most current state (stored
or recalled) is shown with a colored highlight, while non-current states appear unhighlighted.

Click on the number box labeled recall a preset. Set it to one of the values youve stored. The user interface objects should
recall to their saved values, and the slot column representing that state in the storage window should go to boldface.

Sending an integer to pattrstorage will recall the slot corresponding to that integer. Attempting to recall a slot that has
never been saved is harmless, and pattrstorage will ignore you.

Interpolation
Click on the floating-point number box labeled interpolate between presets. Type in a value between two adjacent slots
youve saved (e.g. if youve saved a state under 1 and a state under 2, type 1.5). The pattr-exposed objects will go to an
interpolated value between those two states. Drag with the mouse in the number box so that you effect a smooth transition
from one state to another. The controlled objects will smoothly interpolate as well.

Floating-point values sent to pattrstorage will interpolate values between saved states. Non-adjacent states can be
interpolated as well, using the message fade a b n, where a and b are the slot numbers and n is a value from 0.0 (100% a)
to 1.0 (100% b). Note that interpolated values will italicize both of the participating slot in the storage window (the highlight
color will fade from the a to the b slot, as well).

Saving and Loading Files


After youve saved a couple of states into preset slots, click on the message box labeled write attached to the pattrstorage
object. A file save dialog will appear, asking you to save a file with the suffix .html. Save the file somewhere and open it in
any application that can read text files (Max, for example). Look over the file.

The pattrstorage object reads and writes collections of preset states as XML (extended markup language) files, a format
which uses nested tags as identifiers for different types of data in a file.

An example XML file from our tutorial patch could look something like this:

<.html version="1.0" encoding="iso-8859-1" standalone="yes"?>


<pattrstorage name = "u518000001">
<slot number = "1">
<pattr name = "angle" value = 60. />
<pattr name = desynch value = 7 />
<pattr name = offset value = 0. />
<pattr name = range value = 50 100" />
</slot>
<slot number = 2>
<pattr name = angle value = 33.5 />
<pattr name = desynch value = 39 />
<pattr name = offset value = 8.8 />
<pattr name = range value = 50 147" />
</slot>
</pattrstorage>
The first relevant tag that encompasses all our data defines the information as belonging the a pattrstorage object. The
<pattrstorage> tag also tells us the name of the pattrstorage argument, which is randomly generated unless we set it
explicitly with an argument to the object.

Between the <pattrstorage> tags, we have <slot> tags defining the saved states. Note that slot 0 is not saved in the file.
Within each <slot>, we have <pattr> tags that list the exposed objects by name and list their preset value for that state.
Make a change to the numerical data in one of the slots and save the XML file. Be careful to preserve the quotation marks
around the values. Read it back into the patch by clicking the read message box and selecting the file. The storage window
will update to the new preset value, which you can then recall.
Because XML is a straightforward, human-readable format, its quite simple to edit preset files saved using pattrstorage.
We could even use a piece of software (e.g. Max) to automatically generate preset files for our patches once theyve been set
up to use pattrstorage!

Conclusion
The autopattr object functions as a hybrid of the pattr and pattrhub objects, allowing you to automatically expose multiple
user interface objects to the pattr system in one easy step. The object allows you to automatically name objects for inclusion
(through the autoname attribute), as well as explicitly include or exclude objects through the first two outlets, respectively.
The pattrstorage object allows you to view the current settings of pattr-exposed objects, as well as save states of settings
into numerical slots (through the store message) and recall them (by sending an integer to the object). Furthermore, you can
interpolate between preset slots, as well as save and recall your saved states in an easy-to-read XML format.

See Also
Name Description
autopattr Expose multiple objects to the pattr system
pattrstorage Save and recall pattr presets
MSP Tutorials - Table of Contents
Topics
Introduction
How Digital Audio Works
How MSP Works - Max Patches and the MSP Signal Network
Audio I/O - Audio input and output with MSP

Tutorials
MSP Tutorial 1 - Test Tone
MSP Tutorial 2 - Adjustable Oscillator
MSP Tutorial 3 - Wavetable Oscillator
MSP Tutorial 4 - Routing Signals
MSP Tutorial 5 - Turning Signals On and Off
MSP Tutorial 6 - A Review of Fundamentals
MSP Tutorial 7 - Additive Synthesis
MSP Tutorial 8 - Tremolo and Ring Modulation
MSP Tutorial 9 - Amplitude Modulation
MSP Tutorial 10 - Vibrato and FM
MSP Tutorial 11 - Frequency Modulation
MSP Tutorial 12 - Waveshaping
MSP Tutorial 13 - Recording and Playback
MSP Tutorial 14 - Playback with Loops
MSP Tutorial 15 - Variable-length Wavetable
MSP Tutorial 16 - Record and Play Audio Files
MSP Tutorial 17 - Sampling Review
MSP Tutorial 18 - Mapping MIDI to MSP
MSP Tutorial 19 - MIDI Synthesizer Control
MSP Tutorial 20 - MIDI Sampler Control
MSP Tutorial 21 - Using the poly~ Object
MSP Tutorial 22 - MIDI Panning
MSP Tutorial 23 - Viewing Signal Data
MSP Tutorial 24 - Oscilloscope
MSP Tutorial 25 - Using the FFT
MSP Tutorial 26 - Frequency Domain Signal Processing with pfft~
MSP Tutorial 27 - Delay Lines
MSP Tutorial 28 - Delay Lines with Feedback
MSP Tutorial 29 - Flanging
MSP Tutorial 30 - Chorus
MSP Tutorial 31 - Comb Filter
Compression Tutorials
MSP Compression Introduction - What is Compression?
MSP Compression Tutorial 1 - Peak Limiting
MSP Compression Tutorial 2 - Basic Compression
MSP Compression Tutorial 3 - Tweaking Compression
MSP Compression Tutorial 4 - Compression on Real Instruments
MSP Compression Tutorial 5 - Multiband Compression 1
MSP Compression Tutorial 6 - Multiband Compression 2
MSP Compression Tutorial 7 - Keying
MSP Compression Tutorial 8 - Microsounds
MSP Compression Tutorial 9 - Ducking
MSP Compression Tutorial 10 - Controlling Feedback
Introduction
Signal processing in Max
MSP gives you over 170 Max objects with which to build your own synthesizers, samplers, and effects processors as software
instruments that perform audio signal processing.

A filter and delay effect processor in MSP

As you know, Max enables you to design your own programs for controlling MIDI synthesizers, samplers, and effects
processors.

MIDI control with Max

With the addition of the MSP objects, you can also create your own digital audio device designs your own computer music
instruments -- and incorporate them directly into your Max programs. You can specify exactly how you want your
instruments to respond to MIDI control, and you can implement the entire system in a Max patch.

MIDI control of a parameter of an audio process

MSP objects are connected together by patch cords in the same way as Max objects. These connected MSP objects form a
signal network which describes a scheme for the production and modification of digital audio signals. (This signal network is
roughly comparable to the instrument definition familiar to users of Music N sound synthesis languages such as Csound.)
The audio signals are played through the audio output jack of your computer, or through an installed sound card, using
CoreAudio on the Macintosh, MME or DirectSound on Windows, or ASIO on either platform.
Signal network for an FM instrument

How To Use This Manual


The MSP Documentation contains the following sections:

Digital Audio explains how computers represent sound. Reading this chapter may be helpful if MSP is your first exposure to
digital manipulation of audio. If you already have experience in this area, you can probably skip this chapter.

How MSP Works provides an overview of the ideas behind MSP and how the software is integrated into the Max
environment. Almost everyone will want to read this brief chapter.

Audio Input and Output describes MSP support for Core Audio on Macintosh systems, support for DirectSound on Windows
systems, and audio interface cards. It explains how to use the Audio Status window to monitor and tweak MSP performance.

The MSP Tutorials are over 30 step-by-step lessons in the basics of using MSP to create digital audio applications. Each
chapter is accompanied by a patch found in the MSP Tutorial folder. If you're just getting set up with MSP, you should at
least check out the first tutorial, which covers setting up MSP to make sound come out of your computer.

The MSP Object Reference section describes the workings of each of the MSP objects. It's organized in alphabetical order.

Reading the manual online


The table of contents of the MSP documentation is bookmarked, so you can view the bookmarks and jump to any topic listed
by clicking on its names. To view the bookmarks, choose Bookmarks from the Windows menu. Click on the triangle next to
each section to expand it.

Instead of using the Index at the end of the manual, it might be easier to use Acrobat Reader's Find command. Choose Find
from the Tools menu, then type in a word you're looking for. Find will highlight the first instance of the word, and Find
Again takes you to subsequent instances. We'd like to take this opportunity to discourage you from printing out the manual
unless you find it absolutely necessary.

Other Resources for MSP Users


The help files found in the max- help folder provide interactive examples of the use of each MSP object.

The Max Examples folder contains a number of interesting and amusing demonstrations of what can be done with MSP.

The Cycling '74 web site provides the latest updates to our software as well as an extensive list of frequently asked questions
and other support information.

Cycling '74 runs an on-line Max discussion where you can ask questions about programming, exchange ideas, and find out
about new objects and examples other users are sharing. For information on joining the discussion, as well as a guide to
third-party Max resources, visit http://www.cycling74.com/community
Finally, if you're having trouble with the operation of MSP, send e-mail to support@cycling74.com, and we'll try to help you.
We'd like to encourage you to submit questions of a more conceptual nature (how do I...?) to the Max mailing list, so that
the entire community can provide input and benefit from the discussion.
How Digital Audio Works

A thorough explanation of how digital audio works is well beyond the scope of this manual. What follows is a very brief
explanation that will give you the minimum understanding necessary to use MSP successfully.

For a more complete explanation of how digital audio works, we recommend The Computer Music Tutorial by Curtis Roads,
published in 1996 by the MIT Press. It also includes an extensive bibliography on the subject.

Sound
Simple harmonic motion
The sounds we hear are fluctuations in air pressure -- tiny variations from normal atmospheric pressure -- caused by
vibrating objects. (Well, technically it could be water pressure if you're listening underwater, but please keep your computer
out of the swimming pool.)

As an object moves, it displaces air molecules next to it, which in turn displace air molecules next to them, and so on,
resulting in a momentary high pressure front that travels away from the moving object (toward your ears). So, if we cause
an object to vibrate -- we strike a tuning fork, for example -- and then measure the air pressure at some nearby point with a
microphone, the microphone will detect a slight rise in air pressure as the high pressure front moves by. Since the tine of
the tuning fork is fairly rigid and is fixed at one end, there is a restoring force pulling it back to its normal position, and
because this restoring force gives it momentum it overshoots its normal position, moves to the opposite extreme position,
and continues vibrating back and forth in this manner until it eventually loses momentum and comes to rest in its normal
position. As a result, our microphone detects a rise in pressure, followed by a drop in pressure, followed by a rise in pressure,
and so on, corresponding to the back and forth vibrations of the tine of the tuning fork.

If we were to draw a graph of the change in air pressure detected by the microphone over time, we would see a sinusoidal
shape (a sine wave) rising and falling, corresponding to the back and forth vibrations of the tuning fork.

Sinusoidal change in air pressure caused by a simple vibration back and forth

This continuous rise and fall in pressure creates a wave of sound. The amount of change in air pressure, with respect to
normal atmospheric pressure, is called the wave's amplitude (literally, its bigness). We most commonly use the term
amplitude to refer to the peak amplitude, the greatest change in pressure achieved by the wave.

This type of simple back and forth motion (seen also in the swing of a pendulum) is called simple harmonic motion. It's
considered the simplest form of vibration because the object completes one full back-and-forth cycle at a constant rate. Even
though its velocity changes when it slows down to change direction and then gains speed in the other direction -- as shown
by the curve of the sine wave -- its average velocity from one cycle to the next is the same. Each complete vibratory cycle
therefore occurs in an equal interval of time (in a given period of time), so the wave is said to be periodic. The number of
cycles that occur in one second is referred to as the frequency of the vibration. For example, if the tine of the tuning fork goes
back and forth 440 times per second, its frequency is 440 cycles per second, and its period is 1/ 440 second per cycle.

In order for us to hear such fluctuations of pressure:

The fluctuations must be substantial enough to affect our tympanic membrane (eardrum), yet not so substantial as to hurt
us. In practice, the intensity of the changes in air pressure must be greater than about 10 -9 times atmospheric pressure, but
not greater than about 10 -3 times atmospheric pressure. You'll never actually need that information, but there it is. It means
that the softest sound we can hear has about one millionth the intensity of the loudest sound we can bear. That's quite a
wide range of possibilities.

The fluctuations must repeat at a regular rate fast enough for us to perceive them as a sound (rather than as individual
events), yet not so fast that it exceeds our ability to hear it. Textbooks usually present this range of audible frequencies as 20
to 20,000 cycles per second (cps, also known as hertz, abbreviated Hz). Your own mileage may vary. If you are approaching
middle age or have listened to too much loud music, you may top out at about 17,000 Hz or even lower.

Complex tones
An object that vibrates in simple harmonic motion is said to have a resonant mode of vibration a frequency at which it will
naturally tend to vibrate when set in motion. However, most real- world objects have several resonant modes of vibration,
and thus vibrate at many frequencies at once. Any sound that contains more than a single frequency (that is, any sound that
is not a simple sine wave) is called a complex tone. Let's take a stretched guitar string as an example.

A guitar string has a uniform mass across its entire length, has a known length since it is fixed at both ends (at the nut and
at the bridge), and has a given tension depending on how tightly it is tuned with the tuning peg. Because the string is fixed
at both ends, it must always be stationary at those points, so it naturally vibrates most widely at its center.

A plucked string vibrating in its fundamental resonant mode

The frequency at which it vibrates depends on its mass, its tension, and its length. These traits stay fairly constant over the
course of a note, so it has one fundamental frequency at which it vibrates.

However, other modes of vibration are still possible.

Some other resonant modes of a stretched string

The possible modes of vibration are constrained by the fact that the string must remain stationary at each end. This limits its
modes of resonance to integer divisions of its length.

This mode of resonance would be impossible because the string is fixed at each end

Because the tension and mass are set, integer divisions of the string's length result in integer multiples of the fundamental
frequency.
Each resonant mode results in a different frequency

In fact, a plucked string will vibrate in all of these possible resonant modes simultaneously, creating energy at all of the
corresponding frequencies. Of course, each mode of vibration (and thus each frequency) will have a different amplitude. (In
the example of the guitar string, the longer segments of string have more freedom to vibrate.) The resulting tone will be the
sum of all of these frequencies, each with its own amplitude.

As the string's vibrations die away due to the damping force of the fixture at each end, each frequency may die away at a
different rate. In fact, in many sounds the amplitudes of the different component frequencies may vary quite separately and
differently from each other. This variety seems to be one of the fundamental factors in our perception of sounds as having
different tone color (i.e., timbre), and the timbre of even a single note may change drastically over the course of the note.

Harmonic tones
The combination of frequencies -- and their amplitudes -- that are present in a sound is called its spectrum (just as different
frequencies and intensities of light constitute a color spectrum). Each individual frequency that goes into the makeup of a
complex tone is called a partial. (It's one part of the whole tone.)

When the partials (component frequencies) in a complex tone are all integer multiples of the same fundamental frequency,
as in our example of a guitar string, the sound is said to have a harmonic spectrum. Each component of a harmonic
spectrum is called a harmonic partial, or simply a harmonic. The sum of all those harmonically related frequencies still
results in a periodic wave having the fundamental frequency. The integer multiple frequencies thus fuse harmoniously into
a single tone.

The sum of harmonically related frequencies still repeats at the fundamental frequency

This fusion is supported by the famous mathematical theorem of Jean-Baptiste Joseph Fourier, which states that any
periodic wave, no matter how complex, can be demonstrated to be the sum of different harmonically related frequencies
(sinusoidal waves), each having its own amplitude and phase. (Phase is an offset in time by some fraction of a cycle.)

Harmonically related frequencies outline a particular set of related pitches in our musical perception.
Harmonic partials of a fundamental frequency , where = 65.4 Hz = the pitch low C

Each time the fundamental frequency is multiplied by a power of 2 -- 2, 4, 8, 16, etc. -- the perceived musical pitch increases
by one octave. All cultures seem to share the perception that there is a certain sameness of pitch class between such octave-
related frequencies. The other integer multiples of the fundamental yield new musical pitches. Whenever you're hearing a
harmonic complex tone, you're actually hearing a chord! As we've seen, though, the combined result repeats at the
fundamental frequency, so we tend to fuse these frequencies together such that we perceive a single pitch.

Inharmonic tones and noise


Some objects -- such as a bell, for instance -- vibrate in even more complex ways, with many different modes of vibrations
which may not produce a harmonically related set of partials. If the frequencies present in a tone are not integer multiples of
a single fundamental frequency, the wave does not repeat periodically. Therefore, an inharmonic set of partials does not fuse
together so easily in our perception. We may be able to pick out the individual partials more readily, and -- especially when
the partials are many and are completely inharmonic -- we may not perceive the tone as having a single discernible
fundamental pitch.

When a tone is so complex that it contains very many different frequencies with no apparent mathematical relationship, we
perceive the sound as noise. A sound with many completely random frequencies and amplitudes -- essentially all frequencies
present in equal proportion -- is the static-like sound known as white noise (analogous to white light which contains all
frequencies of light).

So, it may be useful to think of sounds as existing on a continuum from total purity and predictability (a sine wave) to total
randomness (white noise). Most sounds are between these two extremes. An harmonic tone -- a trumpet or a guitar note, for
example -- is on the purer end of the continuum, while a cymbal crash is closer to the noisy end of the continuum. Timpani
and bells may be just sufficiently suggestive of a harmonic spectrum that we can identify a fundamental pitch, yet they
contain other inharmonic partials. Other drums produce more of a band-limited noise -- randomly related frequencies, but
restricted within a certain frequency range -- giving a sense of pitch range, or non-specific pitch, rather than an identifiable
fundamental. It is important to keep this continuum in mind when synthesizing sounds.

Amplitude envelope
Another important factor in the nearly infinite variety of sounds is the change in over-all amplitude of a sound over the
course of its duration. The shape of this macroscopic over-all change in amplitude is termed the amplitude envelope. The
initial portion of the sound, as the amplitude envelope increases from silence to audibility, rising to its peak amplitude, is
known as the attack of the sound. The envelope, and especially the attack, of a sound are important factors in our ability to
distinguish, recognize, and compare sounds. We have very little knowledge of how to read a graphic representation of a
sound wave and hear the sound in our head the way a good sight reader can do with musical notation.

However, the amplitude envelope can at least tell us about the general evolution of the loudness of the sound over time.
The amplitude envelope is the evolution of a sound's amplitude over time

Amplitude and loudness


The relationship between the objectively measured amplitude of a sound and our subjective impression of its loudness is very
complicated and depends on many factors. Without trying to explain all of those factors, we can at least point out that our
sense of the relative loudness of two sounds is related to the ratio of their intensities, rather than the mathematical
difference in their intensities. For example, on an arbitrary scale of measurement, the relationship between a sound of
amplitude 1 and a sound of amplitude 0.5 is the same to us as the relationship between a sound of amplitude 0.25 and a
sound of amplitude 0.125. The subtractive difference between amplitudes is 0.5 in the first case and 0.125 in the second case,
but what concerns us perceptually is the ratio, which is 2:1 in both cases.

Does a sound with twice as great an amplitude sound twice as loud to us? In general, the answer is no. First of all, our
subjective sense of loudness is not directly proportional to amplitude. Experiments find that for most listeners, the
(extremely subjective) sensation of a sound being twice as loud requires a much greater than twofold increase in amplitude.
Furthermore, our sense of loudness varies considerably depending on the frequency of the sounds being considered. We're
much more sensitive to frequencies in the range from about 300 Hz to 7,000 Hz than we are to frequencies outside that
range. (This might possibly be due evolutionarily to the importance of hearing speech and many other important sounds
which lie mostly in that frequency range.)

Nevertheless, there is a correlation -- even if not perfectly linear -- between amplitude and loudness, so it's certainly
informative to know the relative amplitude of two sounds. As mentioned earlier, the softest sound we can hear has about one
millionth the amplitude of the loudest sound we can bear. Rather than discuss amplitude using such a wide range of
numbers from 0 to 1,000,000, it is more common to compare amplitudes on a logarithmic scale.

The ratio between two amplitudes is commonly discussed in terms of decibels (abbreviated dB). A level expressed in terms of
decibels is a statement of a ratio relationship between two values -- not an absolute measurement. If we consider one
amplitude as a reference which we call A0, then the relative amplitude of another sound in decibels can be calculated with
the equation:

level in decibels = 20 log10 (A/A 0)

If we consider the maximum possible amplitude as a reference with a numerical value of 1, then a sound with amplitude 0.5
has 1/ 2 the amplitude (equal to 10 -0.3 ) so its level is

20 log10 (0.5/1) _ 20 (-0.3) = -6 dB

Each halving of amplitude is a difference of about -6 dB; each doubling of amplitude is an increase of about 6 dB. So, if one
amplitude is 48 dB greater than another, one can estimate that it's about 2 8 (256) times as great.

Summary
A theoretical understanding of sine waves, harmonic tones, inharmonic complex tones, and noise, as discussed here, is useful
to understanding the nature of sound. However, most sounds are actually complicated combinations of these theoretical
descriptions, changing from one instant to another. For example, a bowed string might include noise from the bow scraping
against the string, variations in amplitude due to variations in bow pressure and speed, changes in the prominence of
different frequencies due to bow position, changes in amplitude and in the fundamental frequency (and all its harmonics)
due to vibrato movements in the left hand, etc. A drum note may be noisy but might evolve so as to have emphases in certain
regions of its spectrum that imply a harmonic tone, thus giving an impression of fundamental pitch. Examination of existing
sounds, and experimentation in synthesizing new sounds, can give insight into how sounds are composed. The computer
provides that opportunity.

Digital representation of sound


Sampling and quantizing a sound wave
To understand how a computer represents sound, consider how a film represents motion. A movie is made by taking still
photos in rapid sequence at a constant rate, usually twenty-four frames per second. When the photos are displayed in
sequence at that same rate, it fools us into thinking we are seeing continuous motion, even though we are actually seeing
twenty-four discrete images per second. Digital recording of sound works on the same principle. We take many discrete
samples of the sound wave's instantaneous amplitude, store that information, then later reproduce those amplitudes at the
same rate to create the illusion of a continuous wave.

The job of a microphone is to transduce (convert one form of energy into another) the change in air pressure into an
analogous change in electrical voltage. This continuously changing voltage can then be sampled periodically by a process
known as sample and hold. At regularly spaced moments in time, the voltage at that instant is sampled and held constant
until the next sample is taken. This reduces the total amount of information to a certain number of discrete voltages.

Time-varying voltage sampled periodically

A device known as an analog-to-digital converter (ADC) receives the discrete voltages from the sample and hold device, and
ascribes a numerical value to each amplitude. This process of converting voltages to numbers is known as quantization.
Those numbers are expressed in the computer as a string of binary digits (1 or 0). The resulting binary numbers are stored
in memory usually on a digital audio tape, a hard disk, or a laser disc. To play the sound back, we read the numbers from
memory, and deliver those numbers to a digital-to-analog converter (DAC) at the same rate at which they were recorded.
The DAC converts each number to a voltage, and communicates those voltages to an amplifier to increase the amplitude of
the voltage.

In order for a computer to represent sound accurately, many samples must be taken per second many more than are
necessary for filming a visual image. In fact, we need to take more than twice as many samples as the highest frequency we
wish to record. (For an explanation of why this is so, see Limitations of Digital Audio on the next page.) If we want to record
frequencies as high as 20,000 Hz, we need to sample the sound at least 40,000 times per second. The standard for compact
disc recordings (and for CD-quality computer audio) is to take 44,100 samples per second for each channel of audio. The
number of samples taken per second is known as the sampling rate.

This means the computer can only accurately represent frequencies up to half the sampling rate. Any frequencies in the
sound that exceed half the sampling rate must be filtered out before the sampling process takes place. This is accomplished
by sending the electrical signal through a low-pass filter which removes any frequencies above a certain threshold. Also,
when the digital signal (the stream of binary digits representing the quantized samples) is sent to the DAC to be re-converted
into a continuous electrical signal, the sound coming out of the DAC will contain spurious high frequencies that were created
by the sample and hold process itself. (These are due to the sharp edges created by the discrete samples, as seen in the
above example.) Therefore, we need to send the output signal through a low-pass filter, as well.

The digital recording and playback process, then, is a chain of operations, as represented in the following diagram.
Digital recording and playback process

Limitations of digital audio


Sampling rate and Nyquist rate
We've noted that it's necessary to take at least twice as many samples as the highest frequency we wish to record. This was
proven by Harold Nyquist, and is known as the Nyquist theorem. Stated another way, the computer can only accurately
represent frequencies up to half the sampling rate. One half the sampling rate is often referred to as the Nyquist frequency
or the Nyquist rate.

If we take, for example, 16,000 samples of an audio signal per second, we can only capture frequencies up to 8,000 Hz. Any
frequencies higher than the Nyquist rate are perceptually folded back down into the range below the Nyquist frequency. So,
if the sound we were trying to sample contained energy at 9,000 Hz, the sampling process would misrepresent that
frequency as 7,000 Hz -- a frequency that might not have been present at all in the original sound. This effect is known as
foldover or aliasing. The main problem with aliasing is that it can add frequencies to the digitized sound that were not
present in the original sound, and unless we know the exact spectrum of the original sound there is no way to know which
frequencies truly belong in the digitized sound and which are the result of aliasing. That's why it's essential to use the low-
pass filter before the sample and hold process, to remove any frequencies above the Nyquist frequency.

To understand why this aliasing phenomenon occurs, think back to the example of a film camera, which shoots 24 frames
per second. If we're shooting a movie of a car, and the car wheel spins at a rate greater than 12 revolutions per second, it's
exceeding half the sampling rate of the camera. The wheel completes more than 1/ 2 revolution per frame. If, for example it
actually completes 18/ 24 of a revolution per frame, it will appear to be going backward at a rate of 6 revolutions per second.
In other words, if we don't witness what happens between samples, a 270 revolution of the wheel is indistinguishable from
a -90 revolution. The samples we obtain in the two cases are precisely the same.

For the camera, a revolution of 18/24 is no different from a revolution of -6/24

For audio sampling, the phenomenon is practically identical. Any frequency that exceeds the Nyquist rate is
indistinguishable from a negative frequency the same amount less than the Nyquist rate. (And we do not distinguish
perceptually between positive and negative frequencies.) To the extent that a frequency exceeds the Nyquist rate, it is folded
back down from the Nyquist frequency by the same amount.

For a demonstration, consider the next two examples. The following example shows a graph of a 4,000 Hz cosine wave
(energy only at 4,000 Hz) being sampled at a rate of 22,050 Hz. 22,050 Hz is half the CD sampling rate, and is an acceptable
sampling rate for sounds that do not have much energy in the top octave of our hearing range.
In this case the sampling rate is quite adequate because the maximum frequency we are trying to record is well below the
Nyquist frequency.

A 4,000 Hz cosine wave sampled at 22,050 Hz

Now consider the same 4,000 Hz cosine wave sampled at an inadequate rate, such as 6,000 Hz. The wave completes more
than 1/ 2 cycle per sample, and the resulting samples are indistinguishable from those that would be obtained from a 2,000
Hz cosine wave.

A 4,000 Hz cosine wave undersampled at 6,000 Hz

The simple lesson to be learned from the Nyquist theorem is that digital audio cannot accurately represent any frequency
greater than half the sampling rate. Any such frequency will be misrepresented by being folded over into the range below half
the sampling rate.

Precision of quantization
Each sample of an audio signal must be ascribed a numerical value to be stored in the computer. The numerical value
expresses the instantaneous amplitude of the signal at the moment it was sampled. The range of the numbers must be
sufficiently large to express adequately the entire amplitude range of the sound being sampled.

The range of possible numbers used by a computer depends on the number of binary digits (bits) used to store each number.
A bit can have one of two possible values: either 1 or 0. Two bits together can have one of four possible values: 00, 01, 10, or
11. As the number of bits increases, the range of possible numbers they can express increases by a power of two. Thus, a
single byte (8 bits) of computer data can express one of 2 8 = 256 possible numbers. If we use two bytes to express each
number, we get a much greater range of possible values because 2 16 = 65,536.

The number of bits used to represent the number in the computer is important because it determines the resolution with
which we can measure the amplitude of the signal. If we use only one byte to represent each sample, then we must divide the
entire range of possible amplitudes of the signal into 256 parts since we have only 256 ways of describing the amplitude.

Using one byte per sample, each sample can have one of only 256 different possible values

For example, if the amplitude of the electrical signal being sampled ranges from -10 volts to +10 volts and we use one byte
for each sample, each number does not represent a precise voltage but rather a 0.078125 V portion of the total range. Any
sample that falls within that portion will be ascribed the same number. This means each numerical description of a sample's
value could be off from its actual value by as much as 0.078125V -- 1/ 256 of the total amplitude range. In practice each
sample will be off by some random amount from 0 to 1/ 256 of the total amplitude range. The mean error will be 1/ 512 of the
total range.

This is called quantization error. It is unavoidable, but it can be reduced to an acceptable level by using more bits to
represent each number. If we use two bytes per sample, the quantization error will never be greater than 1/ 65,536 of the
total amplitude range, and the mean error will be 1/ 131,072 .

Since the quantization error for each sample is usually random (sometimes a little too high, sometimes a little too low), we
generally hear the effect of quantization error as white noise. This noise is not present in the original signal. It is added into
the digital signal by the imprecise nature of quantization. This is called quantization noise.

The ratio of the total amplitude range to the quantization error is called the signal-to-quantization- noise-ratio (SQNR).
This is the ratio of the maximum possible signal amplitude to the average level quantization of the quantization noise, and is
usually stated in decibels.

As a rule of thumb, each bit of precision used in quantization adds 6 dB to the SQNR. Therefore, sound quantized with 8-bit
numerical precision will have a best case SQNR of about 48 dB. This is adequate for cases where fidelity is not important,
but is certainly not desirable for music or other critical purposes. Sound sampled with 16-bit precision (CD-quality) has a
SQNR of 96 dB, which is quite good -- much better than traditional tape recording.

In short, the more bits used by the computer to store each sample, the better the potential ratio of signal to noise.

Memory and storage


We have seen that the standard sampling rate for high-fidelity audio is 44,100 samples per second. We've also seen that 16
bits (2 bytes) are needed per sample to achieve a good signal-to-noise ratio. With this information we can calculate the
amount of data needed for digital audio: 41,000 samples per second, times 2 bytes per sample, times 2 channels for stereo,
times 60 seconds per minute equals more than 10 megabytes of data per minute of CD-quality audio.

For this quality of audio, a high-density floppy disk holds less than 8 seconds of sound, and a 100 MB Zip cartridge holds
less than 10 minutes. Clearly, the memory and storage requirements of digital audio are substantial. Fortunately, a compact
disc holds over an hour of stereo sound, and a computer hard disk of at least 1 gigabyte is standard for audio recording and
processing.

Clipping
If the amplitude of the incoming electrical signal exceeds the maximum amplitude that can be expressed numerically, the
digital signal will be a clipped-off version of the actual sound.

A signal that exceeds maximum amplitude will be clipped when it is quantized

The clipped sample will often sound quite different from the original. Sometimes this type of clipping causes only a slight
distortion of the sound that is heard as a change in timbre. More often though, it sounds like a very unpleasant noise added
to the sound. For this reason, it's very important to take precautions to avoid clipping. The amplitude of the electrical signal
should not exceed the maximum expected by the ADC.

It's also possible to produce numbers in the computer that exceed the maximum expected by the DAC. This will cause the
sound that comes out of the DAC to be a clipped version of the digital signal. Clipping by the DAC is just as bad as clipping
by the ADC, so care must be taken not to generate a digital signal that goes beyond the numerical range the DAC is capable
of handling.

Advantages of digital audio


Synthesizing digital audio
Since a digital representation of sound is just a list of numbers, any list of numbers can theoretically be considered a digital
representation of a sound. In order for a list of numbers to be audible as sound, the numerical values must fluctuate up and
down at an audio rate. We can listen to any such list by sending the numbers to a DAC where they are converted to voltages.
This is the basis of computer sound synthesis. Any numbers we can generate with a computer program, we can listen to as
sound.

Many methods have been discovered for generating numbers that produce interesting sounds. One method of producing
sound is to write a program that repeatedly solves a mathematical equation containing two variables. At each repetition, a
steadily increasing value is entered for one of the variables, representing the passage of time. The value of the other variable
when the equation is solved is used as the amplitude for each moment in time. The output of the program is an amplitude
that varies up and down over time.

For example, a sine wave can be produced by repeatedly solving the following algebraic equation, using an increasing value
for n:

y = A sin(2_n/R+)

where A is the amplitude of the wave, is the frequency of the wave, n is the sample number (0,1, 2,3, etc.), R is the
sampling rate, and is the phase. If we enter values for A, ,and y while increasing the value of n, the value of y (the output
sample) will vary sinusoidally.

A complex tone can be produced by adding sinusoids -- a method known as additive synthesis:

y = A1 sin(2_1n/R+1) + A2 sin(2_2n/R+2) + ...

This is an example of how a single algebraic expression can produce a sound. Naturally, many other more complicated
programs are possible. A few synthesis methods such as additive synthesis, wavetable synthesis, frequency modulation, and
waveshaping are demonstrated in the MSP Tutorial.

Manipulating digital signals


Any sound in digital form -- whether it was synthesized by the computer or was quantized from a real world sound -- is just
a series of numbers. Any arithmetic operation performed with those numbers becomes a form of audio processing.

For example, multiplication is equivalent to audio amplification. Multiplying each number in a digital signal by 2 doubles the
amplitude of the signal (increases it 6 dB). Multiplying each number in a signal by some value between 0 and 1 reduces its
amplitude.

Addition is equivalent to audio mixing. Given two or more digital signals, a new signal can be created by adding the first
numbers from each signal, then the second numbers, then the third numbers, and so on.

An echo can be created by recalling samples that occurred earlier and adding them to the current samples. For example,
whatever signal was sent out 1000 samples earlier could be sent out again, combined with the current sample.

y = xn + A yn-1000

As a matter of fact, the effects that such operations can have on the shape of a signal (audio or any other kind) are so many
and varied that they comprise an entire branch of electrical engineering called digital signal processing (DSP). DSP is
concerned with the effects of digital filters -- formulae for modifying digital signals by combinations of delay, multiplication,
addition, and other numerical operations.

Summary
This chapter has described how the continuous phenomenon of sound can be captured and faithfully reproduced as a series
of numbers, and ultimately stored in computer memory as a stream of binary digits. There are many benefits obtainable only
by virtue of this digital representation of sound: higher fidelity recording than was previously possible, synthesis of new
sounds by mathematical procedures, application of digital signal processing techniques to audio signals, etc.

MSP provides a toolkit for exploring this range of possibilities. It integrates digital audio recording, synthesis, and processing
with the MIDI control and object-based programming of Max.
How MSP Works: Max Patches and the MSP Signal Network
Introduction
Max objects communicate by sending each other messages through patch cords. These messages are sent at a specific
moment, either in response to an action taken by the user (a mouse click, a MIDI note played, etc.) or because the event was
scheduled to occur (by metro, delay, etc.).
MSP objects are connected by patch cords in a similar manner, but their inter-communication is conceptually different.
Rather than establishing a path for messages to be sent, MSP connections establish a relationship between the connected
objects, and that relationship is used to calculate the audio information necessary at any particular instant. This
configuration of MSP objects is known as the signal network.

The following example illustrates the distinction between a Max patch in which messages are sent versus a signal network in
which an ongoing relationship is established.

Max messages occur at a specific instant; MSP objects are in constant communication

In the Max example on the left, the number box doesn't know about the number 0.75 stored in the float object. When the
user clicks on the button, the float object sends out its stored value. Only then does the number box receive, display, and
send out the number 0.75. In the MSP example on the right, however, each outlet that is connected as part of the signal
network is constantly contributing its current value to the equation. So, even without any specific Max message being sent,
the *~ object is receiving the output from the two sig~ objects, and any object connected to the outlet of *~ would be
receiving the product 0.75.

Another way to think of a MSP signal network is as a portion of a patch that runs at a faster (audio) rate than Max. Max, and
you the user, can only directly affect that signal portion of the patch every millisecond. What happens in between those
millisecond intervals is calculated and performed by MSP. If you think of a signal network in this way -- as a very fast patch -
- then it still makes sense to think of MSP objects as sending and receiving messages (even though those messages are sent
faster than Max can see them), so we will continue to use standard Max terminology such as send, receive, input, and output
for MSP objects.

Audio rate and control rate


The basic unit of time for scheduling events in Max is the millisecond (0.001 seconds). This rate -- 1000 times per second --
is generally fast enough for any sort of control one might want to exert over external devices such as synthesizers, or over
visual effects such as QuickTime movies.

Digital audio, however, must be processed at a much faster rate -- commonly 44,100 times per second per channel of audio.
The way MSP handles this is to calculate, on an ongoing basis, all the numbers that will be needed to produce the next few
milliseconds of audio. These calculations are made by each object, based on the configuration of the signal network.

An oscillator (cycle~), and an amplifier (*~) controlled by another oscillator (phasor~)

In this example, a cosine waveform oscillator with a frequency of 2000 Hz (the cycle~ object) has its amplitude scaled (every
sample is multiplied by some number in the *~ object) then sent to the digital-to-analog converter (dac~). Over the course
of each second, the (sub-audio) sawtooth wave output of the phasor~ object sends a continuous ramp of increasing values
from 0 to 1. Those increasing numbers will be used as the right operand in the *~ for each sample of the audio waveform,
and the result will be that the 2000 Hz tone will fade in linearly from silence to full amplitude each second. For each
millisecond of audio, MSP must produce about 44 sample values (assuming an audio sample rate of 44,100 Hz), so for each
sample it must look up the proper value in each oscillator and multiply those two values to produce the output sample.

Even though many MSP objects accept input values expressed in milliseconds, they calculate samples at an audio sampling
rate. Max messages travel much more slowly, at what is often referred to as a control rate. It is perhaps useful to think of
there being effectively two different rates of activity: the slower control rate of Max's scheduler, and the faster audio sample
rate.

Note: Since you can specify time in Max in floating-point milliseconds, the resolution of the scheduler varies depending on
how often it runs. The exact control rate is set by a number of MSP settings we'll introduce shortly. However, it is far less
efficient to process audio using the control functions running in the scheduler than it is to use the specialized audio objects
in MSP.

The link between Max and MSP


Some MSP objects exist specifically to provide a link between Max and MSP -- and to translate between the control rate and
the audio rate. These objects (such as sig~ and line~) take Max messages in their inlets, but their outlets connect to the
signal network; or conversely, some objects (such as snapshot~) connect to the signal network and can peek (but only as
frequently as once per millisecond) at the value(s) present at a particular point in the signal network.

Supply a Max message to the signal network, or get a Max message from a signal

These objects are very important because they give Max, and you the user, direct control over what goes on in the signal
network.

User interface control over the signal's amplitude

Some MSP object inlets accept both signal input and Max messages. They can be connected as part of a signal network, and
they can also receive instructions or modifications via Max messages.

For example the dac~ (digital-to-analog converter) object, for playing the audio signal, can be turned on and off with the
Max messages start and stop.

Some MSP objects can receive audio signals and Max messages in the same inlet

And the cycle~ (oscillator) object can receive its frequency as a Max float or int message, or it can receive its frequency from
another MSP object (although it can't do both at the same time, because the audio input can be thought of as constantly
supplying values that would immediately override the effect of the float or int message).
Some MSP objects can receive either Max messages or signals for the same purpose

So you see that a Max patch (or subpatch) may contain both Max objects and MSP objects. For clear organization, it is
frequently useful to encapsulate an entire process, such as a signal network, in a subpatch so that it can appear as a single
object in another Max patch.

Encapsulation can clarify relationships in a Max patch

Limitations of MSP
From the preceding discussion, it's apparent that digital audio processing requires a lot of number crunching. The computer
must produce tens of thousands of sample values per second per channel of sound, and each sample may require many
arithmetic calculations, depending on the complexity of the signal network. And in order to produce realtime audio, the
samples must be calculated at least as fast as they are being played.

Realtime sound synthesis of this complexity on a general-purpose personal computer was pretty much out of the question
until the introduction of sufficiently fast processors such as the PowerPC. Even with the PowerPC, though, this type of
number crunching requires a great deal of the processor's attention. So it's important to be aware that there are limitations
to how much your computer can do with MSP.

Unlike a MIDI synthesizer, in MSP you have the flexibility to design something that is too complicated for your computer to
calculate in real time. The result can be audio distortion, a very unresponsive computer, or in extreme cases, crashes.

Because of the variation in processor performance between computers, and because of the great variety of possible signal
network configurations, it's difficult to say precisely what complexity of audio processing MSP can or cannot handle. Here
are a few general principles:

The faster your computer's CPU, the better will be the performance of MSP.

A fast hard drive and a fast connection will improve input/output of audio files.

Turning off background processes (such as file sharing) will improve performance.

Reducing the audio sampling rate will reduce how many numbers MSP has to compute for a given amount of sound, thus
improving its performance (although a lower sampling rate will mean degradation of high frequency response). Controlling
the audio sampling rate is discussed in the Audio Input and Output chapter.

When designing your MSP instruments, you should bear in mind that some objects require more intensive computation than
others. An object that performs only a few simple arithmetic operations (such as sig~, line~, +~floating-point number
box, *~, or phasor~) is computationally inexpensive. (However, /~ is much more expensive.) An object that looks up a
number in a function table and interpolates between values (such as cycle~) requires only a few calculations, so it's likewise
not too expensive. The most expensive objects are those which must perform many calculations per sample: filters (reson~,
biquad~), spectral analyzers (fft~, ifft~), and objects such as play~, groove~, comb~, and tapout~ when one of their
parameters is controlled by a continuous signal. Efficiency issues are discussed further in the MSP Tutorial.

Note: To see how much of the processor's time your patch is taking, look at the CPU Utilization value in
the Audio Status window. Choose Audio Status... from the Options menu to open this window.

Advantages of MSP
Your laptop or desktop machine is a general purpose computer, not a specially designed sound processing computer such as
a commercial sampler or synthesizer, so as a rule you can't expect it to perform quite to that level. However, for relatively
simple instrument designs that meet specific synthesis or processing needs you may have, or for experimenting with new
audio processing ideas, it is a very convenient instrument-building environment.

1. Design an instrument to fit your needs. Even if you have a lot of audio equipment, it probably cannot do every
imaginable thing you need to do. When you need to accomplish a specific task not readily available in your studio, you can
design it yourself.

2. Build an instrument and hear the results in real time. With non-realtime sound synthesis programs you define an
instrument that you think will sound the way you want, then compile it and test the results, make some adjustments,
recompile it, etc. With MSP you can hear each change that you make to the instrument as you build it, making the process
more interactive.

3. Establish the relationship between gestural control and audio result. With many commercial instruments you can't
change parameters in real time, or you can do so only by programming in a complex set of MIDI controls. With Max you can
easily connect MIDI data to the exact parameter you want to change in your MSP signal network, and you know precisely
what aspect of the sound you are controlling with MIDI.

4. Integrate audio processing into your composition or performance programs. If your musical work consists of devising
automated composition programs or computer-assisted performances in Max, now you can incorporate audio processing
into those programs. Need to do a hands- free crossfade between your voice and a pre-recorded sample at a specific point in
a performance? You can write a Max patch with MSP objects that does it for you, triggered by a single MIDI message.

Some of these ideas are demonstrated in the MSP tutorials.

See Also
Name Description
MSP: Audio Input and Output MSP: Audio Input and Output
Audio Input and Output
MSP interfaces with your computer's audio hardware via the dac~ and adc~ objects and their easy-to-use equivalents
ezdac~ and ezadc~. If you don't have any special audio hardware and have no need for inter- application audio routing, the
default driver on your system will give you stereo full- duplex audio I/O with no special configuration on your part.

In addition to Core Audio or MME on Windows, there are a number of other ways to get audio into and out of Max. Each of
these methods involves using what we call a driver, which is actually a special type of Max object. Some of these drivers
facilitate the use of MSP with third- party audio hardware. Also, a non real-time driver allows you to use MSP as a disk-
based audio processing and synthesis system, removing the limit of how much processing you can do with your CPU in real
time.

MSP audio driver objects are located in the ad folder located in the Cycling '74 folder inside the Max application folder.
These object files must be in this folder called ad (which stands for audio driver), otherwise MSP will be unable to locate
them.

We will begin with a discussion of audio input/output in MSP in general. Later in this chapter we will discuss aspects of
specific audio drivers that are available to you in MSP. First we'll discuss the Audio Status window and how to use it to get
information about your audio hardware and set parameters for how MSP handles audio input and output.

The Audio Status Window


All global audio parameters in MSP are displayed in the Audio Status window. To open the Audio Status window, just
double-click on any dac~ or adc~ object in a locked Patcher window. Alternately, you can choose Audio Status... from the
Options menu.

The Audio Status window is arranged as a group of menus and checkboxes that set all of the parameters of the audio input
and output in MSP. Since all of these options can be changed from within your patch, the Audio Status window serves as a
monitor for your current audio settings as well.
Technical Detail: The Audio Status window is in fact a Max patch (called Audio Status, in the interfaces folder inside
the Cycling '74 folder). Every parameter shown in the Audio Status window is a menu or checkbox hooked up to an
instance of the adstatus object. The adstatus object can be used inside of your MSP patches so that you can set and
restore audio parameters specifically for certain patches. The adstatus object is also useful for obtaining information
current CPU load, vector size, and sampling rate. See the adstatus object manual pages in the MSP Reference Manual
for more details.

At the very top of the Audio Status window is a pop-up menu for turning the audio in MSP on and off and a set of pop-up
menus that let you select an audio driver and configure its input source and output destination.

The second pop-up menu allows you to view and select an audio driver for MSP. The specific audio drivers will be discussed
later in this chapter. A brief summary will suffice for now:
None: This setting shuts off MSP audio processing.
Core Audio: This is the default audio driver for MSP on Macintosh. It interfaces with the system's built-in Core Audio
system and can be used with the built-in audio of the computer, or, with the proper software support, a third-party
hardware interface, such as ASIO.
MME or DirectSound: (Windows only) On Windows, MSP loads the MME driver by default. If you have correctly
installed external hardware and it also supports DirectSound, it should also appear as an option on the pop-up menu.
ad_rewire: This driver supports a standard developed by Propellerhead Software that allows sound generating
applications (ReWire Devices) to send multiple channels of audio and midi to other applications (ReWire Mixers) that
process and output it. Selecting the ad_rewire driver enables Max to function as a ReWire Device to route audio from
MSP into applications that support ReWire (such as Live, Digital Performer or Cubase). Using MSP to host ReWire
devices (such as Reason) can be accomplished with the rewire~ object.
ASIO: (Windows only) If you have a third-party audio interface which supports ASIO (a cross-platform audio hardware
standard developed by Steinberg), and it is installed correctly, it will be found by the MSP ASIO driver. You may have
as many ASIO devices as you wish; they will all be found by the driver and will appear in the Driver pull-down menu in
the Audio Status Window preceded by the word ASIO.
ad_nonreal: This driver enables MSP to work in non real-time mode, allowing you to synthesize and process audio
without any real-time processor performance limitations. Real-time audio input and output are disabled under this
driver.
Only one audio driver can be selected at any given time. MSP saves the settings for each audio driver separately and will
recall the last used audio driver when you restart Max.

The next two pop-up menus are active only when using the Core Audio driver on Macintosh or ASIO drivers. When the Core
Audio driver or either the MME or DirectSound drivers on Windows are selected, the pop-up menus allow you to change the
audio input source. These settings can also be changed using the Audio MIDI Setup application on Macintosh or the Sounds
and Audio Devices Properties window (Start > Settings > Control Panel > Sounds and Audio Devices) on Windows, but only
with these menus while MSP is running.

When ASIO is in use, the pop-up menus allow you to set the clock source for your audio hardware and whether or not to
prioritize MIDI input and output over audio I/O.

The Audio Status Window lets you control the size of the blocks of samples (called signal vectors) that MSP uses. There are
two vector sizes you can control.
The I/O Vector Size (I/O stands for input/output) controls the number of samples that are transferred to and from the
audio interface at one time.

The Signal Vector Size sets the number of samples that are calculated by MSP objects at one time. This can be less
than or equal to the I/O Vector Size, but not more. If the Signal Vector Size is less than the I/O Vector Size, MSP
calculates two or more signal vectors in succession for each I/O vector that needs to be calculated.
With an I/O vector size of 256, and a sampling rate of 44.1 kHz, MSP calculates about 5.8 milliseconds of audio data at
a time.

The I/O Vector Size may have an effect on latency and overall performance. A smaller vector size may reduce the inherent
delay between audio input and audio output, because MSP has to perform calculations for a smaller chunk of time. On the
other hand, there is an additional computational burden each time MSP prepares to calculate another vector (the next chunk
of audio), so it is easier over-all for the processor to compute a larger vector. However, there is another side to this story.
When MSP calculates a vector of audio, it does so in what is known as an interrupt. If MSP is running on your computer,
whatever you happen to be doing (word processing, for example) is interrupted and an I/O vector's worth of audio is
calculated and played. Then the computer returns to its normally scheduled program. If the vector size is large enough, the
computer may get a bit behind and the audio output may start to click because the processing took longer than the computer
expected. Reducing the I/O Vector Size may solve this problem, or it may not. On the other hand, if you try to generate too
many interrupts, the computer will slow down trying to process them (saving what you are doing and starting another task is
hard work). Therefore, you'll typically find the smaller I/O Vector Sizes consume a greater percentage of the computer's
resources. Optimizing the performance of any particular signal network when you are close to the limit of your CPU's
capability is a trial-and-error process. That's why MSP provides you with a choice of vector sizes.

Technical Detail: Some audio interface cards do not provide a choice of I/O Vector Sizes. There are also some ASIO
drivers whose selection of I/O Vector Sizes may not conform to the multiple- of-a-power-of-2 limitation currently
imposed by MSP's ASIO support. In some cases, this limitation can be remedied by using the ASIO driver at a different
sampling rate.

Changing the vector sizes does not affect the actual quality of the audio itself, unlike changing the sampling rate, which
affects the high frequency response. Changing the signal vector size won't have any effect on latency, and will have only a
slight effect on overall performance (the larger the size, the more performance you can expect). However, certain types of
algorithms benefit from a small signal vector size. For instance, the minimum delay you can get from MSP's delay line
objects tapin~ and tapout~ is equal to the number of samples in one signal vector at the current sampling rate. ith a signal
vector size of 64 at 44.1 kHz sampling rate, this is 1.45 milliseconds, while at a signal vector size of 1024, it is 23.22
milliseconds. The Signal Vector size in MSP can be set as low as 2 samples, and in most cases can go as high as the largest
available I/O Vector Size for your audio driver. However, if the I/O Vector Size is not a power of 2, the maximum signal
vector size is the largest power of 2 that divides evenly into the I/O vector size.

You can set the audio sampling rate with the Sampling Rate pop-up menu. For full-range audio, the recommended sampling
rate is 44.1 kHz. Using a lower rate will reduce the number of samples that MSP has to calculate, thus lightening your
computer's burden, but it will also reduce the frequency range. If your computer is struggling at 44.1 kHz, you should try a
lower rate.

Technical Detail: Subpatches loaded into the poly~ object can function at different sampling rates and vector sizes
from the top-level patch. In addition, the poly~ object allows up- and down-sampling as well as different vector sizes.
The Audio Status window only displays and changes settings for the top-level patch.

The Max Scheduler in Overdrive option enables you to turn Max's Overdrive setting on and off from within the Audio Status
window. When Overdrive is enabled, the Max event scheduler runs at interrupt level. The event scheduler does things like
trigger the bang from a repeating metro object, as well as send out any recently received MIDI data. When overdrive is not
enabled, the event scheduler runs inside a lower-priority event handling loop that can be interrupted by doing things like
pulling down a menu. You can also enable and disable Overdrive using the Options menu. Overdrive generally improves
timing accuracy, but there may be exceptions, and some third-party software may not work properly when Overdrive is
enabled.

The Scheduler in Audio Interrupt feature is available when Overdrive is enabled. It runs the Max event scheduler
immediately before processing a signal vector's worth of audio. Enabling Scheduler in Audio Interrupt can greatly improve
the timing of audio events that are triggered from control processes or external MIDI input. However, the improvement in
timing can be directly related to your choice of I/O Vector Size, since this determines the interval at which events outside the
scheduler (such as MIDI input and output) affect Max. When the Signal Vector Size is 512, the scheduler will run every 512
samples. At 44.1 kHz, this is every 11.61 milliseconds, which is just at the outer limits of timing acceptability. With smaller
Signal Vector Sizes (256, 128, 64), the timing will sound tighter. Since you can change all of these parameters as the music
is playing, you can experiment to find acceptable combination of precision and performance.

If you are not doing anything where precise synchronization between the control and audio is important, leave Scheduler in
Audio Interrupt unchecked. You'll get a bit more overall CPU performance for signal processing

The next portion of the Audio Status helps you monitor your system's performance.

The CPU Utilization field displays a rough estimate of how much of your computer's CPU is being allocated for crunching
audio in MSP.

The CPU Limit option allows you to set a limit (expressed in terms of a percentage of your computer's CPU) to how much
signal processing MSP is allowed to do. MSP will not go above the set CPU limit for a sustained period, allowing your
computer to perform other tasks without MSP locking them out. The trade-off, however, is that you'll hear clicks in the audio
output when the CPU goes over the specified limit. Setting this value to either 0 or 100 will disable CPU limiting.

The number next to Signals Used shows the number of internal buffers that were needed by MSP to connect the signal
objects used in the current signal network. The number of Function Calls gives an approximate idea of how many
calculations are being required for each sample of audio. Both of these fields will update whenever you change the number of
audio objects or how they are patched together.

Vector Optimization only applies to PowerPC computers. Vector optimization allows four samples to be processed within the
space of a single instruction. However, not all audio signal processing algorithms can be optimized in this way (for example,
recursive filter algorithms are substantially immune from vector optimization). MSP itself no longer uses vector
optimization, but third-party audio objects may still use it. In other words, unless you are using a vector-enabled third-party
audio object on a PowerPC computer, this setting will have no effect.

The next portion of the Audio Status Window lets you map logical I/O channels.
The pop-up menus labeled Input Channel 1, Input Channel 2, Output Channel Output Channel 2 allow you to map the first
two logical channels of I/O in MSP (i.e. the first two outlets of the adc~ object and the first two inlets of the dac~ object) to
physical channels used by your audiodriver. Different audio drivers give you different options, for example, the MME driver
on Windows only supports two channels, so you will normally use the default options. To map additional logical channels,
use the I/O Mappings window, which you can view by clicking the I/O Mappings button at the bottom of the Audio Status
window (see below for more information about the I/O Mappings window). In addition, you can use the adstatus object
from within your patch to map any of the 512 logical audio I/O channels.

About Logical Input and Output Channels


In MSP 2, you can create a dac~ or adc~ object that uses a channel number between 1 and 512. These numbers refer to what
we call logical channels and can be dynamically reassigned to physical device channels of a particular driver using either the
Audio Status window, its I/O Mappings subwindow, or an adstatus object with an input or output keyword argument.

The adc~ and dac~ objects allow you to specify arguments which define which logical channels are mapped to their inlets
and outlets, respectively. In the example below, multiple logical channels are in use in a simple patch:

In this example, two separate adc~ objects output audio signals from logical channel pairs 1/2 and 3/4, respectively. The
output of all four channels is sent to gain~ objects which attenuate the incoming signals and send them to the first four
logical output channels, as specified by the first dac~ object. The input signals are also multiplied (ring modulated) and sent
out logical channels 9 and 10. Up to sixteen arguments can be typed into a single adc~ or dac~ object; if you want to use
more than 16 logical channels, you can use multiple adc~ and dac~ objects. The ezadc~ and ezdac~ objects only access the
first two logical input and output channels in MSP.

The purpose of having both logical channels and physical device channels is to allow you to create patches that use as many
channels as you need without regard to the particular hardware configuration you're using. For instance, some audio
interfaces use physical device channels 1 and 2 for S/ PDIF input and output. If you don't happen to have a S/PDIF-
compatible audio interface, you may wish to use channels 8 and 9 instead. With MSP 1.x, you would have been required to
change all instances of dac~ and/or adc~ objects with arguments 1 and 2 to have arguments 8 and 9. With MSP 2, this is no
longer necessary. You can simply go to the Audio Status window and choose the eighth and ninth physical channels listed in
the Input and Output pop-up menus.

Logical channels in MSP are only created if there is a dac~ or adc~ object using them. In other words, if you're only using
logical outputs 1 and 2, there aren't 510 unused audio streams sitting around hogging your CPU. However, since you can mix
any number of logical channels to a single physical channel if necessary, you can create a complex multi-channel setup that
will allow other people to hear all of your logical channels when they use it on a two-channel output device.

To assign multiple logical channels to one physical channel of an output device, use the I/O Mapping window. Click on the
I/O Mappings button at the bottom of the Audio Status window.
The configuration shows that logical channels 1, 3, 5, and 7 have been mapped to the left output channel of the current audio
device, and logical channels 2, 4, 6, and 8 have been mapped to the right output channel of the current audio device.

I/O Mappings are saved for each audio driver. You can also create I/O mappings within your patch using the adstatus
object. The example patch below accomplishes the same remapping as that shown in the I/O Mapping window above, but
does so automatically when the patch is loaded.

Using Core Audio


Core Audio provides audio I/O to Mac applications from both the computer's built-in audio hardware as well as any external
audio hardware you may have.

If you have external audio hardware, it should come the drivers to interface with Core Audio. When these drivers are
installed and the hardware is present, Core Audio will include the external device as a Core Audio choice in the Driver menu
in the Audio Status window.
The Sound part of the System Preferences application can be used to set basic sound settings for the system, such as the
Output volume, left/right balance, and sound output device, as well as the Input volume and sound input device. You can
also use the Audio MIDI Setup application (located in /Applications/Utilities) for more detailed control of the sound I/O
settings. Note that modifications you make to the Sound section of the System Preferences application, such as changing the
output volume or balance, are reflected in the audio MIDI Setup (and vice versa). You can open the Audio MIDI Setup
application by clicking on the Open Audio Control Panel button in the lower left corner of the Audio Status Window.

The Audio part of the Audio MIDI Setup application shows Input settings on the left side, and Output settings on the right.

The System Settings let you choose which audio device is used for system audio input and output, while the Selected Audio
Device menu allows you to control the various settings for the built-in and any external hardware audio devices.

When using external audio devices, the Input Volume and Output Volume sliders can be used to set the overall input and
output volumes of the selected device (they are not available when using the built-in audio controller). The Device Mute
checkboxes allow you to mute the input and output devices, if applicable.

Play Through is available on Macs only. Play Through checkbox just under the Input Volume slider lets you choose whether
or not the input device is 'monitored' directly through to the output. When playthrough is enabled, the dry signal from the
input source will play through to the output mixed in with any processed signal you may be sending to the output in MSP.
Disabling playthrough will enable you to control how much (if any) dry signal from the audio input is routed to the output.
This option can be changed in MSP by sending a message to the Max application to change it. Putting the following in a
message box and clicking on it will turn playthrough off:

; dsp driver playthrough 0

Using an argument of 1 will turn it on.

The Input Section allows you to select the Input Source (for example Line or Mic input for the selected device) as well as the
sampling rate and bit depth in the Current Format pop-up menu. Similarly, the Output Section also allows you to select the
sampling rate and bit-depth in its Current Format pop-up menu. The available selections will vary, depending on your audio
hardware.

You can set the volume levels for the individual audio input and output channels, mute individual channels, and/or select
them for playthrough using the controls located below the Current Format menus. The lower part of the window is used to
display the current input and output settings.

Using MME Audio and DirectSound on Windows


Three types of sound card drivers are supported in Windows: MME, DirectSound and ASIO. Your choice of driver will have a
significant impact on the performance and latency you will experience with MSP.

The MME driver (ad_mme) is the default used for output of Windows system sounds, and are provided for almost any sound
card and built-in audio system. While compatibility with your hardware is almost guaranteed, the poor latency values you
get from an MME driver make this the least desirable option for real-time media operation.

DirectSound drivers, built on Microsoft's DirectX technology, have become commonplace for most sound cards, and provide
much better latency and performance than MME drivers. Whenever possible, a DirectSound driver (ad_directsound) should
be used in preference to an MME driver. Occasionally, (and especially in the case of motherboard-based audio systems) you
will find the DirectSound driver performs more poorly than the MME driver. This can happen when a hardware-specific
DirectSound driver is not available, and the system is emulating DirectSound while using the MME driver. In these cases, it
is best to use MME directly, or find an ASIO driver for your system.

The best performance and lowest latency will typically be achieved using ASIO drivers. The ASIO standard, developed by
Steinberg and supported by many media-oriented sound cards, is optimized for very low latency and high performance. As
with the DirectSound driver, you need to verify that performance is actually better than other options; occasionally, an ASIO
driver will be a simple wrapper around the MME or DirectSound driver, and will perform more poorly than expected.

Using MME and DirectSound Drivers on with MSP on Windows


On Windows, MSP loads the MME driver by default. The MSP MME and DirectSound drivers are located in C:\Program
Files\Common Files\Cycling 74\ad\.

If you have correctly installed external hardware, it should support playback and recording with the MME driver and the
Direct Sound driver in the Driver Menu of the Audio Status Window.

If an audio device only supports MME or DirectSound, the Windows OS does an automatic mapping of one to the other.
Since many audio devices initially did not support DirectSound, Microsoft emulated DirectSound with a layer that bridged
from DirectSound to MME. Currently, there is greater support for native DirectSound drivers, and sometimes when you use
MME drivers Windows is actually running a layer to convert from MME to DirectSound.

Note: Some devices such as the Digidesign mBox only support the ASIO driver standard. In such cases, you will need to
select the proper ASIO driver in the Audio Status Window. See the section Using ASIO Drivers on Windows for more
information.

You can make overall changes to the basic operation of your default audio driver by accessing the Sounds and Audio Devices
Properties window (Start > Settings > Control Panel > Sounds and Audio Devices). Here you can select Audio devices, and
create settings for balance and output volume.
MSP supports the use of different input and output devices with MME and DirectSound drivers. Use the Audio Status
Window to choose input and output devices.

Input and Output Devices


When using MME or Directsound drivers, you may choose input and output devices from the pull-down menus in the Audio
Status window, which will be automatically populated with the drivers for your audio hardware. When using the MME and
Directsound drivers, it is possible to use different audio devices for input and output simultaneously. However, this is not
recommended or supported and unless there is some external (from Max) provision for synchronizing the devices dropouts
will likely occur over time.

Thread Priority and Latency Settings


Both MME and Directsound drivers include settings for Thread Priority and Latency. These are both set by default to
settings which we hope will work on your computer in the majority of situations. However, you may find that when you are
working with a patch that you have problems which you may be able to resolve by changing some of these settings. If your
audio is crackling or there are glitches in it, you may want to try increasing the latency setting. This has the disadvantage of
making your audio feel less responsive in real time, but it will allow the audio driver more time to work on the extra audio
demands you have placed on it.

If your system is slow in other areas -- such as screen redrawing or general timing accuracy -- you may wish to decrease the
thread priority of the audio driver. This will give your other tasks more room to get done, but may also result in you needing
to increase latency in order to give your audio driver room to breathe at the new lower priority.

Timing between the max scheduler and MSP is best when the I/O vector size is on the order of 1ms. We recommend setting
the IO vector size to 128 samples. Having a setting of the latency separate from the I/O vector size allows this to work
without audio glitches on most hardware.
Using ReWire with MSP
The ad_rewire driver allows you to use MSP as a ReWire Device, where MSP audio will be routed into a ReWire Mixer
application such as Cubase. Both Max and the mixer application must be running at the same time in order to take
advantage of ReWire's services. The mixer application should be also compatible with ReWire 2 or later for best results.

When the ad_rewire driver is selected, audio from MSP can be routed to any of 16 inter- application ReWire channels which
will appear as inputs in ReWire mixer host applications. The first time ad_rewire is selected it will register itself with the
ReWire system. Subsequent launches of ReWire Mixer applications will then offer Max as a ReWire device.

For example, after the Max ReWire Device is registered, Cubase will have a Max menu item in the Devices menu. When you
choose it you will see a list of the audio outputs from Max. They will default to the off state. Click on any of the buttons to
activate that channel. Once the channel is activated it will show up in the Cubase Track Mixer.

MSP can also be used as a Mixer Application for ReWire Devices such as Reason. To do this, you use the rewire~ object.
Please see the MSP Reference Manual pages on the rewire~~ object for more information.
If you try to use rewire~and the ad_rewire audio driver simultaneously, you won't get any audio output. This is because each
is waiting for the other: the ad_rewire driver is waiting for the rewire~ object to ask it for an audio stream, but the rewire~
object can't do anything unless given processing time by an audio driver.

However, you can use rewire~ in conjunction with the Max Runtime or a standalone built using Max when the runtime or
standalone is using the ad_rewire driver.

Inter-application Synchronization and MIDI in ReWire


ReWire supports sending synchronization, transport, and tempo information both to and from ReWire Devices. The
hostsync~, hostphasor~, and hostcontrol~ MSP objects can work with the ad_rewire driver to provide this information
and to control the host's transport. See the MSP Reference Manual pages of these objects for more information.

Rewire 2 also supports MIDI communication to and from ReWire Devices. Currently both the rewire~ object and the
ad_rewire driver support MIDI, although they work in different ways. To send and receive midi using the rewire~ object,
you send message to and receive messages directly from the object. See the MSP Reference Manual pages for the rewire~
object for more information.

The ad_rewire MIDI support is more integrated into the Max MIDI system -- Max MIDI ports are created so you can use the
standard Max MIDI objects to send and receive MIDI via the ad_rewire driver. After you choose the ad_rewire driver in the
Audio Status Window, MIDI ports will appear in the MIDI Setup window the next time it is opened. The number of midi
ports dedicated to ReWire can be changed using the MIDI Ports option in the Audio Status Window.

For example, you can choose one of the Max ReWire MIDI ports as a MIDI output device in Cubase and then use standard
Max MIDI objects (such as notein) to control your Max created synthesizer. Likewise, you can send MIDI into Cubase using
the max MIDI objects and the ReWire MIDI ports, and recorded the results to a track for further manipulation or playback.

Advanced ad_rewire Features


When you build a standalone application using Max you can use the ad_rewire driver in your standalone and it will create an
ReWire Device that works independently of Max and other Max-created standalone applications. By default, the ReWire
Device will take on the name of your application and will have 16 channels. You can customize this by editing the
msprewire.config file in the support/ad folder for your standalone. Note: This file doesn't exist until the default one is
created the first time you launch your standalone and choose ad_rewire in the Audio Status window.

The msprewire.config file is located in the ad folder found in the following locations:

Macintosh: Library/Application Support/Cycling 74/ad/

Windows: c:\Program Files\Common Files\Cycling '74\ad\

In a Max-built standalone this is in the standalone's support/ad/ folder. The msprewire.config contains two lines that specify
the name that ReWire will use for the device and the number of audio channels. You can edit this to change the behavior of
Max or your standalone.

Using ASIO on Windows


Selecting an ASIO driver from the Audio Status window allows MSP to talk directly to an audio interface. To use ASIO
soundcards your device needs to be correctly installed and connected; The MSP ASIO driver will find it at startup.
All correctly installed ASIO devices should be available to you for selection in the Audio Status window. However, MSP does
not check to see if the relevant audio interface hardware is installed correctly on your system until you explicitly switch to
the ASIO driver for that interface card. If an ASIO driver fails to load when you try to use it, an error message will appear in
the Max window (typically, an initialization error with a code of 1000) and the menus in the rest of the Audio Status
window will blank out. Switching to the MME and/or DirectSound driver will re-enable MSP audio.

The Clock Source pop-up menu lets you to set the clock source for your audio hardware. Some ASIO drivers do not support
an external clock; if this is the case there will only be one option in the menu, typically labeled Internal.

The Prioritize MIDI pop-up menu allows you to set the clock source for your audio hardware and whether or not to prioritize
MIDI input and output over audio I/O.

Many ASIO drivers have other settings you can edit in a separate window. Click the Open ASIO Control Panel button at the
bottom of the Audio Status window to access these settings. If your interface card has a control panel in its ASIO driver, the
documentation for the interface should cover its operation.

Controlling ASIO Drivers with Messages to the dsp Object on Windows


Version 2 of the ASIO specification allows for direct monitoring of inputs to an audio interface. In other words, you can
patch audio inputs to the interface directly to audio outputs without having the signals go through your computer. You also
have control over channel patching, volume, and pan settings.

To control direct monitoring, you send the monitor message to the dsp object. The monitor message takes the following
arguments

int Obligatory. A number specifying an input channel number (starting at 1)

int Optional. A number specifying an outlet channel number, or 0 to turn the routing for the specified input channel off. This
is also what happens if the second argument is not present.

int or float Optional. A number specifying the gain of the input -> output connection, between 0 and 4. 1 represents unity
gain (and is the default).

int or float Optional. A number specifying the panning of the output channel. -1 is left, 0 is center, and 1 is right. 0 is the
default.

Here are some examples of the monitor message:

; dsp driver monitor 1 1 Patches input 1 to output 1 at unity gain with center pan.

; dsp driver monitor 1 0Turns off input 1

; dsp driver monitor 1 4 2. -1. patches input 1 to output 4 with 6dB gain panned to the left

Note: When using these messages, the word driver is optional but recommended. Not all ASIO drivers support this feature.
If you send the monitor message and get an ASIO result error -998 message in the Max window, then the driver does not
support it.

Another feature of ASIO 2 is the ability to start, stop, and read timecode messages. To start timecode reading, send the
following message:

; dsp driver timecode 1

To stop timecode reading, send the following message:


; dsp driver timecode 0

The plugsync~ object reports the sample position reported by the audio interface when you enable timecode, but there isn't
currently an object that reports the timecode of the interface.

Working in Non-Real Time with MSP


The MSP ad_nonreal driver allows you to use MSP for synthesis and signal processing without worrying about the
constraints imposed by the speed of your computer's CPU. Non-real-time mode simply calculates samples in MSP
independently of any physical scheduling priority, allowing you to process a vector of audio using a signal path that might
take your computer more than one vector's worth of real time to compute.

Typically, you will want to use the dsptime~ object to see how long the audio has been turned on, and you will pipe the
output of your routine to sfrecord~ to capture the results. Hardware audio input and output under the non-real-time driver
are disabled.

A typical non-real-time signal path in MSP would look something like this:

Starting the Audio (by toggling the dac~ object) will start the dsptime~ object at 0 samples, in sync with the playback of the
audio out of sfplay~ and the recording of audio into the sfrecord~ at the bottom of the patch. When five seconds have
elapsed, the sfrecord~ object will stop recording the output audio file.

See Also
Name Description
adc~ Audio input and on/off
adstatus Report and control audio driver settings
dac~ Audio output and on/off
ezadc~ Audio input and on/off button
ezdac~ Audio output and on/off button
Test Tone
Tutorial 1: Test Tone
Open the tutorial.

MSP objects are pretty much like Max objects


MSP objects are for processing digital audio (i.e., sound) to be played by your computer. MSP objects look just like Max
objects, have inlets and outlets just like Max objects, and are connected together with patch cords just like Max objects. They
are created the same way as Max objects just by placing an object box in the Patcher window and typing in the desired
name -- and they co-exist quite happily with Max objects in the same Patcher window.

...but they're a little different


A patch of interconnected MSP objects works a little differently from the way a patch of standard Max objects works.

One way to think of the difference is just to think of MSP objects as working much faster than ordinary Max objects. Since
MSP objects need to produce enough numbers to generate a high fidelity audio signal (commonly 44,100 numbers per
second), they must work faster than the millisecond schedule used by standard Max objects.

Here's another helpful way to think of the difference. Think of a patch of MSP objects not as a program in which events occur
at specific instants (as in a standard Max patch), but rather as a description of an instrument design -- a synthesizer,
sampler, or effect processor. It's like a mathematical formula, with each object constantly providing numerical values to the
object(s) connected to its outlet. At any given instant in time, this formula has a result, which is the instantaneous amplitude
of the audio signal. This is why we frequently refer to an ensemble of inter-connected MSP objects as a signal network.

So, whereas a patch made up of standard Max objects sits idle and does nothing until something occurs (a mouse click, an
incoming MIDI message, etc.) causing one object to send a message to another object, a signal network of MSP objects, by
contrast, is always active (from the time it's turned on to the time it's turned off), with all its objects constantly
communicating to calculate the appropriate amplitude for the sound at that instant.

...so they look a little different


The names of all MSP objects end with the tilde character (~). This character, which looks like a cycle of a sine wave, just
serves as an indicator to help you distinguish MSP objects from other Max objects.

The patch cords between MSP objects have stripes. This helps you distinguish the MSP signal network from the rest of the
Max patch.

MSP objects are connected by striped patch cords

Digital-to-analog converter: dac~


The digital-to-analog converter (DAC) is the part of your computer that translates the stream of discrete numbers in a
digital audio signal into a continuous fluctuating voltage which will drive your loudspeaker.

Once you have calculated a digital signal to make a computer-generated sound, you must send the numbers to the DAC. So,
MSP has an object called dac~, which generally is the terminal object in any signal network. It receives, as its input, the
signal you wish to hear. It has as many inlets as there are available channels of audio playback. If you are using Core Audio
(or MME on Windows) to play sounds directly from your computer's audio hardware, there are two output channels, so
there will be two inlets to dac~. (If you are using more elaborate audio output hardware, you can type in an argument to
specify other audio channels.)
dac~ plays the signal

Important! dac~ must be receiving a signal of non-zero amplitude in order for you to hear anything. dac~ expects to
receive signal values in the range -1.0 to 1.0. Numbers that exceed that range will cause distortion when the sound is played.

Wavetable synthesis: cycle~


The best way to produce a periodic waveform is with cycle~. This object uses the technique known as wavetable synthesis.
It reads through a list of 512 values at a specified rate, looping back to the beginning of the list when it reaches the end. This
simulates a periodically repeating waveform.

You can direct cycle~ to read from a list of values that you supply (in the form of an audio file), or if you don't supply one, it
will read through its own table which represents a cycle of a cosine wave with an amplitude of 1. We'll show you how to
supply your own waveform in Tutorial 3. For now we'll use the cosine waveform.

Graph of 512 numbers describing one cycle of a cosine wave with amplitude 1

cycle~ receives a frequency value (in Hz) in its left inlet, and it determines on its own how fast it should read through the list
in order to send out a signal with the desired frequency.

Technical detail: To figure out how far to step through the list for each consecutive sample, cycle~ uses the basic
formula

I=L/R

where I is the amount to increment through the list, is the signal's frequency, L is the length of the list (512 in this
case), and R is the audio sampling rate. cycle~ is an interpolating oscillator, which means that if I does not land
exactly on an integer index in the list for a given sample, cycle~ interpolates between the two closest numbers in the
list to find the proper output value. Performing interpolation in a wavetable oscillator makes a substantial
improvement in audio quality. The cycle~ object uses linear interpolation, while other MSP objects use very high-
quality (and more computationally expensive) polynomial interpolation.

By default cycle~ has a frequency of 0 Hz. So in order to hear the signal, we need to supply an audible frequency value. This
can be done with a number argument as in the example patch, or by sending a number in the left inlet, or by connecting
another MSP object to the left inlet.

Starting and stopping signal processing


The way to turn audio on and off is by sending the Max messages start and stop (or 1 and 0) to the left inlet of a dac~
object (or an adc~ object, discussed in a later chapter). Sending start or stop to any dac~ or adc~ object enables or disables
processing for all signal networks.

The simplest possible signal network

Although dac~ is part of a signal network, it also understands certain Max messages, such as start and stop. Many of the
MSP objects function in this manner, accepting certain Max messages as well as audio signals.

Listening to the Test Tone


The first time you start up Max, it will try to use your computer's default sound card and driver (Core Audio on Macintosh or
MME on Windows) for audio input and output. If you have the audio output of your computer connected to headphones or
an amplifier, you should hear the output of MSP through it. If you don't have an audio cable connected to your computer,
you'll hear the sound through the computer's internal speaker.

In order to get MSP up and running properly, we recommend that you start the tutorials using your computer's built-in
sound hardware. If you want to use an external audio interface or sound care, please refer to the Audio Input and Output
chapter for details on configuring MSP to work with audio hardware.

Set your audio amplifier (or amplified speakers) to their minimum setting, then click on the start message box. Adjust your
audio amplifier to the desired maximum setting, then click on the stop message box to turn off that annoying test tone.

Troubleshooting
If you don't hear any sound coming from your computer when you start the dac~ in this example, check the level setting on
your amplifier or mixer, and check all your audio connections. Check that the sound output isn't currently muted. On
Macintosh, the sound output level is set using the Sound preferences in the System Preferences application. On Windows,
the sound output level is set using the Sounds and Audio Devices setup (Start - Control Panels - Sounds and Audio Devices).

If you are still are not hearing anything, choose Audio Status from the Options Menu and verify that Core Audio Built in
Controller for Macintosh or MME driver for Windows is selected in the Driver pop-up menu. If it isn't, choose it.

Summary
A signal network of connected MSP objects describes an audio instrument. The digital-to-analog converter of the instrument
is represented by the dac~ object; dac~ must be receiving a signal of non-zero amplitude (in the range -1.0 to 1.0) in order
for you to hear anything. The cycle~ object is a wavetable oscillator which reads cyclically through a list of 512 amplitude
values, at a rate determined by the supplied frequency value. Signal processing is turned on and off by sending a start or
stop message to any dac~ or adc~ object.
Close the Patcher window before proceeding to the next chapter.

See Also
Name Description
cycle~ Sinusoidal oscillator
dac~ Audio output and on/off
MSP: Audio Input and Output MSP: Audio Input and Output
Adjustable Oscillator
Tutorial 2: Adjustable Oscillator
Open the tutorial.

Amplifier: *~
A signal you want to listen to -- a signal you send to dac~ -- must be in the amplitude range from -1.0 to +1.0. Any values
exceeding those bounds will be clipped off by dac~ (i.e. sharply limited to 1 or -1). This will cause (in most cases pretty
objectionable) distortion of the sound. Some objects, such as cycle~, output values in that same range by default.

The default output of cycle~ has amplitude of 1

To control the level of a signal you simply multiply each sample by a scaling factor. For example, to halve the amplitude of a
signal you simply multiply it by 0.5. (Although it would be mathematically equivalent to divide the amplitude of the signal by
2, multiplication is a more efficient computation procedure than division.

Amplitude adjusted by multiplication

If we wish to change the amplitude of a signal continuously over time, we can supply a changing signal in the right inlet of
*~. By continuously changing the value in the right inlet of *~, we can fade the sound in or out, create a crescendo or
diminuendo effect, etc.

However, a sudden drastic change in amplitude would cause a discontinuity in the signal, which would be heard as a noisy
click.

Instantaneous change of amplitude causes a noisy distortion of the signal

For that reason it's usually better to modify the amplitude using a signal that changes more gradually with each sample, say
in a straight line over the course of several milliseconds.

Line segment generator: line~


If, instead of an instantaneous change of amplitude (which can cause an objectionable distortion of the signal), we supply a
signal in the right inlet of *~ that changes from 1.0 to 0.5 over the course of 5 milliseconds, we interpolate between the
starting amplitude and the target amplitude with each sample, creating a smooth amplitude change.
Linear amplitude change over 5 milliseconds using line~

The line~ object functions similarly to the Max object line. In its left inlet it receives a target value and a time (in ms) to
reach that target. line~ calculates the proper intermediate value for each sample in order to change in a straight line from its
current value to the target value.

Technical detail: Any change in the over-all amplitude of a signal introduces some amount of distortion during the
time when the amplitude is changing. (The shape of the waveform is actually changed during that time, compared with
the original signal.) Whether this distortion is objectionable depends on how sudden the change is, how great the
change in amplitude is, and how complex the original signal is. A small amount of such distortion introduced into an
already complex signal may go largely unnoticed by the listener. Conversely, even a slight distortion of a very pure
original signal will add partials to the tone, thus changing its timbre.

In the preceding example, the amplitude of a sinusoidal tone decreased by half (6 dB) in 5 milliseconds. Although one
might detect a slight change of timbre as the amplitude drops, the shift is not drastic enough to be heard as a click. If,
on the other hand, the amplitude of a sinusoid increases eightfold (18 dB) in 5 ms, the change is drastic enough to be
heard as a percussive attack.

An eightfold (18 dB) increase in 5 ms creates a percussive effect

Adjustable oscillator
The example patch uses this combination of *~ and line~ to make an adjustable amplifier for scaling the amplitude of the
oscillator. The pack object appends a transition time to the target amplitude value, so every change of amplitude will take
100 milliseconds. A number box for changing the frequency of the oscillator has also been included.

Oscillator with adjustable frequency and amplitude

Notice that the signal network already has default values before any Max message is sent to it. The cycle~ object has a
specified frequency of 1000 Hz, and the line~ object has a default initial value of 0. Even if the *~ had a typed-in argument
for initializing its right inlet, its right operand would still be 0 because line~ is constantly supplying it that value.
Use the Amplitude number box to set the volume to the level you desire, then click on the toggle marked Audio On/Off
to start the sound. Use the number box objects to change the frequency and amplitude of the tone. Click on the toggle
again to turn the sound off.

Fade In and Fade Out


The combination of line~ and *~ also helps to avoid the clicks that can occur when the audio is turned on and off. The 1 and
0 on and off messages from the toggle are used to fade the volume up to the desired amplitude, or down to 0, just as the
start or stop message is sent to dac~. In that way, the sound is faded in and out gently rather than being turned on
instantaneously.

On and off messages fade audio in or out before starting or stopping the DAC

Just before turning audio off, the 0 from toggle is sent to the pack object to start a 100 ms fade-out of the oscillator's
volume. A delay of 100 ms is also introduced before sending the stop message to dac~, in order to let the fade-out occur.
Just before turning the audio on, the desired amplitude value is triggered, beginning a fade-in of the volume; the fade-in
does not actually begin, however, until the dac~ is started -- immediately after, in this case. (In an actual program, the start
and stop message boxes might be hidden from view or encapsulated in a subpatch in order to prevent the user from
clicking on them directly.)

Summary
Multiplying each sample of an audio signal by some number other than 1 changes its amplitude; therefore the *~ object is
effectively an amplifier. A sudden drastic change of amplitude can cause a click, so a more gradual fade of amplitude -- by
controlling the amplitude with another signal -- is usually advisable. The line segment signal generator line~ is comparable
to the Max object line and is appropriate for providing a linearly changing value to the signal network. The combination of
line~ and *~ can be used to make an envelope for controlling the over-all amplitude of a signal.

See Also
Name Description
cycle~ Sinusoidal oscillator
dac~ Audio output and on/off
line~ Linear ramp generator
Wavetable Oscillator
Tutorial 3: Wavetable Oscillator
Open the tutorial.

Audio on/off switch: ezdac~


In this tutorial patch, the dac~ object which was used in earlier examples has been replaced by a button with a speaker icon.
This is the ezdac~ object, a user interface object available in the object palette.

ezdac~ is an on/off button for audio, available in the object palette

The ezdac~ works much like dac~, except that clicking on it turns the audio on or off. It can also respond to start and stop
messages in its left inlet, like dac~. (Unlike dac~, however, it is appropriate only for output channels 1 and 2.) The ezdac~
button is highlighted when audio is on.

A stored sound: buffer~


In the previous examples, the cycle~ object was used to read repeatedly through 512 values describing a cycle of a cosine
wave. In fact, though, cycle~ can read through any 512 values, treating them as a single cycle of a waveform. These 512
numbers must be stored in an object called buffer~. (A buffer means a holding place for data.)
A buffer~ object requires a unique name typed in as an argument. A cycle~ object can then be made to read from that
buffer by typing the same name in as its argument. (The initial frequency value for cycle~, just before the buffer name, is
optional.)

cycle~ reads its waveform from a buffer~ of the same name

To get the sound into the buffer~, send it a read message. That opens an Open Document dialog box, allowing you to select
an audio file to load. The word read can optionally be followed by a specific file name, to read a file in without selecting it
from the dialog box, provided that the audio file is in Max's search path.

Read in a specific sound immediately


Regardless of the length of the sound in the buffer~, cycle~ uses only 512 samples from it for its waveform. (You can specify
a starting point in the buffer~ for cycle~ to begin its waveform, either with an additional argument to cycle~ or with a set
message to cycle~.) In the example patch, we use an audio file that contains exactly 512 samples.

Technical detail: In fact, cycle~ uses 513 samples. The 513th sample is used only for interpolation from the 512th
sample. When cycle~ is being used to create a periodic waveform, as in this example patch, the 513th sample should be
the same as the 1st sample. If the buffer~ contains only 512 samples, as in this example, cycle~ supplies a 513th
sample that is the same as the 1st sample.

Click on the message box that says read gtr512.aiff. This loads in the audio file. Then click on the ezdac~ object to turn
the audio on. (There will be no sound at first. Can you explain why?) Next, click on the message box marked B3 to listen to
1 second of the cycle~ object.
There are several other objects that can use the data in a buffer~, as you will see in later chapters.

Create a breakpoint line segment function with line~


In the previous example patch, we used line~ to make a linearly changing signal by sending it a list of two numbers. The first
number in the list was a target value and the second was the amount of time, in milliseconds, for line~ to arrive at the target
value.

line~ is given a target value (1.) and an amount of time to get there (100 ms)

If we want to, we can send line~ a longer list containing many value-time pairs of numbers (up to 64 pairs of numbers). In
this way, we can make line~ perform a more elaborate function composed of many adjoining line segments. After
completing the first line segment, line~ proceeds immediately toward the next target value in the list, taking the specified
amount of time to get there.

A function made up of line segments

Synthesizer users are familiar with using this type of function to generate an ADSR amplitude envelope. That is what we're
doing in this example patch, although we can choose how many line segments we wish to use for the envelope.

Other signal generators: phasor~ and noise~


The phasor~ object produces a signal that ramps repeatedly from 0 to 1.

Signal produced by phasor~

The frequency with which it repeats this ramp can be specified as an argument or can be provided in the left inlet, in Hertz,
just as with cycle~. This type of function is useful at sub-audio frequencies to generate periodically recurring events (a
crescendo, a filter sweep, etc.). At a sufficiently high frequency, of course, it is audible as a sawtooth waveform.

In the example patch, the phasor~ is pitched an octave above cycle~, and its output is scaled and offset so that it ramps
from -1 to +1.

220 Hz sawtooth wave

Technical detail: A sawtooth waveform produces a harmonic spectrum, with the amplitude of each harmonic
inversely proportional to the harmonic number. Thus, if the waveform has amplitude A, the fundamental (first
harmonic) has amplitude A, the second harmonic has amplitude A/ 2, the third harmonic has amplitude A/3, etc.

The noise~ object produces white noise: a signal that consists of a completely random stream of samples. In this example
patch, it is used to add a short burst of noise to the attack of a composite sound.

Click on the message box marked B1 to hear white noise. Click on the message box marked B2 to hear a sawtooth wave.

Add signals to produce a composite sound


Any time two or more signals are connected to the same signal inlet, those signals are added together and their sum is used
by the receiving object.

Multiple signals are added (mixed) in a signal inlet

Addition of digital signals is equivalent to unity gain mixing in analog audio. It is important to note that even if all your
signals have amplitude less than or equal to 1, the sum of such signals can easily exceed 1. In MSP it's fine to have a signal
with an amplitude that exceeds 1, but before sending the signal to dac~ you must scale it (usually with a *~ object) to keep
its amplitude less than or equal to 1. A signal with amplitude greater than 1 will be distorted by dac~.
In the example patch, white noise, a 220 Hz sawtooth wave, and a 110 Hz tone using the waveform in buffer~ are all mixed
together to produce a composite instrument sound.
Three signals mixed to make a composite instrument sound

Each of the three tones has a different amplitude envelope, causing the timbre of the note to evolve over the course of its 1-
second duration. The three tones combine to form a note that begins with noise, quickly becomes electric-guitar-like, and
gets a boost in its overtones from the sawtooth wave toward the end. Even though the three signals crossfade, their
amplitudes are such that there is no possibility of clipping (except, possibly, in the very earliest milliseconds of the note,
which are very noisy anyway).

Click on the button to play all three signals simultaneously. To hear each of the individual parts that comprise the note,
click on the message boxes marked A1, A2, and A3. If you want to hear how each of the three signals sound sustained at full
volume, click on the message boxes marked B1, B2, and B3. When you have finished, click on ezdac~ to turn the audio off.

Summary
The ezdac~ object is a button for switching the audio on and off. The buffer~ object stores a sound. You can load an audio
file into buffer~ with a read message, which opens an Open Document dialog box for choosing the file to load in. If a cycle~
object has a typed-in argument which gives it the same name as a buffer~ object has, the cycle~ will use 512 samples from
that buffered sound as its waveform, instead of the default cosine wave.

The phasor~ object generates a signal that increases linearly from 0 to 1. This ramp from 0 to 1 can be generated repeatedly
at a specific frequency to produce a sawtooth wave. For generating white noise, the noise~ object sends out a signal
consisting of random samples.

Whenever you connect more than one signal to a given signal inlet, the receiving object adds those signals together and uses
the sum as its input in that inlet. Exercise care when mixing (adding) audio signals, to avoid distortion caused by sending a
signal with amplitude greater than 1 to the DAC; signals must be kept in the range -1 to +1 when sent to dac~ or ezdac~.
The line~ object can receive a list in its left inlet that consists of up to 64 pairs of numbers representing target values and
transition times. It will produce a signal that changes linearly from one target value to another in the specified amounts of
time. This can be used to make a function of line segments describing any shape desired, which is particularly useful as a
control signal for amplitude envelopes. You can achieve crossfades between signals by using different amplitude envelopes
from different line~ objects.

See Also
Name Description
buffer~ Store audio samples
ezdac~ Audio output and on/off button
phasor~ Generate sawtooth signals
noise~ Generate white noise
Routing Signals
Tutorial 4: Routing Signals
Open the tutorial.

Remote signal connections: send~ and receive~


The patch cords that connect MSP objects look different from normal patch cords because they actually do something
different. They describe the order of calculations in a signal network. The connected objects will be used to calculate a whole
block of samples for the next portion of sound.

Max objects can communicate remotely, without patch cords, with the objects send and receive (and some similar objects
such as value and pv). You can transmit MSP signals remotely with send and receive, too, but the patch cord(s) coming out
of receive will not have the yellow-and-black striped appearance of the signal network (because a receive object doesn't
know in advance what kind of message it will receive). Two MSP objects exist specifically for remote transmission of signals:
send~ and receive~.

send and receive for Max messages; send~ and receive~ for signals

The two objects send~ and receive~ work very similarly to send and receive, but are only for use with MSP objects. Max
will allow you to connect normal patch cords to send~ and receive~, but only signals will get passed through send~ to the
corresponding receive~. The MSP objects send~ and receive~ don't transmit any Max messages besides signals.
There are a few other important differences between the Max objects send and receive and the MSP objects send~ and
receive~.

1. The names of send and receive can be shortened to s and r; the names of send~ and receive~ cannot be shortened in
the same way.

2. A Max message can be sent to a receive object from several other objects besides send, such as float, forward, grab, if,
int, and message; receive~ can receive a signal only from a send~ object that shares the same name.

3. If receive has no typed-in argument, it has an inlet for receiving set messages to set or change its name; receive~ also
has an inlet for that purpose, but is nevertheless required to have a typed-in argument.

4. Changing the name of a receive~ object with a set message is a useful way of dynamically redirecting audio signals.
Changing the name of receive~, however, does not redirect the signal until you turn audio off and back on again.
Examples of each of these usages can be seen in the tutorial patch.

Routing a signal: gate~


The MSP object gate~ works very similarly to the Max object gate. Just as gate is used to direct messages to one of several
destinations, or to shut the flow of messages off entirely, gate~ directs a signal to different places, or shuts it off from the
rest of the signal network.

In the example patch, the gate~ objects are used to route signals to the left audio output, the right audio output, both, or
neither, according to what number is received from the umenu object.
gate~ sends a signal to a chosen location

It is worth noting that changing the chosen outlet of a gate~ while an audio signal is playing through it can cause an audible
click because the signal shifts abruptly from one outlet to another. To avoid this, you should generally design your patch in
such a way that the gate~ object's outlet will only be changed when the audio signal going through it is at zero or when
audio is off. (No such precaution was taken in the tutorial patch.)

Wave interference
It's a fundamental physical fact that when we add together two sinusoidal waves with different frequencies we create
interference between the two waves. Since they have different frequencies, they will usually not be exactly in phase with each
other; so, at some times they will be sufficiently in phase that they add together constructively, but at other times they add
together destructively, canceling each other out to some extent. They only arrive precisely in phase with each other at a rate
equal to the difference in their frequencies. For example, a sinusoid at 1000 Hz and another at 1002 Hz come into phase
exactly 2 times per second. In this case, they are sufficiently close in frequency that we don't hear them as two separate
tones. Instead, we hear their recurring pattern of constructive and destructive interference as beats occurring at a sub-audio
rate of 2 Hz, a rate known as the difference frequency or beat frequency. (Interestingly, we hear the two waves as a single
tone with a sub-audio beat frequency of 2 Hz and an audio frequency of 1001 Hz.)

When the example patch is opened, a loadbang object sends initial frequency values to the cycle~ objects1000 Hz and
1002 Hzso we expect that these two tones sounded together will cause a beat frequency of 2 Hz. It also sends initial values
to the gate~ objects (passing through the umenus on the way) which will direct one tone to the left audio output and one to
the right audio output.

The two waves interfere at a rate of 2 Hz

Click on ezdac~ to turn audio on, then use the slider marked Volume to adjust the loudness of the sound to a
comfortable level. Note that the beats occur exactly twice per second. Try changing the frequency of Oscillator B to various
other numbers close to 1000, and note the effect. As the difference frequency approaches an audio rate (say, in the range of
20-30 Hz) you can no longer distinguish individual beats, and the effect becomes more of a timbral change. Increase the
difference still further, and you begin to hear two distinct frequencies.

Philosophical tangent: It can be shown mathematically and empirically that when two sinusoidal tones are added, their
interference pattern recurs at a rate equal to the difference in their frequencies. This apparently explains why we hear beats;
the amplitude demonstrably varies at the difference rate. However, if you listen to this patch through headphonesso that
the two tones never have an opportunity to interfere mathematically, electrically, or in the airyou still hear the beats! This
phenomenon, known as binaural beats is caused by interference occurring in the nervous system. Although such
interference is of a very different physical nature than the interference of sound waves in the air, we experience it as similar.
An experiment like this demonstrates that our auditory system actively shapes the world we hear.

Amplitude and relative amplitude


The slider marked Volume has been set to have a range of 101 values, from 0 to 100, which makes it easy to convert its
output to a float ranging from 0 to 1 just by dividing by 100. (The decimal point in argument typed into the / object ensures
a float division.)

A volume fader is made by converting the int output of slider to a float from 0. to 1.

The *~ objects use the specified amplitude value to scale the audio signal before it goes to the ezdac~. If both oscillators get
sent to the same inlet of ezdac~, their combined amplitude will be 2. Therefore, it is prudent to keep the amplitude scaling
factor at or below 0.5. For that reason, the amplitude valuewhich the user thinks of as being between 0 and 1is actually
kept between 0 and 0.5 by the * 0.5 object.

The amplitude is halved in case both oscillators are going to the same output channel

Because of the wide range of possible audible amplitudes, it may be more meaningful in some cases to display volume
numerically in terms of the logarithmic scale of decibels (dB), rather than in terms of absolute amplitude. The decibel scale
refers to relative amplitudethe amplitude of a signal relative to some reference amplitude. The formula for calculating
amplitude in decibels is

dB = 20(log10(A/Aref))

where A is the amplitude being measured and Aref is a fixed reference amplitude.

The subpatch AtodB uses a reference amplitude of 1 in the formula shown above, and converts the amplitude to dB.

The contents of the subpatch AtodB

Since the amplitude received from the slider will always be less than or equal to 1, the output of AtodB will always be less
than or equal to 0 dB. Each halving of the amplitude is approximately equal to a 6 dB reduction.
AtodB reports amplitude in dB, relative to a reference amplitude of 1

Change the position of the slider and compare the linear amplitude reading to the logarithmic decibel scale reading.

Constant signal value: sig~


Most signal networks require some changing values (such as an amplitude envelope to vary the amplitude over time) and
some constant values (such as a frequency value to keep an oscillator at a steady pitch). In general, one provides a constant
value to an MSP object in the form of a float message, as we have done in these examples when sending a frequency in the
left inlet of a cycle~ object.
However, there are some cases when one wants to combine both constant and changing values in the same inlet of an MSP
object. Most inlets that accept either a float or a signal (such as the left inlet of cycle~) do not successfully combine the two.

For example, cycle~ ignores a float in its left inlet if it is receiving a signal in the same inlet.

cycle~ ignores its argument or a float input when a signal is connected to the left inlet

One way to combine a numerical Max message (an int or a float) with a signal is to convert the number into a steady signal
with the sig~ object. The output of sig~ is a signal with a constant value, determined by the number received in its inlet.

sig~ converts a float to a signal so it can be combined with another signal

In the example patch, Oscillator B combines a constant frequency (supplied as a float to sig~) with a varying frequency
offset (an additional signal value). The sum of these two signals will be the frequency of the oscillator at any given instant.

Changing the phase of a waveform


For the most part, the phase offset of an isolated audio wave doesn't have a substantial effect perceptually. For example, a
sine wave in the audio range sounds exactly like a cosine wave, even though there is a theoretical phase difference of a
quarter cycle. For that reason, we have not been concerned with the rightmost phase inlet of cycle~ until now.
A sine wave offset by a quarter cycle is a cosine wave

However, there are some very useful reasons to control the phase offset of a wave. For example, by leaving the frequency of
cycle~ at 0, and continuously increasing its phase offset, you can change its instantaneous value (just as if it had a positive
frequency). The phase offset of a sinusoid is usually referred to in degrees (a full cycle is 360) or radians (a full cycle is 2
radians). In the cycle~ object, phase is referred to in wave cycles; so an offset of radians is 1/ 2 cycle, or 0.5. In other
words, as the phase varies from 0 to 2 radians, it varies from 0 to 1 wave cycles. This way of describing the phase is handy
since it allows us to use the common signal range from 0 to 1.

So, if we vary the phase offset of a stationary (0 Hz) cycle~ continuously from 0 to 1 over the course of one second, the
resulting output is a cosine wave with a frequency of 1 Hz.

The resulting output is a cosine wave with a frequency of 1 Hz

Incidentally, this shows us how the phasor~ object got its name. It is ideally suited for continuously changing the phase of a
cycle~ object, because it progresses repeatedly from 0 to 1. If a phasor~ is connected to the phase inlet of a 0 Hz cycle~,
the frequency of the phasor~ will determine the rate at which the cycle~ object's waveform is traversed, thus determining
the effective frequency of the cycle~.

The effective frequency of the 0 Hz cycle~ is equal to the rate of the phasor~

The important point demonstrated by the tutorial patch, however, is that the phase inlet can be used to read through the 512
samples of cycle~ object's waveform at any desired rate. (In fact, the contents of cycle~ can be scanned at will with any
value in the range 0 to 1.) In this case, line~ is used to change the phase of cycle~ from .75 to 1.75 over the course of 10
seconds.

The result is one cycle of a sine wave. The sine wave is multiplied by a depth factor to scale its amplitude up to 8. This sub-
audio sine wave, varying slowly from 0 up to 8, down to -8 and back to 0, is added to the frequency of Oscillator B. This
causes the frequency of Oscillator B to fluctuate very slowly between 1008 Hz and 992 Hz.
Click on the message box in the lower-left part of the window, and notice how the beat frequency varies sinusoidally over
the course of 10 seconds, from 0 Hz up to 8 Hz (as the frequency of Oscillator B approaches 1008 Hz), back to 0 Hz, back up
to 8 Hz (as the frequency of Oscillator B approaches 992 Hz), and back to 0 Hz.

Receiving a different signal


The remaining portion of the tutorial patch exists simply to demonstrate the use of the set message to the receive~ object.
This is another way to alter the signal flow in a network. With set, you can change the name of the receive~ object, which
causes receive~ to get its input from a different send~ object (or objects).

Giving receive~ a new name changes its input

Click on the message box containing set sawtooth. Both of the connected receive~ objects now get their signal from the
phasor~ in the lower-right corner of the window. Click on the message boxes containing set outL and set outR to receive
the sinusoidal tones once again. Click on ezdac~ to turn audio off.

Summary
It is possible to make signal connections without patch cords, using the MSP objects send~ and receive~, which are similar
to the Max objects send and receive. The setmessage can be used to change the name of a receive~ object, thus switching
it to receive its input from a different send~ object (or objects). Signal flow can be routed to different destinations, or shut
off entirely, using the gate~ object, which is the MSP equivalent of the Max object gate.
The cycle~ object can be used not only for periodic audio waves, but also for sub-audio control functions: you can read
through the waveform of a cycle~ object at any rate you wish, by keeping its frequency at 0 Hz and changing its phase
continuously from 0 to 1. The line~ object is appropriate for changing the phase of a cycle~ waveform in this way, and
phasor~ is also appropriate because it goes repeatedly from 0 to 1.

The sig~ object converts a number to a constant signal; it receives a number in its inlet and sends out a signal of that value.
This is useful for combining constant values with varying signals. Mixing together tones with slightly different frequencies
creates interference between waves, which can create beats and other timbral effects.

See Also
Name Description
gate~ Route a signal to one of several outlets
receive~ Signals can be received from any loaded patcher, without patch cords
send~ Send signals without patch cords
sig~ Convert numbers into audio signals
Turning Signals On and Off
Tutorial 5: Turning Signals On and Off
Open the tutorial.

Turning audio on and off selectively


So far we have seen two ways that audio processing can be turned on and off:

1. Send a start or stop message to a dac~, adc~, ezdac~, or ezadc~ object.

2, Click on a ezdac~ or ezadc~ object.

There are a couple of other ways we have not yet mentioned:

3. Send an int to a dac~, adc~, ezdac~, or ezadc~ object. 0 is the same as stop, and a non-zero number is the same as
start.

4. Double-click on a dac~ or adc~ object to open the Audio Status window, then use its Audio on/ off pop-up menu. You
can also choose Audio Status... from the Options menu to open the Audio Status window.

Any of those methods of starting MSP will turn the audio on in all open Patcher windows and their subpatches. There is also
a way to turn audio processing on and off in a single Patcher.

Sending the message startwindow -- instead of start -- to a dac~, adc~, ezdac~, or ezadc~ object turns the audio on only
in the Patcher window that contains that object, and in its subpatches. It turns audio off in all other Patchers. The
startwindow message is very useful because it allows you to have many different signal networks loaded in different
Patchers, yet turn audio on only in the Patcher that you want to hear. If you encapsulate different signal networks in separate
patches, you can have many of them loaded and available but only turn on one at a time, which helps avoid overtaxing your
computer's processing power. (Note that startwindow is used in all MSP help files so that you can try the help file's
demonstration without hearing your other work at the same time.)

In some cases startwindow is more appropriate than start

Selecting one of several signals: selector~


In the previous chapter, we saw the gate~ object used to route a signal to one of several possible destinations. Another useful
object for routing signals is selector~, which is comparable to the Max object switch. Several different signals can be sent
into selector~, but it will pass only one of them -- or none at all -- out its outlet. The left inlet of selector~ receives an int
specifying which of the other inlets should be opened. Only the signal coming in the opened inlet gets passed on out the
outlet.

The number in the left inlet determines which other inlet is open

As with gate~, switching signals with selector~ can cause a very abrupt change in the signal being sent out, resulting in
unwanted clicks. So if you want to avoid such clicks it's best to change the open inlet of selector~ only when audio is off or
when all of its input signal levels are 0.

In the tutorial patch, selector~ is used to choose one of four different classic synthesizer wave types: sine, sawtooth, triangle,
or square. The umenu contains the names of the wave types, and sends the correct number to the control inlet of selector~
to open the desired inlet.

Choose a wave type from the pop-up menu, then click on the startwindow message. Use the pop-up menu to listen to the
four different waves. Click on the stop message to turn audio off.

Technical detail: A sawtooth wave contains all harmonic partials, with the amplitude of each partial
proportional to the inverse of the harmonic number. If the fundamental (first harmonic) has
amplitude A, the second harmonic has amplitude A/2, the third harmonic has amplitude A/3, etc. A
square wave contains only odd numbered harmonics of a sawtooth spectrum. A triangle wave contains
only odd harmonics of the fundamental, with the amplitude of each partial proportional to the square
of the inverse of the harmonic number. If the fundamental has amplitude A, the third harmonic has
amplitude A/9, the fifth harmonic has amplitude A/25, etc.

Note that the waveforms in this patch are ideal shapes, not band-limited versions. That is to say, there is nothing limiting the
high frequency content of the tones. For the richer tones such as the sawtooth and pulse waves, the upper partials can easily
exceed the Nyquist rate and be folded back into the audible range. The partials that are folded over will not belong to the
intended spectrum, and the result will be an inharmonic spectrum. As a case in point, if we play an ideal square wave at
2,500 Hz, only the first four partials can be accurately represented with a sampling rate of 44.1 kHz. The frequencies of the
other partials exceed the Nyquist rate of 22,050 Hz, and they will be folded over back into the audible range at frequencies
that are not harmonically related to the fundamental. For example, the eighth partial (the 15th harmonic) has a frequency of
37,500 Hz, and will be folded over and heard as 6,600 Hz, a frequency that is not a harmonic of 2,500. (And its amplitude is
only about 24 dB less than that of the fundamental.) Other partials of the square wave will be similarly folded over.

Partials that exceed the Nyquist frequency are folded over

Choose the square wave from the pop-up menu, and set the frequency to 2500 Hz. Turn audio on. Notice that some of the
partials you hear are not harmonically related to the fundamental. If you move the frequency up further, the folded-over
partials will go down by the same amount. Turn audio off.

Turning off part of a signal network: begin~


You have seen that the selector~ and gate~ objects can be used to listen selectively to a particular part of the signal network.
The parts of the signal network that are being ignored for example, any parts of the network that are going into a closed
inlet of selector~ continue to run even though they have been effectively disconnected. That means MSP continues to
calculate all the numbers necessary for that part of the signal network, even though it has no effect on what you hear. This is
rather wasteful, computationally, and it would be preferable if one could actually shut down the processing for the parts of
the signal network that are not needed at a given time.

If the begin~ object is placed at the beginning of a portion of a signal network, and that portion goes to the inlet of a
selector~ or gate~ object, all calculations for that portion of the network will be completely shut down when the selector~
or gate~ is ignoring that signal. This is illustrated by comparing the sinusoid and sawtooth signals in the tutorial patch.
When the sinusoid is chosen, processing for the sawtooth is turned off entirely

When the first signal inlet of selector~ is chosen, as in the example shown above, the other signal inlets are ignored.
Calculations cease for all the objects between begin~ and selector~ in this case, the sig~, *~, and phasor~ objects. The
line~ object, because it is not in the chain of objects that starts with begin~, continues to run even while those other objects
are stopped.

Choose Sawtooth from the pop-up menu, set the frequency back to 440 Hz, and turn audio on. Click on the message
box above the line~ object. The line~ makes a glissando up an octave and back down over the course of ten seconds. Now
click on it again, let the glissando get underway for two seconds, then use the pop-up menu to switch the selector~ off. Wait
five seconds, then switch back to the sawtooth. The glissando is on its way back down, indicating that the line~ object
continued to work even though the sig~, *~, and phasor~ objects were shut down. When the glissando has finished, turn
audio off.

The combination of begin~ and selector~ (or gate~) can work perfectly well from one subpatch to another, as well.
Double-click on the patcher triangle object to view its contents.

Contents of the patcher triangle object

Here the begin~ object is inside a subpatch, and the selector~ is in the main patch, but the combination still works to stop
audio processing in the objects that are between them. There is no MSP object for making a triangle wave, so cycle~ reads a
single cycle of a triangle wave from an AIFF file loaded into a buffer~.
begin~ is really just an indicator of a portion of the signal network that will be disabled when selector~ turns it off. What
actually comes out of begin~ is a constant signal of 0, so begin~ can be used at any point in the signal network where a 0
signal is appropriate. It can either be added with some other signal in a signal inlet (in which case it adds nothing to that
signal), or it can be connected to an object that accepts but ignores signal input, such as sig~ or noise~.

Disabling audio in a Patcher: mute~ and pcontrol


You have seen that the startwindow message to dac~ turns audio on in a single Patcher and its subpatches, and turns audio
off in all other patches. There are also a couple of ways to turn audio off in a specific subpatch, while leaving audio on
elsewhere.

One way is to connect a mute~ object to the inlet of the subpatch you want to control.
Stopping audio processing in a specific subpatch

To mute a subpatch, connect a mute~ object to the inlet of the subpatch, as shown. When mute~ receives a non-zero int in
its inlet, it stops audio processing for all MSP objects in the subpatch. Sending 0 to mute~ object's inlet unmutes the
subpatch.

Choose Square from the pop-up menu, and turn audio on to hear the square wave. Click on the toggle above the mute~
object to disable the patcher pulsewave subpatch. Click on the same toggle again to unmute the subpatch.
This is similar to using the begin~ and selector~ objects, but the mute~ object disables the entire subpatch. (Also, the
syntax is a little different. Because of the verb mute, a non-zero int to mute~ has the effect of turning audio off, and 0 turns
audio on.)

In the tutorial example, it really is overkill to have the output of patcher pulsewave go to selector~ and to have a mute~
object to mute the subpatch. However, it's done here to show a distinction. The selector~ can cut off the flow of signal from
the patcher pulsewave subpatch, but the MSP objects in the subpatch continue to run (because there is no begin~ object at
its beginning). The mute~ object allows one to actually stop the processing in the subpatch, without using begin~ and
selector~.

Double-click on the patcher pulsewave object to see its contents.

Output is 1 for half the cycle, and 0 for half the cycle

To make a square wave oscillator, we simply send the output of phasor~ -- which goes from 0 to 1 -- into the inlet of <~ 0.5
(<~ is the MSP equivalent of the Max object <). For the first half of each wave cycle, the output of phasor~ is less than 0.5,
so the <~ object sends out 1. For the second half of the cycle, the output of phasor~ is greater than 0.5, so the <~ object
sends out 0.

The pass~ object between the <~ object and the outlet is necessary to avoid unwelcome noise when the subpatcher is muted.
It merely passes its input to its output unless the subpatcher is muted, when it outputs a zero signal. pass~ objects are
needed above any outlet of a patcher that might be muted.

Another way to disable the MSP objects in a subpatch is with the pcontrol object. Sending the message enable 0 to a
pcontrol object connected to a subpatch disables all MSP objects -- and all MIDI objects! -- in that subpatch. The message
enable 1 re-enables MIDI and audio objects in the subpatch.

pcontrol can disable and re-enable all MIDI and audio objects in a subpatch
The patcher harmonics subpatch contains a complete signal network that's essentially independent of the main patch. We
used pcontrol to disable that subpatch initially, so that it won't conflict with the sound coming from the signal network in
the main patch. (Notice that loadbang causes an enable 0 message to be sent to pcontrol when the main patch is loaded,
disabling the MSP objects in the subpatch.)

Turn audio off, click on the toggle above the patcher harmonics object to enable it, then double- click on the patcher
harmonics object to see its contents.

This subpatch combines 8 harmonically related sinusoids to create a complex tone in which the amplitude of each harmonic
(harmonic number n) is proportional to 1/ 2n. Because the tones are harmonically related, their sum is a periodic wave at the
fundamental frequency.

Wave produced by the patcher harmonics subpatch

The eight frequencies fuse together psychoacoustically and are heard as a single complex tone at the fundamental frequency.
It is interesting to note that even when the fundamental tone is removed, the sum of the other seven harmonics still implies
that fundamental, and we perceive only a loudness change and a timbral change but no change in pitch.

The same tone, minus its first harmonic, still has the same period

Click on the startwindow message to start audio in the subpatch. Try removing and replacing the fundamental frequency
by sending 0 and 1 to the selector~. Click on stop to turn audio off.

Summary
The startwindow message to dac~ (or adc~) starts audio processing in the Patcher window that contains the dac~, and in
any of that window's subpatches, but turns audio off in all other patches. The mute~ object, connected to an inlet of a
subpatch, can be used to disable all MSP objects in that subpatch. An enable 0 message to a pcontrol object connected to an
inlet of a subpatch can also be used to disable all MSP objects in that subpatch. (This disables all MIDI objects in the
subpatch, too.) The pass~ object silences the output of a subpatcher when it is muted.
You can use a selector~ object to choose one of several signals to be passed on out the outlet, or to close off the flow of all
the signals it receives. All MSP objects that are connected in a signal flow between the outlet of a begin~ object and an inlet
of a selector~ object (or a gate~ object) get completely disconnected from the signal network when that inlet is closed.
Any of these methods is an effective way to play selectively a subset of all the MSP objects in a given signal network (or to
select one of several different networks). You can have many signal networks loaded, but only enable one at a time; in this
way, you can switch quickly from one sound to another, but the computer only does processing that affects the sound you
hear.

See Also
Name Description
begin~ Define a switchable part of a signal network
mute~ Disable signal processing in a subpatch
pass~ Eliminate noise in a muted subpatcher
pcontrol Open and close subwindows
selector~ Assign one of several inputs to an outlet
A Review of Fundamentals
Tutorial 6: A Review of Fundamentals
Open the tutorial.

Exercises in the fundamentals of MSP


In this chapter, we suggest some tasks for you to program that will test your understanding of the fundamentals of MSP
presented in the Tutorial so far. A few hints are included to get you started. Try these three progressive exercises on your
own first, in new file of your own. Then check the example patch to see a possible solution, and read on in this chapter for an
explanation of the solution patch.

Exercise 1
Write a patch that plays the note E above middle C for one second, ten times in a row, with an electric guitar-like timbre.
Make it so that all you have to do is click once to turn audio on, and once to play the ten notes.

Here are a few hints:

1. The frequency of E above middle C is 329.627557 Hz.

2. For an electric guitar-like timbre you can use the AIFF file gtr512.aiff that was used in Tutorial 3. You'll need to read
that file into a buffer~ object, and access the buffer~ with a cycle~ object. In order to read the file in directly, without a
dialog box to find the file, your patch and the audio file should be saved in the same folder. You can either save your patch in
the MSP Tutorial folder or, in the Finder, option-drag a copy of the gtr512.aiff file into the folder where you have saved your
patch.

3. Your sound will also need an amplitude envelope that is characteristic of a guitar: very fast attack, fast decay, and fairly
steady (only slightly diminishing) sustain. Try using a list of line segments (target values and transition times) to a line~
object, and using the output of line~ to scale the amplitude of the cycle~.
4. To play the note ten times in a row, you'll need to trigger the amplitude envelope repeatedly at a steady rate. The Max
object metro is well suited for that task. To stop after ten notes, your patch should either count the notes or wait a specific
amount of time, then turn the metro off.

Exercise 2
Modify your first patch so that, over the course of the ten repeated notes, the electric guitar sound crossfades with a
sinusoidal tone a perfect 12th higher. Use a linear crossfade, with the amplitude of one sound going from 1 to 0, while the
other sound goes from 0 to 1. (We discuss other ways of crossfading in a future chapter.) Send the guitar tone to the left
audio output channel, and the sine tone to the right channel.

Hints:

1. You will need a second cycle~ object to produce the tone a 12th higher.
2. To obtain the frequency that's a (just tuned) perfect 12th above E, simply multiply 329.627557 times 3. The frequency
that's an equal tempered perfect 12th above E is 987.7666 Hz. Use whichever tuning you prefer.

3. In addition to the amplitude envelope for each note, you will need to change the over-all amplitude of each tone over the
course of the ten seconds. This can be achieved using an additional *~ object to scale the amplitude of each tone, slowly
changing the scaling factor from 1 to 0 for one tone, and from 0 to 1 for the other.

Exercise 3
Modify your second patch so that, over the course of the ten repeated notes, the two crossfading tones also perform an
over-all diminuendo, diminishing to 1/ 32 their original amplitude (i.e., by 30 dB).

Hints:

1. This will require yet another amplitude scaling factor (presumably another *~ object) to reduce the amplitude gradually
by a factor of .03125.

2. Note that if you scale the amplitude linearly from 1 to .03125 in ten seconds, the diminuendo will seem to start slowly
and accelerate toward the end. That's because the linear distance between 1 and .5 (a reduction in half) is much greater than
the linear distance between .0625 and .03125 (also a reduction in half). The first 6 dB of diminuendo will therefore occur in
the first 5.16 seconds, but the last 6 dB reduction will occur in the last .32 seconds. So, if you want the diminuendo to be
perceived as linear, you will have to adjust accordingly.

Solution to Exercise 1
Scroll the example Patcher window all the way to the right to see one possible solution to these exercises.

To make an oscillator with a guitar-like waveform, you need to read the audio file gtr512.aiff (or some similar waveform)
into a buffer~, and then refer to that buffer~ with a cycle~. (See Tutorial 3.)

cycle~ traverses the buffer~ 329.627533 times per second

Note that there is a limit to the precision with which Max can represent decimal numbers. When you save your patch, Max
may change float values slightly. In this case, you won't hear the difference.

If you want the audio file to be read into the buffer~ immediately when the patch is loaded, you can type the filename in as a
second argument in the buffer~ object, or you can use loadbang to trigger a read message to buffer~. In our solution we
also chose to provide the frequency from a number box -- which allows you to play other pitches -- rather than as an
argument to cycle~, so we also send cycle~ an initial frequency value with loadbang.

loadbang is used to initialize the contents of buffer~ and the frequency of cycle~

Now that we have an oscillator producing the desired tone, we need to provide an amplitude envelope to shape a note.

We chose the envelope shown below, composed of straight line segments. (See Tutorial 3.)

Guitar-like amplitude envelope

This amplitude envelope is imposed on the output of cycle~ with a combination of line~ and *~. A metro is used to trigger
the envelope once per second, and the metro gets turned off after a 10-second delay.
Ten guitar-like notes are played when the button is clicked

Solution to Exercise 2
For the right output channel we want a sinusoidal tone at three times the frequency (the third harmonic of the fundamental
tone), with the same amplitude envelope.

Two oscillators with the same amplitude envelope and related frequencies

To crossfade between the two tones, the amplitude of the first tone must go from 1 to 0 while the amplitude of the second
tone goes from 0 to 1. This can again be achieved with the combination of line~ and *~ for each tone.

Linear crossfade of two tones

We used a little trick to economize. Rather than use a separate line~ object to fade the second tone from 0 to 1, we just
subtract 1 from the output of the existing line~, which gives us a ramp from 0 to -1. Perceptually this will have the same
effect.

This crossfade is triggered (via s and r objects) by the same button that triggers the metro, so the crossfade starts at the
same time as the ten individual notes do.

Solution to Exercise 3
Finally, we need to use one more amplitude envelope to create a global diminuendo. The two tones go to yet another *~
object, controlled by another line~. As noted earlier, a straight line decrease in amplitude will not give the perception of
constant diminuendo in loudness.

Therefore, we used five line segments to simulate a curve that decreases by half every two seconds.
Global amplitude envelope decreasing by half every two seconds

This global amplitude envelope is inserted in the signal network to scale both tones down smoothly by a factor of .03125 over
10 seconds.

Both tones are scaled by the same global envelope


Additive Synthesis
Tutorial 7: Additive Synthesis
Open the tutorial.

In the tutorial examples up to this point we have synthesized sound using basic waveforms. In the next few chapters we'll
explore a few other well known synthesis techniques using sinusoidal waves. Most of these techniques are derived from pre-
computer analog synthesis methods, but they are nevertheless instructive and useful.

Combining tones
A sine wave contains energy at a single frequency. Since complex tones, by definition, are composed of energy at several (or
many) different frequencies, one obvious way to synthesize complex tones is to use multiple sine wave oscillators and add
them together.

Four sinusoids added together to make a complex tone

Of course, you can add any waveforms together to produce a composite tone, but we'll stick with sine waves in this tutorial
example. Synthesizing complex tones by adding sine waves is a somewhat tedious method, but it does give complete control
over the amplitude and frequency of each component (partial) of the complex tone.

In the tutorial patch, we add together six cosine oscillators (cycle~ objects), with independent control over the frequency,
amplitude, and phase of each one. In order to simplify the patch, we designed a subpatch called partial~ which allows us to
specify the frequency of each partial as a ratio relative to a fundamental frequency.

The contents of the subpatch partial~

For example, if we want a partial to have a frequency twice that of the fundamental we just type in 2.0 as an argument (or
send it in the second inlet). This way, if several partial~ subpatches are receiving their fundamental frequency value (in the
left inlet) from the same source, their relative frequencies will stay the same even when the value of the fundamental
frequency changes.

Of course, for the sound to be very interesting, the amplitudes of the partials must evolve with relative independence.
Therefore, in the main patch, we control the amplitude of each partial with its own envelope generator.

Envelope generator: function


In Tutorial 3 you saw how to create an amplitude envelope by sending a list of pairs of numbers to a line~ object, thus
giving it a succession of target values and transition times. This idea of creating a control function from a series of line
segments is useful in many contexts -- generating amplitude envelopes happens to be one particularly common usage -- and
it is demonstrated in Tutorial 6, as well.

The function object is a great help in generating such line segment functions, because it allows you to draw in the shape that
you want, as well as define the function's domain and range (the numerical value of its dimensions on the x and y axes). You
can draw a function simply by clicking with the mouse where you want each breakpoint to appear. When function receives a
bang, it sends a list of value-time pairs out its 2nd outlet. That list, when used as input to the line~ object, produces a
changing signal that corresponds to the shape drawn.

function is a graphic function generator for a control signal when used with line~

By the way, function is also useful for non-signal purposes in Max. It can be used as an interpolating lookup table. When it
receives a number in its inlet, it considers that number to be an x value and it looks up the corresponding y value in the
drawn function (interpolating between breakpoints as necessary) and sends it out the left outlet.

A variety of complex tones


Even with only six partials, one can make a variety of timbres ranging from realistic instrument- like tones to clearly
artificial combinations of frequencies. The settings for a few different tones have been stored in a preset object, for you to
try them out. A brief explanation of each tone is provided below.

Click on the ezdac~ speaker icon to turn audio on. Click on the button to play a tone. Click on one of the stored presets in
the preset object to change the settings, then click the button again to hear the new tone.
Preset 1. This tone is not really meant to emulate a real instrument. It's just a set of harmonically related partials, each one
of which has a different amplitude envelope. Notice how the timbre of the tone changes slightly over the course of its
duration as different partials come to the foreground. (If you can't really notice that change of timbre, try changing the note's
duration to something longer, such as 8000 milliseconds, to hear the note evolve more slowly.)

Preset 2. This tone sounds rather like a church organ. The partials are all octaves of the fundamental, the attack is
moderately fast but not percussive, and the amplitude of the tone does not diminish much over the course of the note. You
can see and hear that the upper partials die away more quickly than the lower ones.

Preset 3. This tone consists of slightly mistuned harmonic partials. The attack is immediate and the amplitude decays
rather rapidly after the initial attack, giving the note a percussive or plucked effect.

Preset 4. The amplitude envelopes for the partials in this tone are derived from an analysis of a trumpet note in the lower
register. Of course, these are only six of the many partials present in a real trumpet sound.

Preset 5. The amplitude envelopes for the partials of this tone are derived from the same trumpet analysis. However, in this
case, only the odd-numbered harmonics are used. This creates a tone more like a clarinet, because the cylindrical bore of a
clarinet resonates the odd harmonics. Also, the longer duration of this note slows down the entire envelope, giving it a more
characteristically clarinet-like attack.

Preset 6. This is a completely artificial tone. The lowest partial enters first, followed by the sixth partial a semitone higher.
Eventually the remaining partials enter, with frequencies that lie between the first and sixth partial, creating a microtonal
cluster. The beating effect is due to the interference between these waves of slightly different frequency.

Preset 7. In this case the partials are spaced a major second apart, and the amplitude of each partial rises and falls in such a
way as to create a composite effect of an arpeggiated whole-tone cluster. Although this is clearly a whole-tone chord rather
than a single tone, the gradual and overlapping attacks and decays cause the tones to fuse together fairly successfully.

Preset 8. In this tone the partials suggest a harmonic spectrum strongly enough that we still get a sense of a fundamental
pitch, but they are sufficiently mistuned that they resemble the inharmonic spectrum of a bell. The percussive attack, rapid
decay, and independently varying partials during the sustain portion of the note are also all characteristic of a struck metal
bell.
Notice that when you are adding several signals together like this, their sum will often exceed the amplitude limits of the
dac~ object, so the over-all amplitude must be scaled appropriately with a *~ object.

Experiment with complex tones


Using these tones as starting points, you may want to try designing your own tones with this additive synthesis patch. Vary
the tones by changing the fundamental frequency, partials, and duration of the preset tones. You can also change the
envelopes by dragging on the breakpoints.

To draw a function in the function object:


Click in the function object to create a new breakpoint. If you click and drag, the x and y coordinates of the point are
shown in the upper portion of the object, and you can immediately move the breakpoint to the position you want.

Similarly, you can click and drag on any existing breakpoint to move it.

Shift-click on an existing point to delete it.

Although not demonstrated in this tutorial, it is also possible to create, move, and delete breakpoints in a function just by
using Max messages. See the description of function in the Objects section of the manual for details.
The message setdomain, followed by a number, changes the scale of the x axis in the function without changing the shape
of the envelope. When you change the number in the Duration number box, it sends a setdomain message to the
function.

Summary
Additive synthesis is the process of synthesizing new complex tones by adding tones together. Since pure sine tones have
energy at only one frequency, they are the fundamental building blocks of additive synthesis, but of course any signals can be
added together. The sum signal may need to by scaled by some constant signal value less than 1 in order to keep it from
being clipped by the DAC.

In order for the timbre of a complex tone to remain the same when its pitch changes, each partial must maintain its
relationship to the fundamental frequency. Stating the frequency of each partial in terms of a ratio to (i.e., a multiplier of)
the fundamental frequency maintains the tone's spectrum even when the fundamental frequency changes.

In order for a complex tone to have an interesting timbre, the amplitude of the partials must change with a certain degree of
independence. The function object allows you to draw control shapes such as amplitude envelopes, and when function
receives a bang it describes that shape to a line~ object to generate a corresponding control signal.

See Also
Name Description
function Graphically edit a breakpoint function
Tremolo and Ring Modulation
Tutorial 8: Tremolo and Ring Modulation
Open the tutorial.

Multiplying signals
In the previous chapter we added sine tones together to make a complex tone. In this chapter we will see how a very different
effect can be achieved by multiplying signals. Multiplying one wave by another -- i.e., multiplying their instantaneous
amplitudes, sample by sample -- creates an effect known as ring modulation (or, more generally, amplitude modulation).
Modulation in this case simply means change; the amplitude of one waveform is changed continuously by the amplitude of
another.

Technical detail: Multiplication of waveforms in the time domain is equivalent to convolution of waveforms in the
frequency domain. One way to understand convolution is as the superimposition of one spectrum on every frequency of
another spectrum. Given two spectra S1 and S1 at the location of every frequency in S2, with each copy scaled by the
amplitude of that particular frequency of S2.

Since a cosine wave has equal amplitude at both positive and negative frequencies, its spectrum contains energy
(equally divided) at both and -. When convolved with another cosine wave, then, a scaled copy of (both the positive
and negative frequency components of) the one wave is centered around both the positive and negative frequency
components of the other.

Multiplication in the time domain is equivalent to convolution in the frequency domain

In our example patch, we multiply two sinusoidal tones. Ring modulation (multiplication) can be performed with any
signals, and in fact the most sonically interesting uses of ring modulation involve complex tones.

However, we'll stick to sine tones in this example for the sake of simplicity, to allow you to hear clearly the effects of signal
multiplication.

Simple multiplication of two cosine waves

The tutorial patch contains two cycle~ objects, and the outlet of each one is connected to one of the inlets of a *~ object.
However, the output of one of the cycle~ objects is first scaled by an additional *~ object, which provides control of the
over-all amplitude of the result. (Without this, the over-all amplitude of the product of the two cycle~ objects would always
be 1.)
Product of two cosine waves (one with amplitude scaled beforehand)

Tremolo
When you first open the patch, a loadbang object initializes the frequency and amplitude of the oscillators. One oscillator is
at an audio frequency of 1000 Hz. The other is at a sub-audio frequency of 0.1 Hz (one cycle every ten seconds). The 1000
Hz tone is the one we hear (this is termed the carrier oscillator), and it is modulated by the other wave (called the
modulator) such that we hear the amplitude of the 1000 Hz tone dip to 0 whenever the 0.1 Hz cosine goes to 0. (Twice per
cycle, meaning once every five seconds.)

Click on the ezdac~ to turn audio on. You will hear the amplitude of the 1000 Hz tone rise and fall according to the cosine
curve of the modulator, which completes one full cycle every ten seconds. (When the modulator is negative, it inverts the
carrier, but we don't hear the difference, so the effect is of two equivalent dips in amplitude per modulation period.)

The amplitude is equal to the product of the two waves. Since the peak amplitude of the carrier is 1, the over-all amplitude is
equal to the amplitude of the modulator.

Drag on the Amplitude number box to adjust the sound to a comfortable level. Click on the message box containing the
number 1 to change the modulator rate.

With the modulator rate set at 1, you hear the amplitude dip to 0 two times per second. Such a periodic fluctuation in
amplitude is known as tremolo. (Note that this is distinct from vibrato, a term usually used to describe a periodic fluctuation
in pitch or frequency.) The perceived rate of tremolo is equal to two times the modulator rate, since the amplitude goes to 0
twice per cycle. As described on the previous page, ring modulation produces the sum and difference frequencies, so you're
actually hearing the frequencies 1001 Hz and 999 Hz, and the 2 Hz beating due to the interference between those two
frequencies.

One at a time, click on the message box objects containing 2 and 4. What tremolo rates do you hear? The sound is still
like a single tone of fluctuating amplitude because the sum and difference tones are too close in frequency for you to separate
them successfully, but can you calculate what frequencies you're actually hearing?

Now try setting the rate of the modulator to 8 Hz, then 16 Hz.

In these cases the rate of tremolo borders on the audio range. We can no longer hear the tremolo as distinct fluctuations, and
the tremolo just adds a unique sort of roughness to the sound. The sum and difference frequencies are now far enough
apart that they no longer fuse together in our perception as a single tone, but they still lie within what psychoacousticians call
the critical band. Within this critical band we have trouble hearing the two separate tones as a pitch interval, presumably
because they both affect the same region of our basilar membrane.

Sidebands
Try setting the rate of the modulator to 32 Hz, then 50 Hz.

At a modulation rate of 32 Hz, you can hear the two tones as a pitch interval (approximately a minor second), but the
sensation of roughness persists. With a modulation rate of 50 Hz, the sum and difference frequencies are 1050 Hz and 950
Hz -- a pitch interval almost as great as a major second -- and the roughness is mostly gone. You might also hear the tremolo
rate itself, as a tone at 100 Hz.

You can see that this type of modulation produces new frequencies not present in the carrier and modulator tones. These
additional frequencies, on either side of the carrier frequency, are often called sidebands.

Listen to the remaining modulation rates.


At certain modulation rates, all the sidebands are aligned in a harmonic relationship. With a modulation rate of 200 Hz, for
example, the tremolo rate is 400 Hz and the sum and difference frequencies are 800 Hz and 1200 Hz. Similarly, with a
modulation rate of 500 Hz, the tremolo rate is 1000 Hz and the sum and difference frequencies are 500 Hz and 1500 Hz. In
these cases, the sidebands fuse together more tightly as a single complex tone.

Experiment with other carrier and modulator frequencies by typing other values into the number box objects. When you
have finished, click on ezdac~ again to turn audio off.

Summary
Multiplication of two digital signals is comparable to the analog audio technique known as ring modulation. Ring
modulation is a type of amplitude modulation -- changing the amplitude of one tone (termed the carrier) with the amplitude
of another tone (called the modulator). Multiplication of signals in the time domain is equivalent to convolution of spectra
in the frequency domain.

Multiplying an audio signal by a sub-audio signal results in regular fluctuations of amplitude known as tremolo.
Multiplication of signals creates sidebands -- additional frequencies not present in the original tones. Multiplying two
sinusoidal tones produces energy at the sum and difference of the two frequencies. This can create beating due to
interference of waves with similar frequencies, or can create a fused complex tone when the frequencies are harmonically
related. When two signals are multiplied, the output amplitude is determined by the product of the carrier and modulator
amplitudes.
Amplitude Modulation
Tutorial 9: Amplitude Modulation
Open the tutorial.

Ring modulation and amplitude modulation


Amplitude modulation (AM) involves changing the amplitude of a carrier signal using the output of another modulator
signal. In the specific AM case of ring modulation (discussed in Tutorial 8) the two signals are simply multiplied. In the
more general case, the modulator is used to alter the carrier's amplitude, but is not the sole determinant of it. To put it
another way, the modulator can cause fluctuation of amplitude around some value other than 0. The example below
illustrates the difference between ring modulation and more common amplitude modulation.

Ring modulation Amplitude modulation

The example on the left is 1/ 4 second of a 100 Hz cosine multiplied by a 4 Hz cosine; the amplitude of both cosines is 1. In
the example on the right, the 4 Hz cosine has an amplitude of 0.25, which is used to vary the amplitude of the 100 Hz tone
0.25 around 0.75 (going as low as 0.5 and as high as 1.0). The two main differences are a) the AM example never goes all
the way to 0, whereas the ring modulation example does, and b) the ring modulation is perceived as two amplitude dips per
modulation period (thus creating a tremolo effect at twice the rate of the modulation) whereas the AM is perceived as a
single cosine fluctuation per modulation period.

The two MSP patches that made these examples are shown below.

Ring modulation Amplitude modulation

The difference in effect is due to the constant value of 0.75 in the AM patch, which is varied by a modulator of lesser
amplitude. This constant value can be thought of as the carrier's amplitude, which is varied by the instantaneous amplitude
of the modulator. The amplitude still varies according to the shape of the modulator, but the modulator is not centered on 0.

Technical detail: The amount that a wave is offset from 0 is called the DC offset. A constant amplitude value such as
this represents spectral energy at the frequency 0 Hz. The modulator in AM has a DC offset, which distinguishes it from
ring modulation.

Implementing AM in MSP
The tutorial patch is designed in such a way that the DC offset of the modulator is always 1 minus the amplitude of its
sinusoidal variation. That way, the peak amplitude of the modulator is always 1, so the product of carrier and modulator is
always 1. A separate *~ object is used to control the over-all amplitude of the sound.

The modulator is a sinusoid with a DC offset, which is multiplied by the carrier

Click on the ezdac~ to turn audio on. Notice how the tremolo rate is the same as the frequency of the modulator. Click on
the message boxes 2, 4, and 8 in turn to hear different tremolo rates.

Achieving different AM effects


The primary merit of AM lies in the fact that the intensity of its effect can be varied by changing the amplitude of the
modulator.

To hear a very slight tremolo effect, type the value 0.03 into the number box marked Tremolo Depth. The modulator now
varies around 0.97, from 1 to 0.94, producing an amplitude variation of only about half a decibel. To hear an extreme
tremolo effect, change the tremolo depth to 0.5; the modulator now varies from 1 to 0 -- the maximum modulation possible.

Amplitude modulation produces sidebands -- additional frequencies not present in the carrier or the modulator -- equal to
the sum and the difference of the frequencies present in the carrier and modulator. The presence of a DC offset (technically
energy at 0 Hz) in the modulator means that the carrier tone remains present in the output, too (which is not the case with
ring modulation).

Click on the message boxes containing the numbers 32, 50, 100, and 150, in turn. You will hear the carrier frequency,
the modulator frequency (which is now in the low end of the audio range), and the sum and difference frequencies.

When there is a harmonic relationship between the carrier and the modulator, the frequencies produced belong to the
harmonic series of a common fundamental, and tend to fuse more as a single complex tone. For example, with a carrier
frequency of 1000 Hz and a modulator at 250 Hz, you will hear the frequencies 250 Hz, 750 Hz, 1000 Hz, and 1250 Hz the
1st, 3rd, 4th, and 5th harmonics of the fundamental at 250 Hz.

Click on the message boxes containing the numbers 200, 250, and 500 in turn to hear harmonic complex tones. Drag on
the Tremolo Depth number box to change the depth value between 0. and 0.5, and listen to the effect on the relative
strength of the sidebands.

Explore different possibilities by changing the values in the number box objects. When you have finished, click on the
ezdac~ to turn audio off.

It is worth noting that any audio signals can be used as the carrier and modulator tones, and in fact many interesting results
can be obtained by amplitude modulation with complex tones. (Tutorial 23 allows you to perform amplitude modulation on
the sound coming into the computer.)

Summary
The amplitude of an audio (carrier) signal can be modulated by another (modulator) signal, either by simple multiplication
(ring modulation) or by adding a time-varying modulating signal to a constant signal (DC offset) before multiplying it with
the carrier signal (amplitude modulation). The intensity of the amplitude modulation can be controlled by increasing or
reducing the amplitude of the time-varying modulator relative to its DC offset. When the modulator has a DC offset, the
carrier frequency will remain present in the output sound, along with sidebands at frequencies determined by the sum and
the difference of the carrier and the modulator. At sub-audio modulating frequencies, amplitude modulation is heard as
tremolo; at audio frequencies the carrier, modulator, and sidebands are all heard as a chord or as a complex tone.
Vibrato and FM
Tutorial 10: Vibrato and FM
Open the tutorial.

Basic FM in MSP
Frequency modulation (FM) is a change in the frequency of one signal caused by modulating it with another signal. In the
most common implementation, the frequency of a sinusoidal carrier wave is varied continuously with the output of a
sinusoidal modulating oscillator. The modulator is added to the constant base frequency of the carrier.

Simple frequency modulation

The example above shows the basic configuration for FM. The frequency of the modulating oscillator determines the rate of
modulation, and the amplitude of the modulator determines the depth (intensity) of the effect.

Click on the ezdac~ to turn audio on.


The sinusoidal movement of the modulator causes the frequency of the carrier to go as high as 1015 Hz and as low as 885
Hz. This frequency variation completes six cycles per second, so we hear a 6 Hz vibrato centered around 1000 Hz. (Note that
this is distinct from tremolo, which is a fluctuation in amplitude, not frequency.)

Drag upward on the number box marked Modulation Depth to change the amplitude of the modulator. The vibrato
becomes wider and wider as the modulator amplitude increases. Set the modulation depth to 500.

With such a drastic frequency modulation, one no longer really hears the carrier frequency. The tone passes through 1000
Hz so fast that we don't hear that as its frequency. Instead we hear the extremes -- 500 Hz and 1500 Hz -- because the
output frequency actually spends more time in those areas.

Note that 500 Hz is an octave below 1000 Hz, while 1500 Hz is only a perfect fifth above 1000 Hz. The interval between 500
Hz and 1500 Hz is thus a perfect 12th (as one would expect, given their 1:3 ratio). So you can see that a vibrato of equal
frequency variation around a central frequency does not produce equal pitch variation above and below the central pitch. (In
Tutorial 17 we demonstrate how to make a vibrato that is equal in pitch up and down.)

Set the modulation depth to 1000. Now begin dragging the Modulator Frequency number box upward slowly to hear a
variety of effects.

As the modulator frequency approaches the audio range, you no longer hear individual oscillations of the modulator. The
modulation rate itself is heard as a low tone. As the modulation frequency gets well into the audio range (at about 50 Hz),
you begin to hear a complex combination of sidebands produced by the FM process. The precise frequencies of these
sidebands depend on the relationship between the carrier and modulator frequencies.

Drag the Modulator Frequency number box all the way up to 1000. Notice that the result is a rich harmonic tone with
fundamental frequency of 1000 Hz. Try typing in modulator frequencies of 500, 250, and 125 and note the change in
perceived fundamental.

In each of these cases, the perceived fundamental is the same as the modulator frequency. In fact, though, it is not
determined just by the modulator frequency, but rather by the relationship between carrier frequency and modulator
frequency. This will be examined more in the next chapter.

Type in 125 as the modulator frequency. Now drag up and down on the Modulation Depth number box, making drastic
changes. Notice that the pitch stays the same but the timbre changes.
The timbre of an FM tone depends on the ratio of modulator amplitude to modulator frequency. This, too, will be discussed
more in the next chapter.

Summary
Frequency modulation (FM) is achieved by adding a time-varying signal to the constant frequency of an oscillator. It is good
for vibrato effects at sub-audio modulating frequencies, and can produce a wide variety of timbres at audio modulating
frequencies. The rich complex tones created with FM contain many partials, even though only two oscillators are needed to
make the sound. This is a great improvement over additive synthesis, in terms of computational efficiency.
Frequency Modulation
Tutorial 11: Frequency Modulation
Open the tutorial.

Elements of FM synthesis
Frequency modulation (FM) has proved to be a very versatile and effective means of synthesizing a wide variety of musical
tones. FM is very good for emulating acoustic instruments, and for producing complex and unusual tones in a
computationally efficient manner.

Modulating the frequency of one wave with another wave generates many sidebands, resulting in many more frequencies in
the output sound than were present in the carrier and modulator waves themselves. As was mentioned briefly in the
previous chapter, the frequencies of the sidebands are determined by the relationship between the carrier frequency (Fc) and
the modulator frequency (Fm); the relative strength of the different sidebands (which affects the timbre) is determined by
the relationship between the modulator amplitude (Am) and the modulator frequency (Fm).

Because of these relationships, it's possible to boil the control of FM synthesis down to two crucial values, which are defined
as ratios of the pertinent parameters. One important value is the harmonicity ratio, defined as Fm/Fc; this will determine
what frequencies are present in the output tone, and whether the frequencies have an harmonic or inharmonic relationship.
The second important value is the modulation index, defined as Am/Fm; this value affects the brightness of the timbre by
affecting the relative strength of the partials.

Technical detail: In John Chowning's article Synthesis of Complex Audio Spectra by Means of Frequency
Modulation and in Curtis Roads' Computer Music Tutorial, they write about the ratio Fc/Fm. However, in F.R. Moore's
Elements of Computer Music he defines the term harmonicity ratio as Fm/Fc. The idea in all cases is the same, to
express the relationship between the carrier and modulator frequencies as a ratio. In this tutorial we use Moore's
definition because that way whenever the harmonicity ratio is an integer the result will be a harmonic tone with Fc as
the fundamental.

The frequencies of the sidebands are determined by the sum and difference of the carrier frequency plus and minus integer
multiples of the modulator frequency. Thus, the frequencies present in an FM tone will be Fc, Fc+Fm, Fc-Fm, Fc+2Fm, Fc-
2Fm, Fc+3Fm, Fc-3Fm, etc. This holds true even if the difference frequency turns out to be a negative number; the negative
frequencies are heard as if they were positive. The number and strength of sidebands present is determined by the
modulation index; the greater the index, the greater the number of sidebands of significant energy.

An FM subpatch: simpleFM~
The simpleFM~ object in this tutorial patch is not an MSP object; it's a subpatch that implements the ideas of harmonicity
ratio and modulation index.

Double-click on the simpleFM~ subpatch object to see its contents.

The simpleFM~ subpatch


The main asset of this subpatch is that it enables one to specify the carrier frequency, harmonicity ratio, and modulation
index, and it then calculates the necessary modulator frequency and modulator amplitude (in the *~ objects) to generate the
correct FM signal. The subpatch is flexible in that it accepts either signals or numbers in its inlets, and the harmonicity ratio
and modulation index can be typed in as arguments in the main patch.

Close the [simpleFM~]window.

Producing different FM tones


In the main patch, the carrier frequency and harmonicity ratio are provided to simpleFM~ as constant values, and the
modulation index is provided as a time-varying signal generated by the envelope in the function object.

Providing values for the FM instrument

Because modulation index is the main determinant of timbre (brightness), and because the timbre of most real sounds varies
over time, the modulation index is a prime candidate to be controlled by an envelope. This timbre envelope may or may not
correspond exactly with the amplitude of the sound, so in the main patch one envelope is used to control amplitude, and
another to control brightness.

Over the course of the note, the timbre and the amplitude evolve independently

Each of the presets contains settings to produce a different kind of FM tone, as described below.

Turn audio on and click on the first preset in the preset object to recall some settings for the instrument. Click on the
button to play a note. To hear each of the different preset tones, click on a different preset in the preset object to recall the
settings for the instrument, then click on the button to play a note.
Preset 1. The carrier frequency is for the pitch C an octave below middle C. The non-integer value for the harmonicity ratio
will cause an inharmonic set of partials. This inharmonic spectrum, the steady drop in modulation index from bright to pure,
and the long exponential amplitude decay all combine to make a metallic bell-like tone.

Preset 2. This tone is similar to the first one, but with a (slightly mistuned) harmonic value for the harmonicity ratio, so the
tone is more like an electric piano.

Preset 3. An irrational (1 over the square root of 2) value for the harmonicity ratio, a low modulation index, a short
duration, and a characteristic envelope combine to give this tone a quasi- pitched drum-like quality.

Preset 4. In brass instruments the brightness is closely correlated with the loudness. So, to achieve a trumpet-like sound in
this example the modulation index envelope essentially tracks the amplitude envelope. The amplitude envelope is also
characteristic of brass instruments, with a slow attack and little decay. The pitch is G above middle C, and the harmonicity
ratio is 1 for a fully harmonic spectrum.

Preset 5. On the trumpet, a higher note generally requires a more forceful attack; so the same envelope applied to a shorter
duration, and a carrier frequency for the pitch high C, emulate a staccato high trumpet note.

Preset 6. The same pitch and harmonicity, but with a percussive attack and a low modulation index, give a xylophone
sound.

Preset 7. A harmonicity ratio of 4 gives a spectrum that emphasizes odd harmonics. This, combined with a low modulation
index and a slow attack, produces a clarinet-like tone.

Preset 8. Of course, the real fun of FM synthesis is the surreal timbres you can make by choosing unorthodox values for the
different parameters. Here, an extreme and wildly fluctuating modulation index produces a sound unlike that produced by
any acoustic object.

You can experiment with your own envelopes and settings to discover new FM sounds. When you have finished, click on
the ezdac~ to turn audio off.
As with amplitude modulation, frequency modulation can also be performed using complex tones. Sinusoids have
traditionally been used most because they give the most predictable results, but many other interesting sounds can be
obtained by using complex tones for the carrier and modulator signals.

Summary
FM synthesis is an effective technique for emulating acoustic instrumental sounds as well as for generating unusual new
sounds.

The frequencies present in an FM tone are equal to the carrier frequency plus and minus integer multiples of the modulator
frequency. Therefore, the harmonicity of the tone can be described by a single number -- the ratio of the modulator and
carrier frequencies -- sometimes called the harmonicity ratio. The relative amplitude of the partials is dependent on the
ratio of the modulator's amplitude to its frequency, known as the modulation index.

In most acoustic instruments, the timbre changes over the course of a note, so envelope control of the modulation index is
appropriate for producing interesting sounds. A non-integer harmonicity ratio yields an inharmonic spectrum, and when
combined with a percussive amplitude envelope can produce drum-like and bell-like sounds. An integer harmonicity ratio
combined with the proper modulation index envelope and amplitude envelope can produce a variety of pitched instrument
sounds.
Waveshaping
Tutorial 12: Waveshaping
Open the tutorial.

Using a stored wavetable


In Tutorial 3 we used 512 samples stored in a buffer~ as a wavetable to be read by the cycle~ object. The name of the
buffer~ object is typed in as an argument to the cycle~ object, causing cycle~ to use samples from the buffer~ as its
waveform, instead of its default cosine wave. The frequency value received in the left inlet of the cycle~ determines how
many times per second it will read through those 512 samples, and thus determines the fundamental frequency of the tone it
plays.

Just to serve as a reminder, an example of that type of wavetable synthesis is included in the lower right corner of this
tutorial patch.

The cycle~ object reads repeatedly through the 512 samples stored in the buffer~

Double-click on the buffer~ object to see its contents. The file gtr512.aiff contains one cycle of a recorded electric guitar
note. Click on the ezdac~ speaker icon to turn audio on. Click on the toggle to open the gate~, allowing the output of
cycle~ to reach the dac~. Click on the toggle again to close the gate~.

This type of synthesis allows you to use any waveform for cycle~, but the timbre is static and somewhat lifeless because the
waveform is unchanging. This tutorial presents a new way to obtain dynamically changing timbres, using a technique known
as waveshaping.

Table lookup: lookup~


In waveshaping synthesis an audio signal -- most commonly a sine wave -- is used to access a lookup table containing some
shaping function (also commonly called a transfer function). Each sample value of the input signal is used as an index to
look up a value stored in a table (an array of numbers). Because a lookup table may contain any values in any order, it is
useful for mapping a linear range of values (such as the signal range -1 to 1) to a nonlinear function (whatever is stored in the
lookup table). The Max object table is an example of a lookup table; the number received as input (commonly in the range 0
to 127) is used to access whatever values are stored in the table.
The MSP object lookup~ allows you to use samples stored in a buffer~ as a lookup table which can be accessed by a signal
in the range -1 to 1. By default, lookup~ uses the first 512 samples in a buffer~, but you can type in arguments to specify any
excerpt of the buffer~ object's contents for use as a lookup table. If 512 samples are used, input values ranging from -1 to 0
are mapped to the first 256 samples, and input values from 0 to 1 are mapped to the next 256 samples; lookup~ interpolates
between two stored values as necessary.

Sine wave used to read back and forth through an excerpt of the buffer~

The most commonly used input signal for indexing the lookup table is a sine wave -- it's a reasonable choice because it reads
smoothly back and forth through the table -- but any audio signal can be used as input to lookup~.
The important thing to observe about waveshaping synthesis is this: changing the amplitude of the input signal changes the
amount of the lookup table that gets used. If the range of the input signal is from -1 to 1, the entire lookup table is used.
However, if the range of the input signal is from -0.33 to 0.33, only the middle third of the table is used. As a general rule,
the timbre of the output signal becomes brighter (contains more high frequencies) as the amplitude of the input signal
increases.

It's also worth noting that the amplitude of the input signal has no direct effect on the amplitude of the output signal; the
output amplitude depends entirely on the values being indexed in the lookup table.

Varying timbre with waveshaping


The waveshaping part of the tutorial patch is in the lower left portion of the Patcher window. It's very similar to the example
shown above.

The lookup table consists of the 512 samples in the buffer~, and it is read by a cosine wave from a cycle~ object.

Lookup table used for waveshaping

The upper portion of the Patcher window contains three different ways to vary the amplitude of the cosine wave, which will
vary the timbre.

With the audio still on, choose Set range by hand from the pop-up umenu. This opens the first signal inlet of the
selector~, so you can alter the amplitude of the cycle~ by dragging in the number box marked By hand. Change the value
in the number box to hear different timbres.

Set the amplitude of the input signal to change the timbre of the output

To make the timbre change over the course of the note, you can use a control function envelope to vary the amplitude of the
cycle~ automatically over time.

Choose Control range by envelope from the umenu. Set a note duration by typing a value into the number box marked
Duration (such as 1000 ms), then click on the button to play a note. Experiment with different durations and envelopes.
You can also modulate the amplitude of the input wave with another signal. An extremely slow modulating frequency (such
as 0.1 Hz) will change the timbre very gradually. A faster sub-audio modulating frequency (such as 8 Hz) will create a unique
sort of timbre tremolo. Modulating the input wave at an audio rate creates sum and difference frequencies (as you have seen
in Tutorial 9) which may interfere in various ways depending on the modulation rate.

Choose Modulate range by wave from the umenu. Set the modulation rate to 0.1 Hz and set the modulation depth to 0.9.

Very slow modulation of the input wave's amplitude creates a gradual timbre change

Notice that the amplitude of the cycle~ is multiplied by 0.45 and offset by 0.5. That makes it range from 0.05 to 0.95. (If it
went completely to 0 the amplitude of the wave it's modulating would be 0 and the sound would stop.) The Modulation
depth number box goes from 0 to 1, but it's actually scaling the cycle~ within that range from 0.05 to 0.95.
Experiment with other values for the depth and rate of modulation.

If you're designing an instrument for musical purposes, you might use some combination of these three ways to vary the
timbre, and you almost certainly would have an independent amplitude envelope to scale the amplitude of the output sound.
(Remember that the amplitude of the signal coming out of lookup~ depends on the sample values being read, and is not
directly affected by the amplitude of the signal coming into it.)

Summary
Waveshaping is the nonlinear distortion of a signal to create a new timbre. The sample values of the original signal are used
to address a lookup table, and the corresponding value from the lookup table is sent out. The lookup~ object treats samples
from a buffer~ as such a lookup table, and uses the input range -1 to 1 to address those samples. A sine wave is commonly
used as the input signal for waveshaping synthesis. The amplitude of the input signal determines how much of the lookup
table gets used. As the amplitude of the input signal increases, more of the table gets used, and consequently more
frequencies are generally introduced into the output. Thus, you can change the timbre of a waveshaped signal dynamically by
continuously altering the amplitude of the input signal, using a control function or a modulating signal.

See Also
Name Description
buffer~ Store audio samples
cycle~ Sinusoidal oscillator
lookup~ Transfer function lookup table
Recording and Playback
Tutorial 13: Recording and Playback
Open the tutorial.

Sound input: adc~


For getting sound from the real world into MSP, there is an analog-to-digital conversion object called adc~. It recognizes all
the same messages as the dac~ object, but instead of sending signal to the audio output jacks of the computer, adc~ receives
signal from the audio input jacks, and sends the incoming signal out its outlets. Just as dac~ has a user interface version
called ezdac~, there is an iconic version of adc~ called ezadc~.

adc~ and ezadc~ get sound from the audio input jacks and send it out as a signal

To use the adc~ object, you need to send sound from some source into the computer. The sound may come from the CD
player of your computer, from any line level source such as a tape player, or from a microphone -- your computer might have
a built-in microphone, or you can use a standard microphone via a preamplifer.

Double click on the adc~ object to open the Audio Status window. Make sure that the Input Source popup menu displays
the input device you want. Depending on your computer system, audio card and driver, you may not have a choice of input
device-this is nothing to be concerned about.

Click on the toggle above the adc~ object to turn audio on. If you want to hear the input sound played directly out the
output jacks, adjust the number box marked Audio thruput level.

Adjust the audio throughput to a comfortable listening level

If your input source is a microphone, you'll need to be careful not to let the output sound from your computer feed back into
the microphone.

Recording a sound: record~


To record a sample of the incoming sound (or any signal), you first need to designate a buffer in which the sound will be
stored. Your patch should therefore include at least one buffer~ object. You also need a record~ object with the same name
as the buffer~. The sound that you want to record must go in the inlet of the record~ object.
Record two seconds of stereo sound into the buffer~ named soundbite

When record~ receives a non-zero int in its left inlet, it begins recording the signals connected to its record inlets; 0 stops
the recording. You can specify recording start and end points within the buffer~ by sending numbers in the two right inlets
of record~. If you don't specify start and end points, recording will fill the entire buffer~. Notice that the length of the
recording is limited by the length of the buffer~. If this were not the case, there would be the risk that record~ might be left
on accidentally and fill the entire application memory.

In the tutorial patch, record~ will stop recording after 2 seconds (2000 ms). We have included a delayed bang to turn off
the toggle after two seconds, but this is just to make the toggle accurately display the state of record~. It is not necessary
to stop record~ explicitly, because it will stop automatically when it reaches its end point or the end of the buffer~.

A delayed bang turns off the toggle after two seconds so it will display correctly

Make sure that you have sound coming into the computer, then click on the toggle to record two seconds of the incoming
sound. If you want to, you can double-click on the buffer~ afterward to see the recorded signal.

Reading through a buffer~: index~


So far you have seen two ways to get sound into a buffer~. You can read in an existing audio file with the read message, and
you can record sound into it with the record~ object. Once you get the sound into a buffer~, there are several things you can
do with it. You can save it to an audio file by sending the write message to the buffer~. You can use 513 samples of it as a
wavetable for cycle~, as demonstrated in Tutorial 3. You can use any section of it as a transfer function for lookup~, as
demonstrated in Tutorial 14.

The index~ object receives a signal as its input, which represents a sample number. It looks up that sample in its associated
buffer~, and sends the value of that sample out its outlet as a signal. The count~ object just sends out a signal value that
increases by one with each sample. So, if you send the output of count~ -- a steady stream of increasing numbers -- to the
input of index~ -- which will treat them as sample numbers -- index~ will read straight through the buffer~, playing it back
at the current sampling rate.
Play the sound in a buffer~ by looking up each sample and sending it to the dac~

Click on the button marked Play to play the sound in the buffer~. You can change the starting sample number by
sending a different starting number into count~.
This combination of count~ and index~ lets you specify a precise sample number in the buffer~ where you want to start
playback. However, if you want to specify starting and ending points in the buffer~ in terms of milliseconds, and/or you
want to play the sound back at a different speed -- or even backward -- then the play~ object is more appropriate.

Variable speed playback: play~


The play~ object receives a signal in its inlet which indicates a position, in milliseconds, in its associated buffer~; play~
sends out the signal value it finds at that point in the buffer~. Unlike index~, though, when play~ receives a position that
falls between two samples in the buffer~ it interpolates between those two values. For this reason, you can read through a
buffer~ at any speed by sending an increasing or decreasing signal to play~, and it will interpolate between samples as
necessary. (Theoretically, you could use index~ in a similar manner, but it does not interpolate between samples so the
sound fidelity would be considerably worse.)

The most obvious way to use the play~ object is to send it a linearly increasing (or decreasing) signal from a line~ object, as
shown in the tutorial patch.

Read through a buffer~, from one position to another, in a given amount of time

Reading from 0 to 2000 (millisecond position in the buffer~) in a time of 2000 ms produces normal playback. Reading
from 0 to 2000 in 4000 ms produces half-speed playback, and so on.

Click on the different message box objects to hear the sound played in various speed/direction combinations. Turn audio
off when you have finished.

Although not demonstrated in this tutorial patch, it's worth noting that you could use other signals as input to play~ in order
to achieve accelerations and decelerations, such as an exponential curve from a curve~ object or even an appropriately
scaled sinusoid from a cycle~ object.

Summary
Sound coming into the computer enters MSP via the adc~ object. The record~ object stores the incoming sound -- or any
other signal -- in a buffer~. You can record into the entire buffer~, or you can record into any portion of it by specifying
start and end buffer positions in the two rightmost inlets of record~. For simple normal-speed playback of the sound in a
buffer~, you can use the count~ and index~ objects to read through it at the current sampling rate. Use the line~ and
play~ objects for variable-speed playback and/or for reading through the buffer~ in both directions.

See Also
Name Description
adc~ Audio input and on/off
ezadc~ Audio input and on/off button
index~ Read from a buffer~ with no interpolation
play~ Position-based sample playback
record~ Record sound into a buffer
Playback with Loops
Tutorial 14: Playback with Loops
Open the tutorial.

Playing samples with groove~


The groove~ object is the most versatile object for playing sound from a buffer~. You can specify the buffer~ to read, the
starting point, the playback speed (either forward or backward), and starting and ending points for a repeating loop within
the sample. As with other objects that read from a buffer~, groove~ accesses the buffer~ remotely, without patch cords, by
sharing its name.

A standard configuration for the use of groove~

In the example above, the message loop 1 turns looping on, the start time of 0 ms indicates the beginning of the buffer~,
the playback speed of 1 means to play forward at normal speed, and the loop start and end times mean that (because
looping is turned on) when groove~ reaches a point 860 milliseconds into the buffer~ it will return to a point 572 ms into
the buffer~ and continue playing from there. Notice that the start time must be received as a float (or int), and the playback
speed must be received as a signal. This means the speed can be varied continuously by sending a time- varying signal in
the left inlet.

Whenever a new start time is received, groove~ goes immediately to that time in the buffer~ and continues playing from
there at the current speed. When groove~ receives the message loop 1 or startloop it goes to the beginning of the loop and
begins playing at the current speed. (Note that loop points are ignored when groove~ is playing in reverse, so this does not
work when the playback speed is negative.) groove~ stops when it reaches the end of the buffer~ (or the beginning if it's
playing backward), or when it receives a speed of 0.

In the tutorial patch, three different buffer~ objects are loaded with AIFF files so that a single groove~ object can switch
between various samples instantly (notice that each buffer~ object also contains two additional optional arguments that
identify the length of the buffer and the number of channels). The message set, followed by the name of a buffer~, refers
groove~ to that new buffer~ immediately. (If groove~ always referred to the same buffer~, and we used read messages to
change the contents of the buffer~, some time would be needed to open and load each new file.)

Refer groove~ to a different buffer~ with a set message

Click on the preset object to play the samples in different ways.

The first preset just functions as an Off button. The next three presets play the three buffer~ objects at normal speed
without looping. The rest of the presets demonstrate a variety of sound possibilities using different playback speeds on
different excerpts of the buffered files, with or without looping.
You may want to experiment with your own settings by changing the user interface objects directly.

You can control all aspects of the playback by changing the user interface object settings

If you want to create smooth undetectable loops with groove~, you can use the loopinterp message to enable crossfades
between the end of a loop and the beginning of the next pass through the loop to smooth out the transition back to the start
point (see the groove~ reference page for more information on this message). If the buffer~ contains an AIFF file that has
its own loop points -- points established in a separate audio editing program -- there is a way to use those loop points to set
the loop points of groove~.

The info~ object can report the loop points of an AIFF file contained in a buffer~, and you can send those loop start and
end times directly into groove~. You can also use the the info~ object to find out the length (in milliseconds) of any file you
load into a buffer.

Using info~ to get loop point information from an AIFF file

Summary
The groove~ object is the most versatile way to play sound from a buffer~. You can specify the buffer~ to read, the starting
point, the playback speed (either forward or backward), and starting and ending points for a repeating loop within the
sample. If the buffer~ contains an AIFF file that has its own pre-established loop points, you can use the info~ object to get
those loop times and send them to groove~. The playback speed of groove~ is determined by the value of the signal coming
in its left inlet. You can set the current buffer position of groove~ by sending a float time value in the left inlet.

See Also
Name Description
buffer~ Store audio samples
groove~ Variable-rate looping sample playback
sig~ Convert numbers into audio signals
Variable-length Wavetable
Tutorial 15: Variable-length Wavetable
Open the tutorial.

Use any part of a buffer~ as a wavetable: wave~


As was shown in Tutorial 3, the cycle~ object can use 512 samples of a buffer~ as a wavetable through which it reads
repeatedly to play a periodically repeating tone. The wave~ object is an extension of that idea; it allows you to use any
section of a buffer~ as a wavetable.
The starting and ending points within the buffer~ are determined by the number or signal received in the middle and right
inlets of wave~. As a signal in the wave~ object's left inlet goes from 0 to 1, wave~ sends out the contents of the buffer~
from the specified start point to the end point. The phasor~ object, ramping repeatedly from 0 to 1, is the obvious choice as
an input signal for the left inlet of wave~.

phasor~ drives wave~ through the section of the buffer~ specified as the wavetable

In a standard implementation of wavetable synthesis, the wavetable (512 samples in the case of cycle~, or a section of any
length in the case of wave~) would be one single cycle of a waveform, and the frequency of the cycle~ object (or the
phasor~ driving the wave~) would determine the fundamental frequency of the tone. In the case of wave~, however, the
wavetable could contain virtually anything (an entire spoken sentence, for example).
wave~ yields rather unpredictable results compared to some of the more traditional sound generation ideas presented so far,
but with some experimentation you can find a great variety of timbres using wave~. In this tutorial patch, you will see some
ways of reading the contents of a buffer~ with wave~.

Synthesis with a segment of sampled sound


The tutorial patch is designed to let you try three different ways of driving wave~: with a repeating ramp signal (phasor~), a
sinusoid (cycle~), or a single ramp (line~). The bottom part of the Patcher window is devoted to the basic implementation
of wave~, and the upper part of the window contains the three methods of reading through the wavetable. First, let's look at
the bottom half of the window.

wave~ can use an excerpt of any length from either buffer~ as its wavetable
Click on the toggle to turn audio on. Set the amplitude to some level greater than 0. Set the end time of the wavetable to
782 (the length in milliseconds of the file isthatyou.aiff).

With these settings, wave~ will use the entire contents of buffer~ words isthatyou.aiff as its wavetable. Now we are ready
to read through the wavetable.

Choose Read forward from the pop-up umenu in the middle of the window. This will open the first signal inlet of the
selector~, allowing wave~ to be controlled by the phasor~ object.

Read through wave~ by going repeatedly from 0 to 1 with a phasor~ object

Set the number box marked Range to 1. This sets the amplitude of the phasor~, so it effectively determines what
fraction of the wavetable will be used. Set the number box marked Frequency to 2. The phasor~ now goes from 0 to 1 two
times per second, so you should hear wave~ reading through the buffer~ every half second.
Try a few different sub-audio frequency values for the phasor~, to read through the buffer~ at different speeds. You can
change the portion of the buffer~ being read, either by changing the Range value, or by changing the start and end times of
the wave~. Try audio frequencies for the phasor~ as well.
Notice that the rate of the phasor~ often has no obvious relationship to the perceived pitch, because the contents of the
wavetable do not represent a single cycle of a waveform. Furthermore, such rapid repetition of an arbitrarily selected
segment of a complex sample has a very high likelihood of producing frequencies well in excess of the Nyquist rate, which
will be folded back into the audible range in unpredictable ways.

Click on the message box to refer wave~ to the buffer~ chords object.
This changes the contents of the wavetable (because wave~ now accesses a different buffer~), and sets the maximum value
of the End time number box equal to the length of the file sacre.aiff. Notice an additional little programming trick --
shown in the example below -- employed to prevent the user from entering inappropriate start and end times for wave~.

Each time the start or end time is changed, it revises the limits of the other number box

With this new buffer~, experiment further by reading different length segments of the buffer~ at various rates.

Using wave~ as a transfer function


The buffer~ object is essentially a lookup table that can be accessed in different ways by other objects. In Tutorial 12 the
lookup~ object was used to treat a segment of a buffer~ as a transfer function, with a cosine wave as its input. The wave~
object can be used similarly. The only difference is that its input must range from 0 to 1, whereas lookup~ expects input in
the range from -1 to 1. To use wave~ in this way, then, we must scale and offset the incoming cosine wave so that it ranges
from 0 to 1.

Set the start and end times of wave~ close together, so that only a few milliseconds of sound are being used for the
wavetable. Choose Read back and forth from the pop-up umenu in the middle of the window. This opens the second signal
inlet of the selector~, allowing wave~ to be controlled by the cycle~ object.
cycle~, scaled and offset to range from 0 to 1, reads back and forth in the wavetable

Set the Range number box to a very small value such as 0.01 at first, to limit the cycle~ object's amplitude. This way,
cycle~ will use a very small segment of the wavetable as the transfer function. Set the frequency of cycle~ to 220 Hz. You
will probably hear a rich tone with a fundamental frequency of 220 Hz. Drag on the Range number box to change the
amplitude of the cosine wave; the timbre will change accordingly. You can also experiment with different wavetable lengths
by changing the start and end times of wave~. Sub-audio frequencies for the cycle~ object will produce unusual vibrato-like
effects as it scans back and forth through the wavetable.

Play the segment as a note


Because wave~ accepts any signal input in the rage 0 to 1, you can read through the wavetable just once by sending wave~ a
ramp signal from 0 to 1 (or backward, from 1 to 0). Other objects such as play~ and groove~ are better suited for this
purpose, but it is nevertheless possible with wave~.
Choose Read once from the pop-up umenu in the middle of the window. This opens the third signal inlet of the
selector~, allowing wave~ to be controlled by the line~ object. Set start and end times for your wavetable, set the Duration
number box to 1000, and click on the button to traverse the wavetable in one second. Experiment with both buffer~
objects, using various wavetable lengths and durations.

Changing the wavetable dynamically


The cycle~ object in the right part of the Patcher window is used to add a sinusoidal position change to the wavetable. As the
cosine wave rises and falls, the start and end times of the wavetable increase and decrease. As a result, the wavetable is
constantly shifting its position in the buffer~, in a sinusoidally varying manner. Sonically this produces a unique sort of
vibrato, not of fundamental frequency but of timbre. The wavetable length and the rate at which it is being read stay the
same, but the wavetable's contents are continually changing.

Shifting the wavetable by adding a sinusoidal offset to the start and end times

Set the Shift amount to 0.35, and set the Shift rate to 6. Set the start time of the wavetable to 102 and the end time to
109. Click on the message box to refer wave~ to the buffer~ chords object. Choose Read forward from the pop-up
umenu. Set the frequency of the phasor~ to an audio rate such as 110, and set its range to 1. You should hear a vibrato-like
timbre change at the rate of 6 Hz. Experiment with varying the shift rate and the shift amount. When you are done, click on
the toggle to turn audio off.

Summary
Any segment of the contents of a buffer~ can be used as a wavetable for the wave~ object. You can read through the
wavetable by sending a signal to wave~ that goes from 0 to 1. So, by connecting the output of a phasor~ object to the input
of wave~, you can read through the wavetable repeatedly at a sub-audio or audio rate. You can also scale and offset the
output of a cycle~ object so that it is in the range 0 to 1, and use that as input to wave~. This treats the wavetable as a
transfer function, and results in waveshaping synthesis. The position of the wavetable in the buffer~ can be varied
dynamically -- by adding a sinusoidal offset to the start and end times of wave~, for example -- resulting in unique sorts of
timbre modulation.

See Also
Name Description
buffer~ Store audio samples
phasor~ Generate sawtooth signals
wave~ Variable size wavetable
Record and Play Audio Files
Tutorial 16: Record and Play Audio Files
Open the tutorial.

Playing from memory vs. playing from disk


You have already seen how to store sound in memory -- in a buffer~ -- by recording into it directly or by reading in a pre-
recorded audio file. Once the sound is in memory, it can be accessed in a variety of ways with cycle~, lookup~, index~,
play~, groove~, wave~, etc.

The main limitation of buffer~ for storing samples, of course, is the amount of unused RAM available to the Max
application. You can only store as much sound in memory as you have memory to hold it. For playing and recording very
large amounts of audio data, it is more reasonable to use the hard disk for storage. But it takes more time to access the hard
disk than to access RAM; therefore, even when playing from the hard disk, MSP still needs to create a small buffer to preload
some of the sound into memory. That way, MSP can play the preloaded sound while it is getting more sound from the hard
disk, without undue delay or discontinuities due to the time needed to access the disk.

Record audio files: sfrecord~


MSP has objects for recording directly into, and playing directly from, an AIFF file: sfrecord~ and sfplay~. Recording an
audio file is particularly easy, you just open a file, begin recording, and stop recording. (You don't even need to close the file;
sfrecord~ takes care of that for you.) In the upper right corner of the Patcher window there is a patch for recording files.

Recording audio into an audio file on disk

sfrecord~ records to disk whatever signal data it receives in its inlets. The signal data can come directly from an adc~ or
ezadc~ object, or from any other MSP object.

Click on the message box marked Create an AIFF file. You will be shown a Save As dialog box for naming your file. (Make
sure you save the file on a volume with sufficient free space.) Navigate to the folder where you want to store the sound, name
the file, and click Save. Turn audio on. Click on the toggle to begin recording; click on it again when you have finished.

Play audio files: sfplay~


In the left part of the Patcher window there is a patch for playing audio files. The basic usage of sfplay~ requires only a few
objects, as shown in the following example. To play a file, you just have to open it and start sfplay~. The audio output of
sfplay~ can be sent directly to dac~ or ezdac~, and/or anywhere else in MSP.

Simple implementation of audio file playback

Click on the openmessage box marked Set the current file, and open the audio file you have just recorded. Then (with
audio on) click on the toggle marked Play/Stop to hear your file.

Play excerpts on cue


Because sfplay~ does not need to load an entire audio file into memory, you can actually have many files open in the same
sfplay~ object, and play any of them (or any portion of them) on cue. The most recently opened file is considered by sfplay~
to be the current file, and that is the file it will play when it receives the message 1.

Click on the remaining openmessage boxes to open some other audio files, and then click on the message box marked
Define cues, 2 to 9.

The preload message to sfplay~ specifies an entire file or a portion of a file, and assigns it a cue number. From then on,
every time sfplay~ receives that number, it will play that cue. In the example patch, cues 2, 3, and 4 play entire files, cue 5
plays the first 270 milliseconds of sacre.aiff, and so on. Cue 1 is always reserved for playing the current (most recently
opened) file, and cue 0 is reserved for stopping sfplay~.
Whenever sfplay~ receives a cue, it stops whatever it is playing and immediately plays the new cue. (You can also send
sfplay~ a queue of cues, by sending it a list of numbers, and it will play each cue in succession.) Each preload message
actually creates a small buffer containing the audio data for the beginning of the cue, so playback can start immediately upon
receipt of the cue number.

Now that cues 0 through 9 are defined, you can play different audio excerpts by sending sfplay~ those numbers. The upper-
left portion of the patch permits you to type those numbers directly from the computer keyboard.

ASCII codes from the number keys used to send cues to sfplay~

Click on the toggle marked Keyplay On/Off. Type number keys to play the different pre- defined cues. Turn Keyplay off
when you are done.

Try different file excerpts


Before you define a cue, you will probably need to listen to segments of the file to determine the precise start and end times
you want. You can use the seek message to hear any segment of the current file.

Open your own audio file again (or any other audio file) to make it the current file. In the right portion of this patch, enter
an end time for the seek message. The excerpt you have specified will begin playing. Try different start and end times.

Once you find start and end times you like, you could use them in a preload message to establish a cue. Because sfplay~
can't know in advance what excerpt it will be required to play in response to a seek message, it can't preload the excerpt.
There will be a slight delay while it accesses the hard disk before it begins playing. For that reason, seek is best used as an
auditioning tool; preloaded cues are better for performance situations where immediate playback is more critical.

Trigger an event at the end of a file


The patch in the lower right portion of the Patcher window demonstrates the use of the right outlet of sfplay~. When a cue
is done playing (or when it is stopped with a 0 message), sfplay~ sends a bang out the right outlet. In this example patch,
the bang is used to trigger the next (randomly chosen) cue, so sfplay~ effectively restarts itself when each cue is done.
When a cue is completed, sfplay~ triggers the next cue

Note the importance of the gate object in this patch. If it were not present, there would be no way to stop sfplay~ because
each 0 cue would trigger another non-zero cue. The gate must be closed before the 0 cue is sent to sfplay~.
In the patch marked Play random excerpts, click on the message box to preload the cues, then click on the toggle to start
the process. To stop it, click on the toggle again. Turn audio off.

Summary
For large and/or numerous audio samples, it is often better to read the samples from the hard disk than to try to load them
all into RAM. The objects sfrecord~ and sfplay~ provide a simple way to record and play audio files to and from the hard
disk. The sfplay~ object can have many audio files open at once. Using the preload message, you can pre-define ready cues
for playing specific files or sections of files. The seek message to sfplay~ lets you try different start and end points for a cue.
When a cue is done playing (or is stopped) sfplay~ sends a bang out its right outlet. This bang can be used to trigger other
processes, including sending sfplay~ its next cue.

See Also
Name Description
sfplay~ Play audio file from disk
sfrecord~ Record to audio file on disk
Sampling Review
Tutorial 17: Sampling Review
Open the tutorial.

A sampling exercise
In this chapter we suggest an exercise to help you check your understanding of how to sample and play audio. Try
completing this exercise in a new file of your own before you check the solution given in the example patch. (But don't have
the example Patcher open while you design your own patch, or you will hear both patches when you turn audio on.) The
exercise is to design a patch in which:

Typing the a key on the computer keyboard turns audio on. Typing a again toggles audio off.

Typing r on the computer keyboard makes a one-second recording of whatever audio is coming into the computer (from the
input jacks or from the internal CD player).

Typing p plays the recording. Playback is to be at half speed, so that the sound lasts two seconds.

An amplitude envelope is applied to the sample when it is played, tapering the amplitude slightly at the beginning and end
so that there are no sudden clicks heard at either end of the sample.

The sample is played back with a 3 Hz vibrato added to it. The depth of the vibrato is one semitone (a factor of 2 1/12 ) up
and down.

Hints
You will need to store the sound in a buffer~ and play it back from memory.

You can record directly into the buffer~ with record~. (See Tutorial 13.) The input to record~ will come from adc~ (or
ezadc~).

The two obvious choices for playing a sample from a buffer~ at half speed are play~ and groove~. However, because we
want to add vibrato to the sound -- by continuously varying the playback speed -- the better choice is groove~, which uses a
(possibly time-varying) signal to control its playback speed directly. (See Tutorial 14.)

The amplitude envelope is best generated by a line~ object which is sending its output to a *~ object to scale the amplitude
of the output signal (coming from groove~). You might want to use a function object to draw the envelope, and send its
output to line~ to describe the envelope. (See Tutorial 7.)
The computer keyboard will need to trigger messages to the objects adc~, record~, groove~, and line~ (or function) in
order to perform the required tasks. Use the key object to get the keystrokes, and use select to detect the keys you want to
use.

Use a sinusoidal wave from a cycle~ object to apply vibrato to the sample. The frequency of the cycle~ will determine the
rate of the vibrato, and the amplitude of the sinusoid will determine the depth of vibrato. Therefore, you will need to scale
the cycle~ object's amplitude with a *~ object to achieve the proper vibrato depth.
In the discussion of vibrato in Tutorial 10, we created vibrato by adding the output of the modulating oscillator to the
frequency input of the carrier oscillator. However, two things are different in this exercise. First of all, the modulating
oscillator needs to modulate the playback speed of groove~ rather than the frequency of another cycle~ object. Second,
adding the output of the modulator to the input of the carrier -- as in Tutorial 10 -- creates a vibrato of equal frequency
above and below the carrier frequency, but does not create a vibrato of equal pitch up and down (as required in this
exercise). A change in pitch is achieved by multiplying the carrier frequency by a certain amount, rather than by adding an
amount to it.

To raise the pitch of a tone by one semitone, you must multiply its frequency by the twelfth root of 2, which is a factor of 2 to
the 1/ 12 power (approximately 1.06). To lower the pitch of a tone by one semitone, you must multiply its frequency by 2 to
the -1/ 12 power (approximately 0.944). To calculate a signal value that changes continuously within this range, you may
need to use an MSP object not yet discussed, pow~. Consult its description in the Objects section of this manual for details.

Solution
Scroll the example Patcher window all the way to the right to see a solution to this exercise.
Solution to the exercise for recording and playing an audio sample

The arguments to the buffer~ object specify a length in milliseconds (1000) and a number of channels (2). This determines
how much memory will initially be allocated to the buffer~.

Set name, length, and channels of the buffer~

Since the memory allocated in the buffer~ is limited to one second, there is no need to tell the record~ object to stop when
you record into the buffer~. It stops when it reaches the end of the buffer~.

The keystrokes from the computer keyboard are reported by key, and the select object is used to detect the a, r, and p keys.
The bangs from select trigger the necessary messages to adc~, record~, and groove~.

Keystrokes are detected and used to send messages to MSP objects

The keystroke p is also used to trigger the amplitude envelope at the same time as the sample is played. This envelope is
used to scale the output of groove~.
A two-second envelope tapers the amplitude at the beginning and end of the sample

A sig~ 0.5 object sets the basic playback speed of groove~ at half speed. The amplitude of a 3 Hz cosine wave is scaled by a
factor of 0.083333 (equal to 1/ 12, but more computationally efficient than dividing by 12) so that it varies from -1/ 12 to
1/ 12. This sinusoidal signal is used as the exponent in a power function in pow~ (2 to the power of the input), and the result
is used as the factor by which to multiply the playback speed.

Play at half speed, one semitone


Mapping MIDI to MSP
Tutorial 18: Mapping MIDI to MSP
Open the tutorial.

MIDI range vs. MSP range


One of the greatest assets of MSP is the ease with which one can combine MIDI and digital signal processing. The great
variety of available MIDI controllers means that you have many choices for the instrument you want to use to control sounds
in MSP. Because Max is already a well developed environment for MIDI programming, and because MSP is so fully
integrated into that environment, it is not difficult to use MIDI to control parameters in MSP.

The main challenge in designing programs that use MIDI to control MSP is to reconcile the numerical ranges needed for the
two types of data. MIDI data bytes are exclusively integers in the range 0 to 127. For that reason, most numerical processing
in Max is done with integers and most Max objects (especially user interface objects) deal primarily with integers. In MSP,
on the other hand, audio signal values are most commonly decimal numbers between -1.0 and 1.0, and many other values
(such as frequencies, for example) require a wide range and precision to several decimal places. Therefore, almost all
numerical processing in MSP is done with floating-point (decimal) numbers.

Often this incompatibility can be easily reconciled by linear mapping of one range of values (such as MIDI data values 0 to
127) into another range (such as 0 to 1 expected in the inlets of many MSP objects). Linear mapping is explained in Tutorial
29 of the Tutorials and Topics manual from the Max documentation, and is reviewed in this chapter. In many other cases,
however, you may need to map the linear numerical range of a MIDI data byte to some nonlinear aspect of human
perception -- such as our perception of a 12-semitone increase in pitch as a power of 2 increase in frequency, etc. This
requires other types of mapping; some examples are explored in this tutorial chapter.

Controlling synthesis parameters with MIDI


In this tutorial patch, we use MIDI continuous controller messages to control several different parameters in an FM
synthesis patch. The synthesis is performed in MSP by the subpatch simpleFM~ which was introduced in Tutorial 11, and
we map MIDI controller 1 (the mod wheel) to affect, in turn, its amplitude, modulation index, vibrato depth, vibrato rate, and
pitch bend.

An FM synthesis subpatch is the sound generator to be modified by MIDI

If we were designing a real performance instrument, we would probably control each of these parameters with a separate
type of MIDI message -- controller 7 for amplitude, controller 1 for vibrato depth, pitchbend for pitch bend, and so on. In this
patch, however, we use the mod wheel controller for everything, to ensure that the patch will work for almost any MIDI
keyboard. While this patch is not a model of good synthesizer design, it does let you isolate each parameter and control it
with the mod wheel.

In the lower right corner of the Patcher window, you can see that keys 0 to 5 of the computer keyboard can be used to choose
an item in the pop-up umenu at the top of the window.

Use ASCII from the computer keyboard to assign the function of the MIDI controller
The umenu sends the chosen item number to gate to open one of its outlets, thus directing the controller values from the
mod wheel to a specific place in the signal network.

gate directs the control messages to a specific place in the signal network

We will look at the special mapping requirements of each parameter individually. But first, let's review the formula for linear
mapping.

Linear mapping
The problem of linear mapping is this: Given a value x which lies in a range from xmin to xmax, find the value y that
occupies a comparable location in the range ymin to ymax. For example, 3 occupies a comparable location within the range
0 to 4 as 0.45 occupies within the range 0 to 0.6. This problem can be solved with the formula:

y = ((x - xmin) * (ymax - ymin) / (xmax - xmin)) + ymin

For this tutorial, we designed a subpatch called map to solve the equation. map receives an x value in its left inlet, and --
based on the values for xmin, xmax, ymax received in its other inlets -- it sends out the correct value for y. This equation will
allow us to map the range of controller values -- 0 to 127 -- onto various other ranges needed for the signal network. The
map subpatch appears in the upper right area of the Patcher window.

The contents of the map subpatch: the linear mapping formula expressed in an expr object

Once we have scaled the range of control values with map, some additional mapping may be necessary to suit various signal
processing purposes, as you will see.

Mapping MIDI to amplitude


As noted in Tutorial 4, we perceive relative amplitude on a multiplicative rather than an additive scale. For example we hear
the same relationship between amplitudes of 0.5 and 0.25 (a factor of 1/ 2, but a difference of 0.25) as we do between
amplitudes of 0.12 and 0.06 (again a factor of 1/ 2, but a difference of only 0.06). For this reason, if we want to express
relative amplitude on a linear scale (using the MIDI values 0 to 127), it is more appropriate to use decibels.

Click on the toggle to turn audio on. Type the number 5 (or choose Amplitude from the umenu) to direct the controller
values to affect the output amplitude.

The item number chosen in the umenu also recalls a preset in the preset object, which provides range values to map. In
this case, ymin is -80 and ymax is 0, so as the mod wheel goes from 0 to 127 the amplitude goes from -80 dB to 0 dB (full
amplitude). The decibel values are converted to amplitude in the subpatch called dBtoA. This converts a straight line into the
exponential curve necessary for a smooth increase in perceived loudness.
The contents of the dBtoA subpatch

Move the mod wheel on your MIDI keyboard to change the amplitude of the tone. Set the amplitude to a comfortable
listening level.

With this mapping, the amplitude changes by approximately a factor of 2 every time the controller value changes by 10. This
permits the same amount of control at low amplitudes as at high amplitudes (which would not be the case with a straight
linear mapping).

Mapping MIDI to frequency


Our perception of relative pitch is likewise multiplicative rather than additive with respect to frequency. In order for us to
hear equal spacings of pitch, the frequency must change in equal powers of 2. (See the discussions of pitch-to-frequency
conversion in Tutorial 17 and Tutorial 19.)

Type the number 1 (or choose Octave Pitch Bend from the umenu) to direct the controller values to affect the carrier
frequency. Move the mod wheel to bend the pitch upward as much as one octave, and back down to the original frequency.

In order for the mod wheel to perform a pitch bend of one octave, we map its range onto the range 0 to 1. This number is
then used as the exponent in a power of 2 function and multiplied times the fundamental frequency in expr.

Octave bend factor ranges from 20 to 21

2 0 = 1, and 2 1 = 2, so as the control value goes from 0 to 1 the carrier frequency increases from 220 to 440, which is to say
up an octave. The increase in frequency from 220 to 440 follows an exponential curve, which produces a linear increase in
perceived pitch from A to A.

Mapping MIDI to modulation index


Mapping the MIDI controller to the modulation index of the FM instrument is much simpler, because a linear control is
what's called for. Once the controller values are converted by the map subpatch, no further modification is needed. The mod
wheel varies the modulation index from 0 (no modulation) to 24 (extreme modulation).

Type the number 4 (or choose Modulation Index from the umenu) to direct the controller values to affect the modulation
index. Move the mod wheel to change the timbre of the tone.

Mapping MIDI to vibrato


This instrument has an additional low-frequency oscillator (LFO) for adding vibrato to the tone by modulating the carrier
frequency at a sub-audio rate. In order for the depth of the vibrato to be equal above and below the fundamental frequency,
we use the output of the LFO as the exponent of a power function in pow~.
Calculate the vibrato factor

The base of the power function (controlled by the mod wheel) varies from 1 to 2. When the base is 1 there is no vibrato; when
the base is 2 the vibrato is one octave.

You'll need to set both the vibrato rate and the vibrato depth before hearing the vibrato effect. Type 2 and move the mod
wheel to set a non-zero vibrato rate. Then type 3 and move the mod wheel to vary the depth of the vibrato.

The clumsiness of this process (re-assigning the mod wheel to each parameter in turn) emphasizes the need for separate
MIDI controllers for different parameters (or perhaps linked simultaneous control of more than one parameter with the
same MIDI message). In a truly responsive instrument, you would want to be able to control all of these parameters at once.
The next chapter shows a more realistic assignment of MIDI to MSP.

Summary
MIDI messages can easily be used to control parameters in MSP instruments, provided that the MIDI data is mapped into
the proper range. The map subpatch implements the linear mapping equation. When using MIDI to control parameters that
affect frequency and amplitude in MSP, the linear range of MIDI data from 0 to 127 must be mapped to an exponential curve
if you want to produce linear variation of perceived pitch and loudness. The dBtoA subpatch maps a linear range of decibels
onto an exponential amplitude curve. The pow~ object allows exponential calculations with signals.
MIDI Synthesizer Control
Tutorial 19: MIDI Synthesizer Control
Open the tutorial.

Implementing standard MIDI messages


In this chapter we'll demonstrate how to implement MIDI control of a synthesis instrument built in MSP. The example
instrument is a MIDI FM synthesizer with velocity sensitivity, pitch bend, and mod wheel control of timbre. To keep the
example relatively simple, we use only a single type of FM sound (a single patch, in synthesizer parlance), and only 2-voice
polyphony.

The main issues involved in MIDI control of an MSP synthesizer are

converting a MIDI key number into the proper equivalent frequency

converting a MIDI pitch bend value into an appropriate frequency-scaling factor

converting a MIDI controller value into a modulator parameter (such as vibrator rate, vibrato depth, etc.).

Additionally, since a given MSP object can only play one note at a time, we will need to handle simultaneous MIDI note
messages gracefully.

Polyphony
Each sound-generating object in MSP -- an oscillator such as cycle~ or phasor~, or a sample player such as groove~ or
play~ -- can only play one note at a time. Therefore, to play more than one note at a time in MSP you need to have more
than one sound-generating object. In this tutorial patch, we make two identical copies of the basic synthesis signal network,
and route MIDI note messages to one or the other of them. This 2-voice polyphony allows some overlap of consecutive notes,
which normally occurs in legato keyboard performance of a melody.

Assign a voice number with poly to play polyphonic music

The poly object assigns a voice number -- 1 or 2 in this case -- to each incoming note message, and if more than two keys are
held down at a time poly provides note-off messages for the earlier notes so that the later notes can be played. The voice
number, key number, and velocity are packed together in a three-item list, and the route object uses the voice number to
send the key number and velocity to one synthesizer voice or the other. If your computer is fast enough, of course, you can
design synthesizers with many more voices. You can test the capability of your computer by adding more and more voices
and observing the CPU Utilization in the Audio Status window.

There is another way to manage polyphonic voice allocation in MSP -- the poly~ object. We'll look at the elegant and
efficient poly~ object (and its helper objects in, in~, out, out~, and thispoly~) in Tutorial 21; in the meantime, we'll use the
poly object to make polyphonic voice assignments for the simple case required for this tutorial.

Pitch bend
In this instrument we use MIDI pitch bend values from 0 to 127 to bend the pitch of the instrument up or down by two
semitones. Bending the pitch of a note requires multiplying its (carrier) frequency by some amount. For a bend of 2
semitones, we will need to calculate a bend factor ranging from 2 -2/12 (approximately 0.891) to 2 2/12 (approximately
1.1225).

MIDI pitch bend presents a unique mapping problem because, according to the MIDI protocol, a value of 64 is used to mean
no bend but 64 is not precisely in the center between 0 and 127. (The precise central value would be 63.5.) There are 64
values below 64 (0 to 63), but only 63 values above it (65 to 127). We will therefore need to treat upward bends slightly
differently from downward bends.
Downward bend is calculated slightly differently from upward bend

The downward bend values (0 to 63) are offset by -64 and divided by 384 so that the maximum downward bend (pitch bend
value 0) produces an exponent of -64/ 384, which is equal to -2/ 12. The upward bend values (64 to 127) are offset by -64
and divided by 378 so that an upward bend produces an exponent ranging from 0 to 63/ 378, which is equal to 2/ 12. The
pack and line~ objects are used to make the frequency factor change gradually over 20 milliseconds, to avoid creating the
effect of discrete stepwise changes in frequency.

Mod wheel
The mod wheel is used here to change the modulation index of our FM synthesis patch. The mapping is linear; we simply
divide the MIDI controller values by 16 to map them into a range from 0 to (nearly) 8. The precise way this range is used will
be seen when we look at the synthesis instrument itself.

Controller values mapped into the range 0 to 7.9375

The FM synthesizer
Double-click on one of the synthFMvoice~ subpatch objects to open its Patcher window.

The basis for this FM synthesis subpatch is the simpleFM~ subpatch introduced (and explained) in Tutorial 11. A typed-in
argument is used to set the harmonicity ratio at 1, yielding a harmonic spectrum. The MIDI messages will affect the
frequency and the modulation index of this FM sound. Let's look first at the way MIDI note and pitch bend information is
used to determine the frequency.

MIDI-to-frequency conversion
The object mtof is not a signal object, but it is very handy for use in MSP. It converts a MIDI key number into its equivalent
frequency.

Calculate the frequency of a given pitch

This frequency value is multiplied by the bend factor which was calculated in the main patch, and the result is used as the
carrier frequency in the simpleFM~ subpatch.
The frequency of the note calculated from key number and pitch bend data

Velocity control of amplitude envelope


MIDI note-on velocity is used in this patch, as in most synthesizers, to control the amplitude envelope. The tasks needed to
accomplish this are

Separate note-on velocities from note-off velocities.

Map the range of note-on velocities -- 1 to 127 -- into an amplitude range from 0 to 1 (a non- linear mapping is usually
best).

Map note-on velocity to rate of attack and decay of the envelope (in this case).

The first task is achieved easily with a select 0 object, so that note-on velocity triggers a function object to send the attack
and decay shape, and note-off velocity returns the amplitude to 0, as shown in the following example.

MIDI note-on velocity sets domain and range of the amplitude envelope

Before the function is triggered, however, we use the note-on velocity to set the domain and range, which determine the
duration and amplitude of the envelope. The expr object on the right calculates the amount of time in which the attack and
decay portions of the envelope will occur. Maximum velocity of 127 will cause them to occur in 100 ms, while a much lesser
velocity of 60 will cause them to occur in 496 ms. Thus notes that are played more softly will have a slower attack, as is the
case with many wind and brass instruments.

The expr object on the left maps velocity to an exponential curve to determine the amplitude.
Velocity mapped to amplitude with an exponent of 4

If we used a straight linear mapping, MIDI velocities from 127 to 64 (the range in which most notes are played) would cover
only about a 6 dB amplitude range. The exponential mapping increases this to about 24 dB, so that change in the upper range
of velocities produces a greater change in amplitude.

MIDI control of timbre


It's often the case that acoustic instruments sound brighter (contain more high frequencies) when they're played more
loudly. It therefore makes sense to have note-on velocity affect the timbre of the sound as well as its loudness. In the case of
brass instruments, the timbre changes very much in correlation with amplitude, so in this patch we use the same envelope to
control both the amplitude and the modulation index of the FM instrument. The envelope is sent to a *~ object to scale it
into the proper range. The +~ 8 object ensures that the modulation index affected by velocity ranges from 0 to 8 (when the
note is played with maximum velocity). As we saw earlier, in the main patch the modulation wheel can be used to increase
the modulation index still further (adding up to 8 more to the modulation index range).

Thus, the combination of velocity and mod wheel position can affect the modulation index substantially.

Envelope and mod wheel control modulation index

Listening only to MSP (with the volume turned down on your keyboard synth), play a single- line melody on the MIDI
keyboard. As you play, notice the effect that velocity has on the amplitude, timbre, and rate of attack. Move the mod wheel
upward to increase the over-all brightness of the timbre. You can also use the mod wheel to modulate the timbre during the
sustain portion of the note. Try out the pitch bend wheel to confirm that it has the intended effect on the frequency.

Summary
MIDI data can be used to control an MSP synthesis patch much like any other synthesizer. In normal instrument design,
MIDI key number and pitch bend wheel position are both used to determine the pitch of a played note. The key number
must be converted into frequency information with the mtof object. The pitch bend value must be converted into the proper
frequency bend factor, based on the twelfth-root-of-two per semitone used in equal temperament. Since the designated no-
bend value of 64 is not in the precise center of the 0 to 127 range, upward bend must be calculated slightly differently from
downward bend.

Note-on velocity is generally used to determine the amplitude of the note, and triggers the attack portion of the amplitude
envelope. The note-off message triggers the release portion of the envelope. The velocity value can be used to alter the range
of the envelope (or to provide a factor for scaling the amplitude). It is usually best to map velocity to amplitude exponentially
rather than linearly. Velocity can also be used to alter the rate of the envelope, and/or other parameters such as modulation
index.

An MSP object can only make one sound at a time, so if you want to play more than one simultaneous note via MIDI you will
need to assign each note a voice number with poly, and route each voice to a different MSP object. In the next tutorial, we'll
use the poly object to make polyphonic voice assignments for the simple case required for this tutorial. Tutorial 21 will
introduce another way to manage polyphonic voice allocation in MSP -- the poly~ object.

See Also
Name Description
mtof Convert a MIDI note number to frequency
poly Allocate notes to different voices
MIDI Sampler Control
Tutorial 20: MIDI Sampler Control
Open the tutorial.

Basic sampler features


In this chapter we demonstrate a design for playing pre-recorded samples from a MIDI keyboard. This design implements
some of the main features of a basic sampler keyboard: assigning samples to regions of the keyboard, specifying a base
(untransposed) key location for each sample, playing samples back with the proper transposition depending on which key is
played, and making polyphonic voice assignments. For the sake of simplicity, this patch does not implement control from the
pitchbend wheel or mod wheel, but the method for doing so would not be much different from that demonstrated in the
previous two chapters.

In this patch we use the groove~ object to play samples back at various speeds, in some cases using looped samples. As was
noted in Tutorial 19, if we want a polyphonic instrument we need as many sound-generating objects as we want separate
simultaneous notes. In this tutorial patch, we use four copies of a subpatch called samplervoice~ to supply four-voice
polyphony. As in Tutorial 19 we use a poly object to assign a voice number to each MIDI note, and we use route to send
the note information to the correct samplervoice~ subpatch.

poly assigns a voice number to each MIDI note, to send information to the correct subpatch

Before we examine the workings of the samplervoice~ subpatch, it will help to review what information is needed to play a
sample correctly.

1. The sound samples must be read into memory (in buffer~ objects), and a list of the memory locations (buffer~ names)
must be kept.

2. Each sample must be assigned to a region of the keyboard, and a list of the key assignments must be kept.

3. A list of the base key for each region -- the key at which the sample should play back untransposed -- must be kept.

4. A list of the loop points for each sample (and whether looping should be on or off) must be kept.

5. When a MIDI note message is received, and is routed to a samplervoice~ subpatch, the groove~ object in that
subpatch must first be told which buffer~ to read (based on the key region being played), how fast to play the sample (based
on the ratio between the frequency being played and the base key frequency for that region), what loop points to use for that
sample, whether looping is on or off, and what amplitude scaling factor to use based on the note- on velocity.

In this patch, the samples are all read into memory when the patch is first loaded.

Double-click on the p samplebuffers subpatch to open its Patcher window.


You can see that six samples have been loaded into buffer~ objects named sample1, sample2, etc. If, in a performance
situation, you need to have access to more samples than you can store at once in RAM, you can use read messages with
filename arguments to load new samples into buffer~ objects as needed.
Close the subpatch window. Click on the message box marked keyboard sample assignments.
This stores a set of numbered key regions in the funbuff object. (This information could have been embedded in the funbuff
and saved with the patch, but we left it in the message box here so that you can see the contents of the funbuff.) MIDI key
numbers 0 to 40 are key region 1, keys 41 to 47 are key region 2, etc. When a note-on message is received, the key number
goes into funbuff, and funbuff reports the key region number for that key. The key region number is used to look up other
vital information in the coll.

Note-on key number finds region number in funbuff, which looks up sample info in coll

Double-click on the coll object to see its contents.

1, 24 sample1 0 0 0;

2, 33 sample2 0 0 0;

3, 50 sample3 0.136054 373.106537 1;

4, 67 sample4 60.204079 70.476189 1;

5, 84 sample5 0 0 0;

6, 108 sample6 0 0 0;

coll contains sample information for each key region

The key region number is used to index the information in coll. For example, whenever a key from 48 to 52 is pressed,
funbuff sends out the number 3, and the information for key region 3 is recalled and sent to the appropriate
samplervoice~ subpatch. The data for each key region is: base key, buffer~ name, loop start time, loop end time, and loop
on/off flag.

The voice number from poly opens the correct outlet of gate so that the information from coll goes to the right subpatch.

Playing a sample: the samplervoice~ subpatch


Close the coll window, and double-click on one of the samplervoice~ subpatch objects to open its Patcher window.

The samplervoice~ subpatch


You can see that the information from coll is unpacked in the subpatch and is sent to the proper places to prepare the
groove~ object for the note that is about to be played. This tells groove~ what buffer~ to read, what loop times to use, and
whether looping should be on or off. Then, when the note information comes in the left inlet, the velocity is used to send an
amplitude value to the *~ object, and the note-on key number is used (along with the base key number received from the
right inlet) to calculate the proper playback speed for groove~ and to trigger groove~ to begin playback from time 0.

MSP sample rate vs. audio file sample rate


Close the subpatch window.

You're almost ready to begin playing samples, but there is one more detail to attend to first. To save storage space, the
samples used in this patch are mono AIFF files with a sample rate of 22,050 Hz. To hear them play properly you should set
the sample rate of MSP to that rate.

Double-click on the dac~ object to open the Audio Status window. Set the Sampling Rate to 22.050 kHz, then close the
Audio Status window.

Note: Resetting the sampling rate may not be possible, depending on your hardware.

The difference between the sample rate of an audio file and the sample rate being used in MSP is a potential problem when
playing samples. This method of resolving the difference suffices in this situation because the audio files are all at the same
sample rate and because these samples are the only sounds we will be playing in MSP. In other situations, however, you're
likely to want to play samples (perhaps with different sampling rates) combined with other sounds in MSP, and you'll want
to use the optimum sampling rate.

For such situations, you would be best advised to use the ratio between the audio file sample rate and the MSP sample rate
as an additional factor in determining the correct playback speed for groove~. For example, if the sample rate of the audio
file is half the sample rate being used by MSP, then groove~ should play the sample half as fast.
You can use the objects info~ and dspstate~ to find out the sampling rate of the sample and of MSP respectively, as
demonstrated in the following example.

Calculate playback speed based on the sampling rates of the audio file and of MSP

The note-on key number is used first to recall the information for the sample to be played. The name of a buffer~ is sent to
groove~ and info~. Next, a bang is sent to dspstate~ and info~. Upon receiving a bang, dspstate~ reports the sampling
rate of MSP and info~ reports the sampling rate of the AIFF file stored in the buffer~. In the lower left part of the example,
you can see how this sampling rate information is used as a factor in determining the correct playback speed for groove~.

Playing samples with MIDI


Turn audio on and set the Output Level number box to a comfortable listening level. Play a slow chromatic scale on the
MIDI keyboard to hear the different samples and their arrangement on the keyboard.

To arrange a unified single instrument sound across the whole keyboard, each key region should contain a sample of a note
from the same source. In this case, though, the samples are arranged on the keyboard in such a way as to make available a
full band consisting of drums, bass, and keyboard. This sort of multi-timbral keyboard layout is useful for simple keyboard
splits (such as bass in the left hand and piano in the right hand) or, as in this case, for accessing several different sounds on a
single MIDI channel with a sequencer.
For an example of how a multi-timbral sample layout can be used by a sequencer, click on the toggle marked Play
Sequence. Click on it again when you want to stop the sequence. Turn audio off. Double-click on the p sequence object to
open the Patcher window of the subpatch.

The p sequence subpatch

The seq sampleseq.midi object contains a pre-recorded MIDI file. The midiparse object sends the MIDI key number and
velocity to poly in the main patch. Each time the sequence finishes playing, a bang is sent out the right outlet of seq; the
bang is used to restart the seq immediately, to play the sequence as a continuous loop. When the sequence is stopped by the
user, a bang is sent to midiflush to turn off any notes currently being played.
When you have finished with this patch, don't forget to open the Audio Status window and restore the Sampling Rate to its
original setting.

Summary
To play samples from the MIDI keyboard, load each sample into a buffer~ and play the samples with groove~. For
polyphonic sample playback, you will need one groove~ object per voice of polyphony. You can route MIDI notes to
different groove~ objects using voice assignments from the poly object.
To assign each sample to a region of the MIDI keyboard, you will need to keep a list of key regions, and for each key region
you will need to keep information about which buffer~ to use, what transposition to use, what loop points to use, etc. A
funbuff object is good for storing keyboard region assignments. The various items of information about each sample can be
best stored together as lists in a coll, indexed by the key region number. When a note is played, the key region is looked up
in the funbuff, and that number is used to look up the sample information in coll.
The proper transposition for each note can be calculated by dividing the played frequency (obtained with the mtof object) by
the base frequency of the sample. The result is used as the playback speed for groove~. If the sampling rate of the recorded
samples differs from the sampling rate being used in MSP, that fact must be accounted for when playing the samples with
groove~. Dividing the audio file sampling rate by the MSP sampling rate provides the correct factor by which to multiply the
playback speed of groove~. The sampling rate of MSP can be obtained with the dspstate~ object. The sampling rate of the
AIFF file in a buffer~ can be obtained with info~ (Remember -- resetting the sampling rate may not be possible on your
hardware).

Note-on velocity can be used to control the amplitude of the samples. An exponential mapping of velocity to amplitude is
usually best. Multi-timbral sample layouts on the keyboard can be useful for playing many different sounds, especially from
a sequencer. The end-of-file bang from the right outlet of seq can be used to restart the seq to play it in a continuous loop.
If the MIDI data goes through a midiflush object, any notes that are on when the seq is stopped can be turned off by
sending a bang to midiflush.

See Also
Name Description
buffer~ Store audio samples
dspstate~ Report current DSP settings
groove~ Variable-rate looping sample playback
poly~ Manage polyphony/DSP for patchers
Using the poly~ Object
Tutorial 21: Using the poly~ Object
Open the tutorial.

A different approach to polyphony


In the last chapter, we demonstrated how to use the poly object to make polyphonic voice assignments in a simple case. This
chapter will describe a more elegant and efficient way to handle polyphonic voice allocation -- the poly~ object.
In the example in the previous chapter, we created multiple copies of our sampler subpatch and used the poly object's voice
numbering to route messages to different copies of the subpatch. Our example could just as easily have used any kind of
sound-producing subpatch. The following example uses the subpatch littlesynth~ to implement a simple four-voice
polyphonic synthesizer:

While this method works, it has two disadvantages. First, there's a lot of housekeeping necessary to duplicate and patch the
multiple copies of littlesynth~ together. But there is also a problem in terms of CPU usage. All four copies of the
littlesynth~ subpatcher are always on, processing their audio even when there is no sound being produced.

MSP 2.0, introduces a different way to solve the problem -- the poly~ object allows you to create and manage multiple
copies of the same MSP subpatch all within one object. You can also control the signal processing activity within each copy of
the subpatch to conserve CPU resources.

The poly~ object


The poly~ object takes as its argument the name of a patcher file, followed by a number that specifies the number of copies
(or instances) of the patch to be created. You'll want to specify the same number of copies as you would have had to
duplicate manually when implementing polyphony the old-fashioned way. Here's an example of the poly~ object.

Double-clicking on the poly~ object opens up the subpatcher to show you the inside of the littlebeep~ object:
Let's look at the littlebeep~ patch for a minute. While you haven't seen the in, out~, or thispoly~ objects before, the rest of
the patcher is pretty straightforward; it takes an incoming MIDI note number, converts it to a frequency value using the
mtof object, and outputs a sine wave at that frequency with a duration of 140 milliseconds and an amplitude envelope
supplied by the line~ object for 140 ms with an envelope on it.
But what about the in and out~ objects? Subpatches created for use in the poly~ object use special objects for inlets and
outlets. The objects in and out create control inlets and outlets, and the in~ and out~ objects create signal inlets and outlets.
You specify which inlet is assigned to which object by adding a number argument to the object -- the in 1 object corresponds
to the leftmost inlet on the poly~ object, and so on. The poly~ object keeps track of the number of inlets and outlets it needs
to create when you tell it which subpatch to load.

Messages sent to a poly~ object are directed to different instances of the subpatch dynamically using the note and midinote
messages, and manually using the target message.

When poly~ receives a note message in its left inlet, it scans through the copies of the subpatch it has in memory until it
finds one that is currently not busy, and then passes the message to it. A subpatch instance can tell its parent poly~ object
that it is busy using the thispoly~ object. The thispoly~ object accepts either a signal or number in its inlet to set its busy
state. A zero signal or a value of 0 sent to its inlet tells the parent poly~ that this instance is available for note or midinote
messages. A non-zero signal or value sent to its inlet tells the parent poly~ that the instance is busy; no note or midinote
messages will be sent to the object until it is no longer busy. The busy state was intended to correspond to the duration of a
note being played by the subpatcher instance, but it could be used to mean anything. In the example above, when the audio
level out of the *~ is nonzero -- that iteration of the subpatch is currently busy. Once the amplitude envelope out of line~
reaches zero and the sound stops, that subpatch's copy of thispoly~ tells poly~ that it is ready for more input.
The thispoly~ object can also control the activity of signal processing within each copy of the subpatch. When the mute
message is sent to thispoly~ followed by a 1, all signal processing in that subpatch stops. When a mute 0message is
received, signal processing starts again.

We can rewrite the littlebeep~ subpatcher to take advantage of this by turning off signal processing when a note is finished
and turning it on again when a new event is received:

While this doesn't change the function of the patch, it would be more efficient, since the amount of CPU allocated is always
based on the number of notes currently sounding.

Another way to allocate events using poly~ is through the target message. Sending a target message followed by an integer
in the left inlet of a poly~ subpatch tells poly~ to send all subsequent messages to that instance of the subpatch. You can
then use poly~ in conjunction with the poly object from the last chapter to create a MIDI synthesizer.

A poly~ subpatch that uses the target message looks like this:
In this example subpatcher, pairs of incoming MIDI pitches and velocities are used to synthesize a sine tone. When a list is
received, the subpatcher sends a bang to thispoly~, causing it to output the instance or voice number. In the example
below, the voice number is sent out an outlet so you can watch it from the parent patch.

In the parent patch the poly object assigns voice numbers to MIDI pitch/velocity pairs output by makenote. The voice
number from the poly object is sent to poly~ with the target message prepended to it, telling poly~ to send subsequent data
to the instance of the targetbeep~ subpatcher specified by poly~. When a new note is generated, the target will change.
Since poly keeps track of note-offs, it should recycle voices properly. The second outlet of poly~ reports the voice that last
received a message -- it should be the same as the voice number output by poly, since we're using poly to specify a specific
target.

Thfloating-point number box object can be used to specify parameters to specific instances of a poly~ subpatcher. By
connecting a loadbang object to thispoly~, we can use the voice number to control the center frequency of a filter:
The littlefilter~ subpatcher, shown here uses the voice number from thispoly~ and multiplies it by the base frequency
received in the second inlet. The incoming signal is filtered by all sixteen instances simultaneously, with the output amplitude
of each instance being controlled by an integer coming into the first inlet.

Here's an example of a patch which uses littlefilter~

The metro object is hooked up to both a counter and a random. The counter, which feeds the target message, cycles
through the 16 voices of littlefilter~ loaded into the poly~ object, supplying each with a random number which is used to
control the amplitude of that voice.

A signal connected to an inlet of poly~ will be sent to the corresponding in~ objects of all subpatcher instances, so the
noise~ object in the example above feeds noise to all the subpatchers inside the poly~. The second inlet (which corresponds
to the in 2 box in the subpatcher) controls the base frequency of the filters. Note that for the frequency to get sent to all
poly~ iterations it is preceded by a target 0 message. You can open a specific instance of a poly~ subpatch by giving the
object the open message, followed by the voice you want to look at.

The subpatch assigned to voice number 15 looks like this:


As you can see, the base frequency of this particular iteration of littlefilter~ is 1500. Hz, which is the multiple of the voice
number (15) with the most recently entered base frequency into the second inlet (100. Hz).

Summary
poly~ is a powerful way to manage multiple copies of the same subpatch for polyphonic voice allocation. The thispoly~
object works inside a subpatch to control its busy state and turn signal processing on and off. The objects in, in~, out, and
out~ create special control and signal inputs and outputs that work with the inlets and outlets of the poly~ object.

See Also
Name Description
in Message input for a patcher loaded by poly~ or pfft~
in~ Signal input for a patcher loaded by poly~
out Message output for a patcher loaded by poly~ or pfft~
out~ Signal output for a patcher loaded by poly~
poly~ Manage polyphony/DSP for patchers
thispoly~ Control poly~ voice allocation and muting
MIDI Panning
Tutorial 22: MIDI Panning
Open the tutorial.

Panning for localization and distance effects


Loudness is one of the cues we use to tell us how far away a sound source is located. The relative loudness of a sound in each
of our ears is a cue we use to tell us in what direction the sound is located. (Other cues for distance and location include
inter-aural delay, ratio of direct to reflected sound, etc. For now we"ll only be considering loudness.)

When a sound is coming from a single speaker, we localize the source in the direction of that speaker. When the sound is
equally balanced between two speakers, we localize the sound in a direction precisely between the speakers. As the balance
between the two speakers varies from one to the other, we localize the sound in various directions between the two speakers.

The term panning refers to adjusting the relative loudness of a single sound coming from two (or more) speakers. On analog
mixing consoles, the panning of an input channel to the two channels of the output is usually controlled by a single knob. In
MIDI, panning is generally controlled by a single value from 0 to 127. In both cases, a single continuum is used to describe
the balance between the two stereo channels, even though the precise amplitude of each channel at various intermediate
points can be calculated in many different ways.

All other factors being equal, we assume that a softer sound is more distant than a louder sound, so the overall loudness
effect created by the combined channels will give us an important distance cue. Thus, panning must be concerned not only
with the proper balance to suggest direction of the sound source; it must also control the perceived loudness of the combined
speakers to suggest distance.

This tutorial demonstrates three ways of calculating panning, controllable by MIDI values 0 to 127. You can try out the three
methods and decide which is most appropriate for a given situation in which you might want to control panning.

Patch for testing panning methods


To see how the sound is generated, double-click on the p sound source subpatch to open its Patcher window.

Because of the gate~ and begin~ objects, audio processing is off in this subpatch until a 1is received in the inlet to open the
gate~. At that time, the phasor~ generates a linear frequency glissando going from 2000 to 200 two times per second.

The p sound sourcesubpatch

Close the subpatch window.

The output of this subpatch is sent to two *~ objects -- one for each output channel -- where its amplitude at each output
channel will be scaled by one of the panning algorithms. You can choose the panning algorithm you want to try from the
pop-up umenu at the top of the patch. This opens the inlet of the two selector~ objects to receive the control signals from
the correct panning subpatch. It also opens an outlet of the gate object to allow control values into the desired subpatch. The
panning is controlled by MIDI input from continuous controller No. 10 (designated for panning in MIDI).
In case your MIDI keyboard doesn"t send controller 10 easily, you can also use the pitch bend wheel to test the panning. (For
that matter, you don"t need MIDI at all. You can just drag on the number box marked MIDI panning.)

Selection from the umenu opens input and output for one of the three panning subpatches

Linear crossfade
The most direct way to implement panning is to fade one channel linearly from 0 to 1 as the other channel fades linearly
from 1 to 0. This is the easiest type of panning to calculate. We map the range of MIDI values 0 to 127 onto the amplitude
range 0 to 1, and use that value as the amplitude for the right channel; the left channel is always set to 1 minus the amplitude
of the left channel. The only hitch is that a MIDI pan value of 64 is supposed to mean equal balance between channels, but it
is not precisely in the center of the range (64/ 127 - 0.5). So we have to treat MIDI values 0 to 64 differently from values 65
to 127.

Double-click on the p simple linear xfade object to open its Patcher window.

Linear crossfade using MIDI values 0 to 127 for control

This method seems perfectly logical since the sum of the two amplitudes is always 1. The problem is that the intensity of the
sound is proportional to the sum of the squares of the amplitudes from each speaker. That is, two speakers playing an
amplitude of 0.5 do not provide the same intensity (thus not the same perceived loudness) as one speaker playing an
amplitude of 1. With the linear crossfade, then, the sound actually seems softer when panned to the middle than it does
when panned to one side or the other.

Close the subpatch window. Choose Simple Linear Crossfade from the umenu. Click on the ezdac~ to turn audio on, click
on the toggle to start the chirping sound, and use the Amplitude number box to set the desired listening level. Move the
pitch bend wheel of your MIDI keyboard to pan the sound slowly from one channel to the other. Listen to determine if the
loudness of the sound seems to stay constant as you pan.
While this linear crossfade might be adequate in some situations, we may also want to try to find a way to maintain a
constant intensity as we pan.

Equal distance crossfade


If we can maintain a constant intensity as we pan from one side to the other, this will give the impression that the sound
source is maintaining a constant distance from the listener. Geometrically, this could only be true if the sound source were
moving in an arc, with the listener at the center, so that the distance between the sound source and the listener was always
equal to the radius of the arc.

It happens that we can simulate this condition by mapping one channel onto a quarter cycle of a cosine wave and the other
channel onto a quarter cycle of a sine wave. Therefore, we"ll map the range of MIDI values 0 to 127 onto the range 0 to 0.25,
and use the result as an angle for looking up the cosine and sine values.

Technical detail: As the sound source travels on a hypothetical arc from 0 to 90 (1 / 4 cycle around a
circle with the listener at the center), the cosine of its angle goes from 1 to 0 and the sine of its angle goes from 0 to 1.
At all points along the way, the square of the cosine plus the square of the sine equals 1. This trigonometric identity is
analogous to what we are trying to achieve -- the sum of the squares of the amplitudes always equaling the same
intensity -- so these values are a good way to obtain the relative amplitudes necessary to simulate a constant distance
between sound source and listener.

Double-click on the p"constant distance xfade"object to open its Patcher window.

MIDI values 0 to 127 are mapped onto 1/4 cycle of cosine and sine functions

Once again we need to treat MIDI values greater than 64 differently from those less than or equal to 64, in order to retain 64
as the center of the range. Once the MIDI value is mapped into the range 0 to 0.25, the result is used as a phase angle two
cycle~ objects, one a cosine and the other (because of the additional phase offset of 0.75) a sine.

Close the subpatch window. Choose Equal Distance Crossfade from the umenu. Listen to the sound while panning it
slowly from one channel to the other.

Is the difference from the linear crossfade appreciable? Perhaps you don"t care whether the listener has the impression of
movement in an arc when listening to the sound being panned. But the important point is that the equal distance method is
preferable if only because it does not cause a noticeable dip in intensity when panning from one side to the other.

Speaker-to-speaker crossfade
Given a standard stereo speaker placement -- with the two speakers in front of the listener at equal distances and angles -- if
an actual sound source (say, a person playing a trumpet) moved in a straight line from one speaker to the other, the sound
source would actually be closer to the listener when it"s in the middle than it would be when it"s at either speaker. So, to
emulate a sound source moving in a straight line from speaker to speaker, we will need to calculate the amplitudes such that
the intensity is proportional to the distance from the listener.
Distance b is shorter than distance a

Technical detail: If we know the angle of the speakers (x and -x), we can use the cosine function to calculate distance
a relative to distance b. Similarly we can use the tangent function to calculate distance c relative to b. The distance
between the speakers is thus o) from the center ranging from -c to +c. Knowing b and o, we can use the Pythagorean
theorem to obtain the distance (y). Armed with all of this information, we can finally calculate the gain for the two
channels as a cos(yx)/d.

Choose Speaker-to-Speaker Crossfade from the umenu. Listen to the sound while panning it slowly from one channel to
the other. You can try different speaker angles by changing the value in the Speaker Angle number box. Choose a speaker
angle best suited to your actual speaker positions.

This effect becomes more pronounced as the speaker angle increases. It is most effective with normal speaker angles
ranging from about 30 up to 45, or even up to 60. Below 30 the effect is too slight to be very useful, and above about 60
it"s too extreme to be realistic.

Double-click on the p"speaker-to-speaker xfade" object to open its Patcher window.


The trigonometric calculations described above are implemented in this subpatch. The straight ahead distance (b) is set at 1,
and the other distances are calculated relative to it. The speaker angle -- specified in degrees by the user in the main patch --
is converted to a fraction of a cycle, and is eventually converted to radians (multiplied by 2, or 6.2832) for the trigonometric
operations. When the actual gain value is finally calculated, it is multiplied by a normalizing factor of 2/ (d+b) to avoid
clipping. When the source reaches an angle greater than 90 from one speaker or the other, that speaker"s gain is set to 0.

To help get a better understanding of these calculations, move the pitch bend wheel and watch the values change in the
subpatch. Then close the subpatch and watch the gain values change in the main Patcher window.

The signal gain values are displayed by an MSP user interface object called number~, which is explained in the next chapter.

Summary
MIDI controller No. 10 (or any other MIDI data) can be used to pan a signal between output channels. The relative amplitude
of the two channels gives a localization cue for direction of the sound source. The overall intensity of the sound (which is
proportional to the sum of the squares of the amplitudes) is a cue for perceived distance of the sound source.

Mapping the MIDI data to perform a linear crossfade of the amplitudes of the two channels is one method of panning, but it
causes a drop in intensity when the sound is panned to the middle. Using the panning value to determine the angle of the
sound source on an arc around the listener (mapped in a range from 0 to 90), and setting the channel amplitudes
proportional to the cosine and sine of that angle, keeps the intensity constant as the sound is panned.

When a sound moves past the listener in a straight line, it is loudest when it passes directly in front of the listener. To
emulate straight line movement, one can calculate the relative distance of the sound source as it travels, and modify the
amplitude of each channel (and the overall intensity) accordingly.

See Also
Name Description
expr Evaluate a mathematical expression
gate~ Route a signal to one of several outlets
Viewing Signal Data
Tutorial 23: Viewing Signal Data

Open the tutorial.

Display the value of a signal: number~


This chapter demonstrates several MSP objects for observing the numerical value of signals, and/ or for translating those
values into Max messages.

Turn audio on and send some sound into the input jacks of the computer.

Every 250 milliseconds the number~ objects at the top of the Patcher display the current value of the signal coming in each
channel, and the meter~ objects show a graphic representation of the peak amplitude value in the past 250 milliseconds,
like an analog LED display.

Current signal value is shown by number~; peak amplitude is shown by meter~

The signal coming into number~ is sent out its right outlet as a float once every time it's displayed. This means it is possible
to sample the signal value and send it as a message to other Max objects.

The number~ object is actually like two objects in one. In addition to receiving signal values and sending them out the right
outlet as a float, number~ also functions as a floating-point number box that sends a signal (instead of a float) out its left
outlet.

Move the mod wheel of your MIDI keyboard or drag on the right side of the number~ marked Amplitude. This sets the
value of the signal being sent out the number~ object's left outlet. The signal is connected to the right inlet of two *~ objects,
to control the amplitude of the signal sent to the ezdac~.

float input to number~ sets the value of the signal sent out the left outlet

A number~ object simultaneously converts any signal it receives into floats sent out the right outlet, and converts any float
it receives into a signal sent out the left outlet. Although it can perform both tasks at the same time, it can only display one
value at a time. The value displayed by number~ depends on which display mode it is in. When a small waveform appears
in the left part of the number~, it is inSignal Output Mode, and shows the value of the signal going out the left outlet.
The two display modes of number~

You can restrict number~ to one display mode or the other by selecting the object in an unlocked Patcher and choosing Get
Info... from the Object menu.

Allowed display modes can be chosen in the number~ Inspector

At least one display mode must be checked. By default, both display modes are allowed, as shown in the above example. If
both display modes are allowed, you can switch from one display mode to the other in a locked Patcher by clicking on the left
side of the number~. The output of number~ continues regardless of what display mode it's in.
In the tutorial patch you can see the two display modes of number~. The number~ objects at the top of the Patcher window
are in Signal Monitor Mode because we are using them to show the value of the incoming signal. The Amplitude number~
is in Signal Output Mode because we are using it to send a signal and we want to see the value of that signal. (New values
can be entered into a number~ by typing or by dragging with the mouse only when it is in Signal Output display mode.)
Since each of these number~ objects is serving only one function, each has been restricted to only one display mode in the
Inspector window.

Click on the left side of the number~ objects. They don't change display mode because they have been restricted to one
mode or the other in the Inspector window.

Interpolation with number~


The number~ object has an additional useful feature. It can be made to interpolate between input values to generate a ramp
signal much like the line~ object. If number~ receives a non-zero number in its right inlet, it uses that number as an
amount of time, in milliseconds, to interpolate linearly to the new value whenever it receives a number in the left inlet. This
is equivalent to sending a list to line~.
number~ can send a linear ramp signal from its old value to a new value

Unlike line~, however, number~ does not need to receive the interpolation time value more than once; it remembers the
interpolation time and uses it for each new number received in the left inlet. This feature is used for the Amplitude
number~ so that it won't cause discontinuous changes of amplitude in the output signal.

Peak amplitude: meter~


The meter~ object periodically displays the peak amplitude it has received since the last display. At the same time it also
sends the peak signal value out its outlet as a float. The output value is always a positive number, even if the peak value was
negative.

meter~ displays the peak signal amplitude and sends it out as a float

meter~ is useful for observing the peak amplitude of a signal (unlike number~, which displays and sends out the
instantaneous amplitude of the signal). Since meter~ is intended for audio signals, it expects to receive a signal in the range
-1 to 1. If that range is exceeded, meter~ displays a red clipping LED as its maximum.
If you want to see the clipping display, increase the amplitude of the output signal until it exceeds 1. (Then return it to a
desirable level.)

The default interval of time between the display updates of meter~ is 250 milliseconds, but the display interval can be
altered with the interval message. A shorter display interval makes the LED display more accurate, while a longer interval
gives you more time to read its visual and numerical output.

You can try out different display intervals by changing the number in the number box marked Display Interval in the
lower left corner of the Patcher window.

By the way, the display interval of a number~ object can be set in the same manner (as well as via its Inspector window).

Use a signal to generate Max messages: snapshot~


The snapshot~ object sends out the current value of a signal, as does the right inlet of number~. With snapshot~, though,
you can turn the output on and off, or request output of a single value by sending it a bang. When you send a non-zero
number in the right inlet, snapshot~ uses that number as a millisecond time interval, and begins periodically reporting the
value of the signal in its left inlet. Sending in a time interval of 0 stops snapshot~.
This right half of the tutorial patch shows a simple example of how a signal waveform might be used to generate MIDI data.
We'll sample a sub-audio cosine wave to obtain pitch values for MIDI note messages.

Use the number~ to set the output amplitude to 0. In the number box objects at the top of the patch, set the Rate
number box to 0.14 and set the Depth number box to 0.5. Click on the message box 200 to start snapshot~ reporting
signal values every fifth of a second.

Because snapshot~ is reporting the signal value every fifth of a second, and the period of the cycle~ object is about 7
seconds, the melody will describe one cycle of a sinusoidal wave every 35 notes. Since the amplitude of the wave is 0.5, the
melody will range from 36 to 84 (6024).
Experiment with different Rate and Depth values for the cycle~. Since snapshot~ is sampling at a rate of 5 Hz (once
every 200 ms), its Nyquist rate is 2.5 Hz, so that limits the effective frequency of the cycle~ (any greater frequency will be
folded over). Click on the 0 message box to stop snapshot~.

Amplitude modulation
Set the tremolo depth to 0.5 and the tremolo rate to 4. Increase the output amplitude to a desirable listening level.

The cycle~ object is modulating the amplitude of the incoming sound with a 4 Hz tremolo.

Experiment with faster (audio range) rates of modulation to hear the timbral effect of amplitude modulation. To hear ring
modulation, set the modulation depth to 1. To remove the modulation effect, simply set the depth to 0.

View a signal excerpt: capture~


The capture~ object is comparable to the Max object capture. It stores many signal values (the most recently received 4096
samples, by default), so that you can view an entire excerpt of a signal as text.

Set the tremolo depth to 1, and set the tremolo rate to 172. Double-click on the capture~ object to open a text window
containing the last 4096 samples.

This object is useful for seeing precisely what has occurred in a signal over time. (4096 samples is about 93 milliseconds at a
sampling rate of 44.1 kHz.) You can type in an argument to specify how many samples you want to view, and capture~ will
store that many samples (assuming there is enough RAM available in Max. There are various arguments and messages for
controlling exactly what will be stored by capture~. See its description in the MSP Reference Manual for details.

Summary
The capture~ object stores a short excerpt of a signal to be viewed as text. The meter~ object periodically displays the peak
level of a signal and sends the peak level out its outlet as a float. The snapshot~ object sends out a float to report the
current value of a signal. snapshot~ reports the signal value once when it receives a bang, and it can also report the signal
value periodically if it receives a non-zero interval time in its right inlet.

The number~ object is like a combination of a float number box, sig~, and snapshot~, all at once. A signal received in its
left inlet is sent out the right outlet as a float, as with snapshot~. A float or int received in its left inlet sets the value of the
signal going out its left outlet, as with sig~. Both of these activities can go on at once in the same number~ object, although
number~ can only display one value at a time. When number~ is in Signal Output Mode, it displays the value of the
outgoing signal.
number~ can also function as a signal ramp generator, like the line~ object. If a non-zero number has been received in the
right inlet (representing interpolation time in milliseconds), whenever number~ receives a float, its output signal
interpolates linearly between the old and new values.

These objects (along with a few others such as sig~floating-point number box and avg~) comprise the primary links
between MSP and Max. They convert signals to numerical Max messages, or vice versa.

See Also
Name Description
capture~ Store a signal to view as text
meter~ Visual peak level indicator
number~ Signal monitor and constant generator
snapshot~ Convert signal values to numbers
Oscilloscope
Tutorial 24: Oscilloscope
Open the tutorial.

Graph of a signal over time


There are times when seeing a picture of a signal is instructive. The scope~ object depicts the signal it receives, in the
manner of an analog oscilloscope, as a graph of amplitude over time.

There are two problems scope~ must consider when plotting a graph of a signal in real time. First of all, in order for your
eye to follow a time-varying signal, an excerpt of the signal must be captured and displayed for a certain period of time (long
enough for you really to see it). Therefore, the graph must be displayed periodically, and will always lag a bit behind what you
hear. Second, there aren't enough pixels on the screen for you to see a plot of every single sample (at least, not without the
display being updated at blinding speed), so scope~ has to use a single pixel to summarize many samples.

A patch to view different waveforms


This tutorial shows how to get a useful display of a signal. The patch adds four cosine oscillators to create a variety of
waveforms, and displays them in scope~. The frequency, phase, and amplitude of each sinusoid is set independently, and
the over-all amplitude of the sum of the oscillators is scaled with an additional *~ object. The settings for each waveform are
stored in a preset object.

Additive synthesis can be used to create a variety of complex waveforms

Click on the first preset in the preset object.

When audio is turned on, the dspstate~ object sends the current sampling rate out its middle outlet. This is divided by the
number of pixels per display buffer (the display buffer is where the display points are held before they're shown on the
screen), and the result is the number of signal samples per display point (samples per pixel). This number is sent in the left
inlet of scope~ to tell it how many samples to assign to each display pixel. The default number of pixels per display buffer is
128, so by this method each display will consist of exactly one second of signal. In other words, once per second scope~
displays the second that has just passed. We have stretched the scope~ (using its grow handle) to be 256 pixels wide -- twice
its default width -- in order to provide a better view.

On the next page we will describe the different waveforms created by the oscillators.

One by one, click on the different presets to see different waveforms displayed in the scope~. The first eight waves are at
the sub-audio frequency of 1 Hz to allow you to see a single cycle of the waveform, so the signal is not sent to the dac~ until
the ninth preset is recalled.

Preset 1. A 1 Hz cosine wave.

Preset 2. A 1 Hz sine wave. (A cosine wave with a phase offset of 3 / 4 cycle.)

Preset 3. A 1 Hz cosine wave plus a 2 Hz cosine wave (i.e. octaves).

Preset 4. Four octaves: cosine waves of equal amplitude at 1, 2, 4, and 8 Hz.

Preset 5. A band-limited square wave. The four oscillators produce four sine waves with the correct frequencies and
amplitudes to represent the first four partials of a square wave. (Although the amplitudes of the oscillators are only shown to
two decimal places, they are actually stored in the preset with six decimal place precision.)

Preset 6. A band-limited sawtooth wave. The four oscillators produce four sine waves with the correct frequencies and
amplitudes to represent the first four partials of a sawtooth wave.

Preset 7. A band-limited triangle wave. The four oscillators produce four sine waves with the correct frequencies and
amplitudes to represent the first four partials of a triangle wave (which, it appears, is actually not very triangular without its
upper partials).

Preset 8. This wave has the same frequencies and amplitudes as the band-limited square wave, but has arbitrarily chosen
phase offsets for the four components. This shows what a profound effect the phase of components can have on the
appearance of a waveform, even though its effect on the sound of a waveform is usually very slight.

Preset 9. A 32 Hz sinusoid plus a 36 Hz sinusoid (one-half cycle out of phase for the sake of the appearance in the scope~).
The result is interference causing beating at the difference frequency of 4 Hz.

Preset 10. Combined sinusoids at 200, 201, and 204 Hz, producing beats at 1, 3, and 4 Hz.

Preset 11. Although the frequencies are all displayed as 200 Hz, they are actually 200, 200.25, 200.667, and 200.8. This
produces a complicated interference pattern of six different sub-audio beat frequencies, a pattern which only repeats
precisely every minute. We have set the number of samples per pixel much lower, so each display represents about 50 ms.
This allows you to see about 10 wave cycles per display.

Preset 12. Octaves at 100, 200, and 400 Hz (with different phase offsets), plus one oscillator at 401 Hz creating beats at 1
Hz.

Preset 13. A cluster of equal-tempered semitones. The dissonance of these intervals is perhaps all the more pronounced
when pure tones are used. Each display shows about 100 ms of sound.

Preset 14. A just-tuned dominant seventh chord; these are the 4th, 5th, 6th, and 7th harmonics of a common fundamental,
so their sum has a periodicity of 100 Hz, two octaves below the chord itself.

Preset 15. Total phase cancellation. A sinusoid is added to a copy of itself 180 out of phase.

Preset 16. All oscillators off.

Summary
The scope~ object gives an oscilloscope view of a signal, graphing amplitude over time. Because scope~ needs to collect the
samples before displaying them, and because the user needs a certain period of time to view the signal, the display always
lags behind the signal by one display period. A display period (in seconds) is determined by the number of pixels per display
buffer, times the number of samples per pixel, divided by the signal sampling rate. You can control those first two values by
sending integer values in the inlets of scope~. The sampling rate of MSP can be obtained with the dspstate~ object.

See Also
Name Description
dspstate~ Report current DSP settings
scope~ Visualize an audio signal
Using the FFT
Tutorial 25: Using the FFT
Open the tutorial.

Fourier's theorem
The French mathematician Joseph Fourier demonstrated that any periodic wave can be expressed as the sum of
harmonically related sinusoids, each with its own amplitude and phase. Given a digital representation of a periodic wave, one
can employ a formula known as the discrete Fourier transform (DFT) to calculate the frequency, phase, and amplitude of its
sinusoidal components. Essentially, the DFT transforms a time-domain representation of a sound wave into a frequency-
domain spectrum. This spectrum can also be transformed back into a time-domain waveform.

Typically the Fourier transform is used on a small slice of time, which ideally is equal to exactly one cycle of the wave being
analyzed. To perform this operation on real world sounds -- which are almost invariably not strictly periodic, and which
may be of unknown frequency -- one can perform the DFT on consecutive time slices to get a sense of how the spectrum
changes over time.

If the number of digital samples in each time slice is a power of 2, one can use a faster version of the DFT known as the fast
Fourier transform (FFT). The formula for the FFT is encapsulated in the fft~ object. The mathematics of the Fourier
transform are well beyond the scope of this manual, but this tutorial chapter will demonstrate how to use the fft~ object for
signal analysis and resynthesis.

Spectrum of a signal: fft~


fft~ receives a signal in its inlet. For each slice of time it receives (512 samples long by default) it sends out a signal of the
same length listing the amount of energy in each frequency region. The signal that comes out of fft~ is not anything you're
likely to want to listen to. Rather, it's a list of relative amplitudes of 512 different frequency bands in the received signal. This
list happens to be exactly the same length as the samples received in each time slice, so it comes out at the same rate as the
signal comes in. The signal coming out of fft~ is a frequency-domain analysis of the samples it received in the previous time
slice.

Although the transform comes out of fft~ in the form of a signal, it is not a time-domain signal. The only object that
understands this special signal is the ifft~ object, which performs an inverse FFT on the spectrum and transforms it back
into a time-domain waveform.

The signal coming out of fft~ is spectral information, not a time-domain signal

With the capture~ object you can grab some of the output of fft~ and examine the frequency analysis of a signal.

Click on one of the ezdac~ objects to turn audio on.

When audio is turned on, dspstate~ sends the MSP sampling rate out its middle outlet. We use this number to calculate a
frequency that has a period of exactly 512 samples. This is the fundamental frequency of the FFT itself. If we send a wave of
that frequency into fft~, each time slice would contain exactly one cycle of the waveform. We will actually use a cosine wave
at ten times that frequency as the test tone for our analysis, as shown below.

The test tone is at 10 times the base frequency of the FFT time slice

The upper left corner of the Patcher window shows a very simple use of fft~. The analysis is stored in a capture~ object, and
an ifft~ object transforms the analysis back into an audio signal. (Ordinarily you would not transform and inverse-transform
an audio signal for no reason like this. The ifft~ is used in this patch simply to demonstrate that the analysis-resynthesis
process works.)

Click on the toggle in the upper left part of the patch to hear the resynthesized sound. Click on the toggle again to close
the gate~. Now double-click on the capture~ object in that part of the patch to see the analysis performed by fft~.
In the capture~ text window, the first 512 numbers are all 0.0000. That is the output of fft~ during the first time slice of its
analysis. Remember, the analysis it sends out is always of the previous time slice. When audio was first turned on, there was
no previous audio, so the fft~ object's analysis shows no signal.
Scroll past the first 512 numbers. (The numbers in the capture~ object's text window are grouped in blocks, so if your
signal vector size is 256 you will have two groups of numbers that are all 0.0000.) Look at the second time slice of 512
numbers.

Each of the 512 numbers represents a harmonic of the FFT frequency itself, starting at the 0th harmonic (0 Hz). The analysis
shows energy in the eleventh number, which represents the 10th harmonic of the FFT, 10/ 512 the sampling rate -- precisely
our test frequency. (The analysis also shows energy at the 10th number from the end, which represents 502/ 512 the sampling
rate. This frequency exceeds the Nyquist rate and is actually equivalent to -10/ 512 of the sampling rate.

Technical detail: An FFT divides the entire available frequency range into as many bands (regions) as
there are samples in each time slice. Therefore, each set of 512 numbers coming out of fft~ represents
512 divisions of the frequency range from 0 to the sampling rate. The first number represents the
energy at 0 Hz, the second number represents the energy at 1 / 512 the sampling rate, the third number
represents the energy at 2 / 512 the sampling rate, and so on.

Note that once we reach the Nyquist rate on the 257th number (256/ 512 of the sampling rate), all numbers after that
are folded back down from the Nyquist rate. Another way to think of this is that these numbers represent negative
frequencies that are now ascending from the (negative) Nyquist rate. Thus, the 258th number is the energy at the
Nyquist rate minus 1/ 512 of the sampling rate (which could also be thought of as -255/ 512 the sampling rate). In our
example, we see energy in the 11th frequency region (10/ 512 the sampling rate) and the 503rd frequency region
(-256/ 512 - -246/ 512 = -10/ 512 the sampling rate).

It appears that fft~ has correctly analyzed the signal. There's just one problem...

Practical problems of the FFT


The FFT assumes that the samples being analyzed comprise one cycle of a periodic wave. In our example, the cosine wave
was the 10th harmonic of the FFT's fundamental frequency, so it worked fine. In most cases, though, the 512 samples of the
FFT will not be precisely one cycle of the wave. When that happens, the FFT still analyzes the 512 samples as if they were
one cycle of a waveform, and reports the spectrum of that wave. Such an analysis will contain many spurious frequencies not
actually present in the signal.

Close the text window of capture~. With the audio still on, set the Test Frequency number box to 1000. This also
triggers the clear message in the upper left corner of the patch to empty the capture~ object of its prior contents. Double-
click once again on capture~, and scroll ahead in the text window to see its new contents.
The analysis of the 1000 Hz tone does indeed show greater energy at 1000 Hz -- in the 12th and 13th frequency regions if
your MSP sampling rate is 44,100 Hz -- but it also shows energy in virtually every other region. That's because the waveform
it analyzed is no longer a sinusoid. (An exact number of cycles does not fit precisely into the 512 samples.) All the other
energy shown in this FFT is an artifact of the incorrect interpretation of those 512 samples as one period of the correct
waveform.

To resolve this problem, we can try to taper the ends of each time slice by applying an amplitude envelope to it, and use
overlapping time slices to compensate for the use of the envelope.

Overlapping FFTs
The lower right portion of the tutorial patch takes this approach of using overlapping time slices, and applies a triangular
amplitude envelope to each slice before analyzing it, and again after resynthesizing it. (Other shapes of amplitude envelope
are often used for this process, but the triangular window is simple and fairly effective.) In this way, the fft~ object is
viewing each time slice through a triangular window which tapers its ends down, thus filtering out many of the false
frequencies that would be introduced by discontinuities. This technique is known as windowing.

Overlapping triangular windows (envelopes) applied to a 100 Hz cosine wave

To accomplish this windowing and overlapping of time slices, we must perform two FFTs, one of which is offset 256 samples
later than the other. (Note that this part of the patch will only work if your current MSP Signal Vector size is 256 or less,
since fft~ can only be offset by a multiple of the vector size.) The offset of an FFT can be given as a (third) typed-in argument
to fft~, as is done for the fft~ object on the right. This results in overlapping time slices.

One FFT is taken 256 samples later than the other

The windowing is achieved by multiplying the signal by a triangular waveform (stored in the buffer~ object) which recurs at
the same frequency as the FFT -- once every 512 samples. The window is offset by 1/ 2 cycle (256 samples) for the second
fft~. Notice also that because we will be applying the amplitude envelope twice (once before the fft~ and once again after the
ifft~), we take the square root of the envelope values, so we do not have unwanted amplitude modulation resulting from our
envelopes (we want the overlapping envelopes to crossfade evenly and always add up to 1).

Double-click on the buffer~ object to view its contents. Then close the buffer~ window and double-click on the capture~
object that contains the FFT of the windowed signal. Scroll past the first block or two of numbers until you see the FFT
analysis of the windowed 1000 Hz tone.

As with the unwindowed FFT, the energy is greatest around 1000 Hz, but here the (spurious) energy in all the other
frequency regions is greatly reduced by comparison with the unwindowed version.
Signal processing using the FFT
In this patch we have used the fft~ object to view and analyze a signal, and to demonstrate the effectiveness of windowing
the signal and using overlapping FFTs. However, one could also write a patch that alters the values in the signal coming out
of fft~, then sends the altered analysis to ifft~ for resynthesis. This kind of processing using overlapped, windowed time
slices is known as a Short Term Fourier Transform (STFT), and is the basis for frequency-domain audio processing. We will
be discussing a simpler way to use the STFT in Tutorial 26.

Windowing, in addition to being important for reducing the false frequencies from discontinuities in the input waveform, as
we have already seen, is also important to smooth out any discontinuities which occur in the resynthesized time-domain
waveform coming from the ifft~. This is why we must window the time-domain signal both on input and output. In this
tutorial we would only get such output discontinuities if we modified the signal between the fft~ and ifft~ objects.

Summary
The fast Fourier transform (FFT) is an algorithm for transforming a time-domain digital signal into a frequency-domain
representation of the relative amplitude of different frequency regions in the signal. An FFT is computed using a relatively
small excerpt of a signal, usually a slice of time 512 or 1024 samples long. To analyze a longer signal, one performs multiple
FFTs using consecutive (or overlapping) time slices.

The fft~ object performs an FFT on the signal it receives, and sends out (also in the form of a signal) a frequency-domain
analysis of the received signal. The only object that understands the output of fft~ is ifft~ which performs an inverse FFT to
synthesize a time-domain signal based on the frequency-domain information. One could alter the signal as it goes from fft~
to ifft~, in order to change the spectrum.
The FFT only works perfectly when analyzing exactly one cycle (or exactly an integer number of cycles) of a tone. To reduce
the artifacts produced when this is not the case, one can window the signal being analyzed by applying an amplitude
envelope to taper the ends of each time slice. The amplitude envelope can be applied by multiplying the signal by using a
cycle~ object to read a windowing function from a buffer~ repeatedly at the same rate as the FFT itself (i.e., once per time
slice). To eliminate any artifacts that result from modifying the frequency-domain signal, we must also apply the same
envelope at the output of the ifft~.

See Also
Name Description
buffer~ Store audio samples
capture~ Store a signal to view as text
fft~ Fast Fourier transform
ifft~ Inverse fast Fourier transform
Frequency Domain Signal Processing with pfft~
Tutorial 26: Frequency Domain Signal Processing with pfft~
Open the tutorial.

Working in the Frequency Domain


Most digital signal processing of audio occurs in what is known as the time domain. As the other MSP tutorials show you, many of the
most common processes for manipulating audio consist of varying samples (or groups of samples) in amplitude (ring modulation,
waveshaping, distortion) or time (filters and delays). The Fast Fourier Transform (FFT) allows you to translate audio data from the
time domain into the frequency domain, where you can directly manipulate the spectrum of a sound (the component frequencies of a
slice of audio).

As we have seen in Tutorial 25, the MSP objects fft~ and ifft~ allow you to transform signals into and out of the frequency domain. The
fft~ object takes a a group of samples (commonly called a frame) and transforms them into pairs of real and imaginary numbers which
contain information about the amplitude and phase of as many frequencies as there are samples in the frame. These are usually
referred to as bins or frequency bins. (We will see later that the real and imaginary numbers are not themselves the amplitude and
phase, but that the amplitude and phase can be derived from them.) The ifft~ object performs the inverse operation, taking frames of
frequency-domain samples and converting them back into a time domain audio signal that you can listen to or process further. The
number of samples in the frame is called the FFT size (or sometimes FFT point size). It must be a power of 2 such as 512, 1024 or
2048 (to give a few commonly used values).

One of the shortcomings of the fft~ and ifft~ objects is that they work on successive frames of samples without doing any overlapping
or cross-fading between them. For most practical musical uses of these objects, we usually need to construct such an overlap and
crossfade system around them, as shown at the end of Tutorial 25. There are several reasons for needing to create such a system when
using the Fourier transform to process sound. In FFT analysis there is always a trade-off between frequency resolution and timing
resolution. For example, if your FFT size is 2048 samples long, the FFT analysis gives you 2048 equally-spaced frequency bins from 0
Hz. up to the sampling frequency (only 1024 of these bins are of any use; see Tutorial 25 for details). However, any timing resolution
that occurs within those 2048 samples will be lost in the analysis, since all temporal changes are lumped together in a single FFT
frame. In addition, if you modify the spectral data after the FFT analysis and before the IFFT resynthesis you can no longer guarantee
that the time domain signal output by the IFFT will match up in successive frames. If the output time domain vectors don't fit together
you will get clicks in your output signal. By designing a windowing function in MSP (see below), you can compensate for these artifacts
by having successive frames cross-fade into each other as they overlap. While this will not compensate for the loss of time resolution,
the overlapping of analysis data will help to eliminate the clicks and pops that occurs at the edges of an IFFT frame after resynthesis.
This analysis/resynthesis scheme (using overlapping, windowed slices of time with the FFT and IFFT) is usually referred to as a Short
Term (or Short Time) Fourier Transform (STFT). An STFT can be designed in MSP by creating a patch that uses one or more pairs of
fft~/ifft~ objects with the input signal windowed into and out of the frequency domain. While this approach works fairly well, it is
somewhat cumbersome to program since every operation performed in the frequency domain needs to be duplicated correctly for each
fft~/ifft~ pair. The following subpatch illustrates how one would window incoming FFT data in this manner:

How to properly window audio for use with the fft~ object
In addition to the fact that this approach can often be a challenge to program, there is also the difficulty of generalizing the patch for
multiple combinations of FFT size and overlap. Since the arguments to fft~/ifft~ for FFT frame size and overlap can't be changed,
multiple hand-tweaked versions of each subpatch must be created for different situations. For example, a percussive sound would
necessitate an analysis with at least four overlaps, while a reasonably static, harmonically rich sound would call for a very large FFT
size.

Technical detail: Time vs. Frequency Resolution

The FFT size we use provides us with a tradeoff; because the Fourier transform mathematically converts a small slice of time into
a frozen snapshot representing its spectrum, you might first think that it would be beneficial to use small FFT sizes in order to
avoid grouping temporal changes together in one analysis spectrum. While this is true, an FFT size with a smaller number of
points also means that our spectrum will have a smaller number of frequency bins, which means that the frequency resolution will
be lower. Smaller FFT sizes result in better temporal resolution, but at the cost of lower frequency resolution when the sound is
modified in the frequency domain and resynthesized. Conversely, larger FFT sizes give us finer frequency detail, but tend to
smear temporal changes in the sound. In practice, we therefore need to choose an appropriate FFT size based on the kind of
sound we want to process.

An Introduction to the pfft~ Object


The pfft~ object addresses many of the shortcomings of the old fft~ and ifft~ objects, allowing you to create and load special spectral
subpatches that manipulate frequency-domain signal data independently of windowing, overlap and FFT size. A single sub-patch can
therefore be suitable for multiple applications. Furthermore, the pfft~ object manages the overlapping of FFT frames, handles the
windowing functions for you, and eliminates the redundant mirrored data in the spectrum, making it both more convenient to use and
more efficient than the traditional fft~ and ifft~ objects.

The pfft~ object takes as its argument the name of a specially designed subpatch containing the fftin~ and fftout~ objects (which will
be discussed below), a number for the FFT size in samples, and a number for the overlap factor (these must both be integers which are
a power of 2):

A simple use of pfft~.

The pfft~ subpatch fftbasic~ referenced above might look something like this:

The fftbasic~ subpatch used in the previous example


The fftbasic~ subpatch shown above takes a signal input, performs an FFT on that signal with a Hanning window (see below), and
performs an IFFT on the FFT'd signal, also with a Hanning window. The pfft~ object communicates with its sub-patch using special
objects for inlets and outlets. The fftin~ object receives a time-domain signal from its parent patch and transforms it via an FFT into
the frequency domain. This time-domain signal has already been converted, by the pfft~ object, into a sequence of frames which
overlap in time, and the signal that fftin~ outputs into the spectral subpatch represents the spectrum of each of these incoming frames.

Technical detail: By default, the signal vector size inside the spectral subpatch is equal to half the FFT size specified as an
argument to the pfft~. Here's the reason why: for efficiency's sake, fftin~ and fftout~ perform what is known as a real FFT,
which is faster than the traditional complex FFT used by fft~ and ifft~. This is possible because the time-domain signals we
transform have no imaginary part (or at least they have an imaginary part which is equal to zero). A real FFT is a clever
mathematical trick which re-arranges the real-only time-domain input to the FFT as real and imaginary parts of a complex FFT
that is half the size of our real FFT. The result of this FFT is then re-arranged into a complex spectrum representing half (from
0Hz to half the sampling rate) of our original real-only signal. The smaller FFT size means it is more efficient for our computer's
processor, and, because a complex FFT produces a mirrored spectrum of which only half is really useful to us, the real FFT
contains all the data we need to define and subsequently manipulate the signal's spectrum. (Nonetheless, we can, if we choose, set
an optional argument to the pfft~ object to tell it to perform a complex FFT resulting in a full-spectrum from 0Hz to the
sampling rate. In this case the signal vector size of the spectral subpatch is the same as the FFT size. This is computationally more
expensive, not only because of the larger FFT, but because the spectral subpatch will have to process twice the number of samples
for the same amount of data.)

The fftout~ object does the reverse, accepting frequency domain signals, converting them back into a time domain signal, and passing
it via an outlet to the parent patch. Both objects take a numbered argument (to specify the inlet or outlet number), and a symbol
specifying the window function to use. The available window functions are Hanning (the default if none is specified), Hamming,
Blackman, Triangle, and Square. In addition, the symbol can be the name of a buffer~ object which holds a custom windowing
function. Different window functions have different bandwidths and stopband depths for each channel (or bin, as it is sometimes
called) of the FFT. A good reference on FFT analysis will help you select a window based on the sound you are trying to analyze and
what you want to do with it. We recommend The Computer Music Tutorial by Curtis Roads or Computer Music by Charles Dodge and
Thomas Jerse. Generally, for musical purposes the default Hanning window works best, as it provides a clean envelope with no
amplitude modulation artifacts on output.

For testing and debugging purposes, there is also a handy nofft argument to fftin~ and fftout~ which allows the overlapping time-
domain frames to and from the pfft~ to be passed directly to and from the subpatch without applying a window function nor
performing a Fourier transform. In this case (because the signal vector size of the spectral subpatch is half the FFT size), the time-
domain signal is split between the real and imaginary outlets of the fftin~ and fftout~ objects, which may be rather inconvenient when
using an overlap of 4 or more. Although the nofft option can be used to send signal data from the parent patch into the spectral
subpatch and may be useful for debugging subpatches, it is not recommended for most practical uses of pfft~.
A more complicated pfft~ subpatch might look something like this:

A simple type of spectral convolution


This subpatch takes two signal inputs (which would appear as inlets in the parent pfft~ object), converts them into the frequency
domain, multiplies the real signals with one another and multiplies the imaginary signals with one another and outputs the result to an
fftout~ object that converts the frequency domain data into a time domain signal. Multiplication in the frequency domain is called
convolution, and is the basic signal processing procedure used in cross synthesis (morphing one sound into another). The result of this
algorithm is that frequencies from the two analyses which have larger amplitude values will reinforce one another, whereas frequency
with weaker amplitude values in one analysis will diminish or cancel the value from the other, whether strong or weak. Frequency
content that the two incoming signals share will be retained while frequency content that exists in one signal and not the other will be
attenuated or eliminated. This example is not a true convolution, however, as the multiplication of complex numbers (see below) is
not as straightforward as the multiplication performed in this example. We'll learn a couple ways of making a correct convolution
patch later in this tutorial.

You have probably already noticed that there are always two signals to connect when connecting fftin~ and fftout~, as well as when
processing the spectra in-between them. This is because the FFT algorithm produces complex numbers numbers that contain a real
and an imaginary part. The real part is sent out the leftmost outlet of fftin~, and the imaginary part is sent out its second outlet. The
two inlets of fftout~ also correspond to real and imaginary, respectively. The easiest way to understand complex numbers is to think of
them as representing a point on a 2-dimensional plane, where the real part represents the X-axis (horizontal distance from zero), and
the imaginary part represents the Y-axis (vertical distance from zero). We'll learn more about what we can do with the real and
imaginary parts of the complex numbers later on in this tutorial.

The Third Outlet


The fftin~ object has a third outlet that puts out a stream of samples corresponding to the current frequency bin index whose data is
being sent out the first two outlets (this is analogous to the third outlet of the fft~ and ifft~ objects discussed in Tutorial 25). For
fftin~, this outlet outputs a number from 0 to half the FFT size minus 1. You can convert these values into frequency values
(representing the center frequency of each bin) by multiplying the signal (called the sync signal) by the base frequency, or
fundamental, of the FFT. The fundamental of the FFT is the lowest frequency that the FFT can analyze, and is inversely proportional to
the size of the FFT (i.e. larger FFT sizes yield lower base frequencies). The exact fundamental of the FFT can be obtained by dividing
the FFT frame size into the sampling rate. The fftinfo~ object, when placed into a pfft~ subpatch, will give you the FFT frame size, the
FFT half-frame size (i.e. the number of bins actually used inside the pfft~ subpatch), and the FFT hop size (the number of samples of
overlap between the windowed frames). You can use this in conjunction with the dspstate~ object or the adstatus object with the sr
(sampling rate) argument to obtain the base frequency of the FFT:

Finding the center frequency of the current analysis bin.

Note that in the above example the number~ object is used for the purposes of demonstration only in this tutorial. When DSP is
turned on, the number displayed in the signal number box will not appear to change because the signal number box by default displays
the first sample in the signal vector, which in this case will always be 0. To see the center frequency values, you will need to use the
capture~ object or record this signal into a buffer~.

Once you know the frequency of the bins being streamed out of fftin~, you can perform operations on the FFT data based on
frequency. For example:

A simple spectral crossover.

The above pfft~ subpatch, called xover~, takes an input signal and sends the analysis data to one of two fftout~ objects based on a
crossover frequency. The crossover frequency is sent to the pfft~ subpatch by using the in object, which passes max messages through
from the parent patch via the pfft~ object's right inlet. The center frequency of the current bin determined by the sync outlet in
conjunction with fftinfo~ and dspstate~ as we mentioned above is compared with the crossover frequency.
The result of this comparison flips a gate that sends the FFT data to one of the two fftout~ objects: the part of the spectrum that is
lower in pitch than the crossover frequency is sent out the left outlet of the pfft~ and the part that is higher than the crossover
frequency is sent out the right. Here is how this subpatcher might be used with pfft~ in a patch

One way of using the xover~ subpatch

Note that we can send integers, floats, and any other Max message to and from a subpatch loaded by pfft~ by using the in and out
objects. (See Tutorial 21, Using the poly~ and out~ currently do not function inside a pfft~.)

Working with Amplitude and Phase


As we have already learned, the first two outlets of fftin~ put out a stream of real and imaginary numbers for the bin response for each
sample of the FFT analysis (similarly, fftout~ expects these numbers). These are not the amplitude and phase of each bin, but should
be thought of instead as pairs of Cartesian coordinates, where x is the real part and y is the imaginary, representing points on a 2-
dimensional plane.

The amplitude and phase of each frequency bin are the polar coordinates of these points, where the distance from the origin is the bin
amplitude and the angle around the origin is the bin phase:
Unit-circle diagram showing the relationship of FFT real and imaginary values to amplitude and phase

You can easily convert between real/imaginary pairs and amplitude/phase pairs using the objects cartopol~ and poltocar~:

Cartesian to polar conversion

Technical detail: The amplitude values output by the left outlet of cartopol~ naturally depend on the amplitude of the signal
you send to the pfft~ object. Nonetheless, the maximum amplitude value for a constant signal of 1.0 will be equal to the sum of
the amplitude values of the windowing function used. For a Hanning window this is equal to half the FFT size, and for a square
window this is equal to the FFT size. For an oscillation, such as a sine wave, with a maximum amplitude of 1.0 the maximum
values obtained from the FFT are one quarter of the window size. FFT bins at the extreme low and high ends of the spectrum may
have slightly smaller maximum values, and a DC offset in the sound may slightly increase the maximum amplitude values of the
FFT analysis. Nonetheless, here is a list of multipliers for various window shapes to find the maximum possible amplitude value
of a full-volume sine wave:

Hanning: FFTsize * 0.25


Hamming: FFTsize * 0.27174
Blackman: FFTsize * 0.21
Triangle: FFTsize * 0.2495
Square: FFTsize * 0.5

So, for example, when using a 512-point FFT with the default Haning window, a full-volume sine wave at half the nyquist
frequency will have a value of 128 in the 128th frequency bin (512 * 0.25). The same scenario using a Blackman window will
provide us with a value of 107.52 in the 128th frequency bin (512 * 0.21). Even though these are the theoretical maximum values
with a single sine wave as input, real-world audio signals will generally have significantly lower values, as the energy in complex
waveforms is spread over many frequencies.

The phase values output by the right outlet of cartopol~ will always be between - and .

You can use this information to create signal processing routines based on amplitude/phase data. A spectral noise gate would look
something like this:
A spectral noise gate

By comparing the amplitude output of cartopol~ with the threshold signal sent into inlet 2 of the pfft~, each bin is either passed or
zeroed by the *~ objects. This way only frequency bins that exceed a certain amplitude are retained in the resynthesis (For information
on amplitude values inside a spectral subpatch, see the Technical note above.).

Convolution and Cross Sythesis


Convolution and cross-synthesis effects commonly use amplitude and phase data for their processing. One of the most basic cross-
synthesis effects we could make would use the amplitude spectrum of one sound with the phase spectrum of another. Since the phase
spectrum is related to information about the sound's frequency content, this kind of cross synthesis can give us the harmonic content
of one sound being played by the spectral envelope of another sound. Naturally, the success of this type of effect depends heavily on
the choice of the two sounds used.

Here is an example of a spectral subpatch which makes use of cartopol~ and poltocar~ to perform this type of cross-synthesis:

Simple cross-synthesis
The following subpatch example shows two ways of convolving the amplitude of one input with the amplitude of another:
Amplitude-only convolution
You can readily see on the left-hand side of this subpatch that the amplitude values of the input signals are multiplied together. This
reinforces amplitudes which are prominent in both sounds while attenuating those which are not. The phase response of the first signal
is unaffected by complex*real multiplication; the phase response of the second signal input is ignored. You will also notice that the
right-hand side of the subpatch is mathematically equivalent to the left, even though it uses only one cartopol~ object.
Toward the beginning of this tutorial, we saw an example of the multiplication of two real/imaginary signals to perform a convolution.
That example was kept simple for the purposes of explanation but was, in fact, incorrect. If you wondered what a correct
multiplication of two complex numbers would entail, here is one way to do it:

The correct method for doing complex convolution

Here's a second and somewhat more clever approach to the same goal:

A correct and clever way of doing complex convolution

Time Stretching
Subpatchers created for use with pfft~ can use the full range of MSP objects, including objects that access data stored in a buffer~
object. (Although some objects which were designed to deal with timing issues may not always behave as initially expected when used
inside a pfft~.)

The following example records spectral analysis data into two channels of a stereo buffer~ and then allows you to resynthesize the
recording at a different speed without changing its original pitch. This is known as time-stretching (or time compression when the
sound is speeded up), and has been one of the important uses of the STFT since the 1970s.

Recording and playback in a pfft~ subpatch

The example subpatcher records spectral data into a buffer~ on the left, and reads data from that buffer~ on the right. In the
recording portion of the subpatch you will notice that we don't just record the amplitude and phase as output from cartopol~, but
instead use the framedelta~ object to compute the phase difference (sometimes referred to as the phase deviation, or phase
derivative). The phase difference is quite simply the difference in phase between equivalent bin locations in successive FFT frames. The
output of framedelta~ is then fed into a phasewrap~ object to ensure that the data is properly constrained between - and .
Messages can be sent to the record~ object from the parent patch via the send object in order to start and stop recording and turn on
looping.

In the playback part of the subpatch we use a non-signal inlet to specify the frame number for the resynthesis. This number is
multiplied by the spectral frame size and added to the output of a count~ object which counts from 0 to the spectral frame size minus 1
in order to be able to recall each frequency bin in the given frame successively using index~ to read both channels of our buffer~. (We
could also have used the sync outlet of the fftin~ object in place of count~, but are using the current method for the sake of visually
separating the recording and playback parts of our subpatch, as well as to give an example of how to make use of count~ in the context
of a spectral subpatch.) You'll notice that we reconstruct the phase using the frameaccum~ object, which accumulates a running
phase value by performing the inverse of framedelta~. We need to do this because we might not be reading the analysis frames
successively at the original rate in which they were recorded. The signals are then converted back into real and imaginary values for
fftout~ by the poltocar~ object.
This is a simple example of what is known as a phase vocoder. Phase vocoders allow you to time-stretch and compress signals
independently of their pitch by manipulating FFT data rather than time-domain segments. If you think of each frame of an FFT
analysis as a single frame in a film, you can easily see how moving through the individual frames at different rates can change the
apparent speed at which things happen. This is more or less what a phase vocoder does.

Note that because pfft~ does window overlapping, the amount of data that can be stored in the buffer~ is dependent on the settings of
the pfft~ object. This can make setting the buffer size correctly a rather tricky matter, especially since the spectral frame size (i.e. the
signal vector size) inside a pfft~ is half the FFT size indicated as its second argument, and because the spectral subpatch is processing
samples at a different rate to its parent patch! If we create a stereo buffer~ with 1000 milliseconds of sample memory, we will have
44100 samples available for our analysis data. If our FFT size is 1024 then each spectral frame will take up 512 samples of our buffer's
memory, which amounts to 86 frames of analysis data(44100 / 512 = 86.13). Those 86 frames do not represent one second of sound,
however! If we are using 4-times overlap, we are processing one spectral frame every 256 samples, so 86 frames means roughly 22050
samples, or a half second's worth of time with respect to the parent patch. As you can see this all can get rather complicated...

Let's take a look at the parent patch for the above phase vocoder subpatch (called mypvoc~):
Wrapper for mypvoc

Notice that we're using a phasor~ object with a snapshot~ object in order to generate a ramp specifying the read location inside our
subpatch. We could also use a line object, or even a slider, if we wanted to scrub our analysis frames by hand. Our main patch allows
us to change the playback rate for a loop of our analysis data. We can also specify the loop size and an offset into our collection of
analysis frames in order to loop a given section of analysis data at a given playback rate. You'll notice that changing the playback rate
does not affect the pitch of the sound, only the speed. You may also notice that at very slow playback rates, certain parts of your sound
(usually note attacks, consonants in speech or other percussive sounds) become rather smeared and gain an artificial sound quality.

Summary
Using pfft~ to perform spectral-domain signal processing is generally easier and visually clearer than using the traditional fft~ and
ifft~ objects, and lets you design patches that can be used at varying FFT sizes and overlaps. There are myriad applications of pfft~ for
musical signal processing, including filtering, cross synthesis and time stretching.

See Also
Name Description
adstatus Report and control audio driver settings
cartopol~ Signal Cartesian to Polar coordinate conversion
dspstate~ Report current DSP settings
fftin~ Input for a patcher loaded by pfft~
fftout~ Output for a patcher loaded by pfft~
framedelta~ Compute phase deviation between successive FFT frames
pfft~ Spectral processing manager for patchers
phasewrap~ Wrap a signal between and -
poltocar~ Signal Polar to Cartesian coordinate conversion
Delay Lines
Tutorial 27: Delay Lines
Open the tutorial.

Effects achieved with delayed signals


One of the most basic yet versatile techniques of audio processing is to delay a signal and mix the delayed version with the
original signal. The delay time can range from a few milliseconds to several seconds, limited only by the amount of RAM you
have available to store the delayed signal.

When the delay time is just a few milliseconds, the original and delayed signals interfere and create a subtle filtering effect
but not a discrete echo. When the delay time is about 100 ms we hear a slapback echo effect in which the delayed copy
follows closely behind the original. With longer delay times, we hear the two signals as discrete events, as if the delayed
version were reflecting off a distant mountain.

This tutorial patch delays each channel of a stereo signal independently, and allows you to adjust the delay times and the
balance between direct signal and delayed signal.

Creating a delay line: tapin~ and tapout~


The MSP object tapin~ is a buffer that is continuously updated so that it always stores the most recently received signal. The
amount of signal it stores is determined by a typed-in argument. For example, a tapin~ object with a typed-in argument of
1000 stores the most recent one second of signal received in its inlet.

A 1-second delay buffer tapped 500 and 1000 ms in the past

The only object to which the outlet of tapin~ should be connected is a tapout~ object. This connection links the tapout~
object to the buffer stored by tapin~. The tapout~ object taps into the delayed signal at certain points in the past. In the
above example, tapout~ gets the signal from tapin~ that occurred 500 ms ago and sends it out the left outlet; it also gets the
signal delayed by 1000 ms and sends that out its right outlet. It should be obvious that tapout~ can't get signal delayed
beyond the length of time stored in tapin~.

A patch for mixing original and delayed signals


The tutorial patch sends the sound coming into the computer to two places: directly to the output of the computer and to a
tapin~-tapout~ delay pair. You can control how much signal you hear from each place for each of the stereo channels,
mixing original and delayed signal in whatever proportion you want.

Turn audio on and send some sound in the input jacks of your computer. Set the number box marked Output Level to a
comfortable listening level. Set the Left Delay Time number box to 500 and the Right Delay Time to 1000.
At this point you don't hear any delayed signal because the Direct Level for each channel is set at 1 and the Delay Level for
each channel is set at 0. The signal is being delayed, but you simply don't hear it because its amplitude is scaled to 0.
Direct signal is on full; delayed signal is turned down to 0

The slider in the left part of the Patcher window serves as a balance fader between a Dry (all direct) output signal and a
Wet (fully processed) output signal.

Drag the slider to the halfway point so that both the direct and delayed signal amplitudes are at 0.5. You hear the original
signal in both channels, mixed with a half-second delay in the left channel and a one-second delay in the right channel.

Equal balance between direct signal and delayed signal

You can try a variety of different delay time combinations and wet-dry levels. Try very short delay times for subtle comb
filtering effects. Try creating rhythms with the two delay times (with, for example, delay times of 375 and 500 ms).

Changing the parameters while the sound is playing can result in clicks in the sound because this patch does not protect
against discontinuities. You could create a version of this patch that avoids this problem by interpolating between parameter
values with line~ or number~ objects.
In future tutorial chapters, you will see how to create delay feedback, how to use continuously variable delay times for
flanging and pitch effects, and other ways of altering sound using delays, filters, and other processing techniques.

Summary
The tapin~ object is a continuously updated buffer which always stores the most recently received signal. Any connected
tapout~ object can use the signal stored in tapin~, and access the signal from any time in the past (up to the limits of the
tapin~ object's storage). A signal delayed with tapin~ and tapout~ can be mixed with the undelayed signal to create discrete
echoes, early reflections, or comb filtering effects.

See Also
Name Description
tapin~ Input to a delay line
tapout~ Output from a delay line
Delay Lines with Feedback
Tutorial 28: Delay Lines with Feedback
Open the tutorial.

Delay emulates reflection


You can delay a signal for a specific amount of time using the tapin~ and tapout~ objects. The tapin~ object is a continually
updated buffer that stores the most recent signal it has received, and tapout~ accesses that buffer at one or more specific
points in the past.

Delaying a signal with tapin~ and tapout~

Combining a sound with a delayed version of itself is a simple way of emulating a sound wave reflecting off of a wall before
reaching our ears; we hear the direct sound followed closely by the reflected sound. In the real world some of the sound
energy is actually absorbed by the reflecting wall, and we can emulate that fact by reducing the amplitude of the delayed
sound, as shown in the following example.

Scaling the amplitude of a delayed signal, to emulate absorption

Technical detail: Different materials absorb sound to varying degrees, and most materials absorb sound in a way
that is frequency-dependent. In general, high frequencies get absorbed more than low frequencies. That fact is being
ignored here.

Delaying the delayed signal


Also, in the real world there's usually more than one surface that reflects sound. In a room, for example, sound reflects off of
the walls, ceiling, floor, and objects in the room in myriad ways, and the reflections are in turn reflected off of other surfaces.
One simple way to model this reflection of reflections is to feed the delayed signal back into the delay line (after first
absorbing some of it).
Delay with feedback

A single feedback delay line like the one above is too simplistic to sound much like any real world acoustical situation, but it
can generate a number of interesting effects. Stereo delay with feedback is implemented in the example patch for this
tutorial. Each channel of audio input is delayed, scaled, and fed back into the delay line.

Stereo delay with individual delay times and feedback amounts

Set the number box marked Output Level to 1., and move the slider to its middle position so that the Direct Level and
Delay Level number box objects read 0.5. Turn audio on, and send some sound into the audio input of the computer.
Experiment with different delay times and feedback amounts. For example, you can use the settings shown above to achieve
a blurring effect. Increase the feedback amounts for a greater resonant ringing at the rate of feedback (1000 divided by the
delay time). Increase the delay times to achieve discrete echoes. You can vary the Dry/Wet mix with the slider.
Note that any time you feed audio signal back into a system, you have a potential for overloading the system. That's why it's
important to scale the signal by some factor less than 1.0 (with the *~ objects and the Feedback number box objects)
before feeding it back into the delay line. Otherwise the delayed sound will continue indefinitely and even increase as it is
added to the new incoming audio.

Controlling amplitude: normalize~


Since this patch contains user-variable level settings (notably the feedback levels) and since we don't know what sound will
be coming into the patch, we can't really predict how we will need to scale the final output level. If we had used a *~ object
just before the ezdac~ to scale the output amplitude, we could set the output level, but if we later increase the feedback
levels, the output amplitude could become excessive. The normalize~ object is good for handling such unpredictable
situations.

The normalize~ object allows you to specify a peak (maximum) amplitude that you want sent out its outlet. It looks at the
peak amplitude of its input, and calculates the factor by which it must scale the signal in order to keep the peak amplitude at
the specified maximum. So, with normalize~ the peak amplitude of the output will never exceed the specified maximum.
normalize~ sends out the current input * peak output / peak input

One potential drawback of normalize~ is that a single loud peak in the input signal can cause normalize~ to scale the entire
signal way down, even if the rest of the input signal is very soft. You can give normalize~ a new peak input value to use, by
sending a number or a reset message in the left inlet.

Turn audio off and close the Patcher window before proceeding to the next chapter.

Summary
One way to make multiple delayed versions of a signal is to feed the output of tapout~ back into the input of tapin~, in
addition to sending it to the DAC. Because the fed back delayed signal will be added to the current incoming signal at the
inlet of tapin~, it's a good idea to reduce the output of tapout~ before feeding it back to tapin~.
In a patch involving addition of signals with varying amplitudes, it's often difficult to predict the amplitude of the summed
signal that will go to the DAC. One way to control the amplitude of a signal is with normalize~, which uses the peak
amplitude of an incoming signal to calculate how much it should reduce the amplitude before sending the signal out.

See Also
Name Description
normalize~ Scale on the basis of maximum amplitude
tapin~ Input to a delay line
tapout~ Output from a delay line
Flanging
Tutorial 29: Flanging
Open the tutorial.

Variable delay time


So far, we have been delaying signals for a fixed amount of time using tapin~ and tapout~. You can change the delay time
of any tap in the tapout~ object by sending a new number in the proper inlet; however, this will cause a discontinuity in the
output signal at the instant when then new delay time is received, because tapout~ suddenly begins tapping a new location
in the tapin~ buffer.

Changing the delay time creates a discontinuity in the output signal

On the other hand, it's possible to provide a new delay time to tapout~ using a continuous signal instead of a discrete Max
message. We can use the line~ object to make a continuous transition between two delay times (just as we did to make
continuous changes in amplitude in Tutorial 2).

Providing delay time in the form of a signal

Technical detail: Note that when the delay time is being changed by a continuous signal, tapout~ has to interpolate
between the old delay time and the new delay time for every sample of output. Therefore, a tapout~ object has to do
much more computation whenever a signal is connected to one of its inlets.

While this avoids the click that could be caused by a sudden discontinuity, it does mean that the pitch of the output signal
will change while the delay time is being changed, emulating the Doppler effect

Technical detail: The Doppler effect occurs when a sound source is moving toward or away from the listener. The
moving sound source is, to some extent, outrunning the wavefronts of the sound it is producing. That changes the
frequency at which the listener receives the wavefronts, thus changing the perceived pitch. If the sound source is
moving toward the listener, wavefronts arrive at the listener with a slightly greater frequency than they are actually
being produced by the source. Conversely, if the sound source is moving away from the listener, the wavefronts arrive
at the listener slightly less frequently than they are actually being produced. The classic case of Doppler effect is the
sound of an ambulance siren. As the ambulance passes you, it changes from moving toward you (producing an increase
in received frequency) to moving away from you (producing a decrease in received frequency). You perceive this as a
swift drop in the perceived pitch of the siren.

A delayed signal emulates a reflection of the sound wave. As the delay time decreases, it is as if the (virtual) reflecting
wall were moving toward you. The source of the delayed sound (the reflecting wall) is moving toward you, causing an
increase in the received frequency of the sound. As the delay time increases, the reverse is true; the source of the
delayed sound is effectively moving away from you. That is why, during the time when the delay time is actually
changing, the perceived pitch of the output sound changes.

A delayed signal emulates a reflection of the sound wave. As the delay time decreases, it is as if the (virtual) reflecting wall
were moving toward you. The source of the delayed sound (the reflecting wall) is moving toward you, causing an increase in
the received frequency of the sound. As the delay time increases, the reverse is true; the source of the delayed sound is
effectively moving away from you. That is why, during the time when the delay time is actually changing, the perceived pitch
of the output sound changes.

A pitch shift due to Doppler effect is usually less disruptive than a click that's caused by discontinuity of amplitude. More
importantly, the pitch variance that results from continuously varying the delay time can be used to create some interesting
effects.

Flanging: Modulating the delay time


Since the delay time can be provided by any signal, one possibility is to use a time-varying signal like a low-frequency cosine
wave to modulate the delay time. In the example below, a cycle~ object is used to vary the delay time.

Modulating the delay time with a low-frequency oscillator

The output of cycle~ is multiplied by 0.25 to scale its amplitude. That signal is multiplied by the basic delay time of 100 ms,
to create a signal with an amplitude 25. When that signal is added to the basic delay time, the result is a signal that varies
sinusoidally around the basic delay time of 100, going as low as 75 and as high as 125. This is used to express the delay time
in milliseconds to the tapout~ object.
When a signal with a time-varying delay (especially a very short delay) is added together with the original undelayed signal,
the result is a continually varying comb filter effect known as flanging. Flanging can create both subtle and extreme effects,
depending on the rate and depth of the modulation.

Stereo flange with feedback


This tutorial patch is very similar to that of the preceding chapter. The primary difference here is that the delay times of the
two channels are being modulated by a cosine wave, as was described on the previous page. This patch gives you the
opportunity to try a wide variety of flanging effects, just by modifying the different parameters: the wet/dry mix between
delayed and undelayed signal, the left and right channel delay times, the rate and depth of the delay time modulation, and
the amount of delayed signal that is fed back into the delay line of each channel.

Send some sound into the audio input of the computer, and click on the buttons of the preset object to hear different
effects. Using the example settings as starting points, experiment with different values for the various parameters. Notice
that the modulation depth can also be controlled by the mod wheel of your synth, demonstrating how MIDI can be used for
realtime control of audio processing parameters.

The different examples stored in the preset object are characterized below.
1. Simple thru of the audio input to the audio output. This is just to allow you to test the input and output.

2. The input signal is combined equally with delayed versions of itself, using short (mutually prime) delay times for each
channel. The rate of modulation is set for 0.2 Hz (one sinusoid every 5 seconds), but the depth of modulation is initially 0.
Use the mod wheel of your synth (or drag on the Mod Wheel number box) to introduce some slow flanging.
3. The same as before, but now the modulation rate is 6 Hz. The modulation depth is set very low for a subtle vibrato effect,
but you can increase it to obtain a decidedly un-subtle wide vibrato.
4. A faster vibrato, with greater depth, and with the delayed signal fed back into the delay line, creates a complex warbling
flange effect.

5. The right channel is delayed a short time for a flange effect and the left channel is delayed a longer time for an echo
effect. Both delay times change sinusoidally over a two second period, and each delayed signal is fed back into its own delay
line (causing a ringing resonance in the right channel and repeated echoes in the left channel).

6. Both delay times are set long with considerable feedback to create repeated echoes. The rate (and pitch) of the echoes is
changed up and down by a very slow modulating frequency -- one cycle every 10 seconds.

7. A similar effect, but modulated sinusoidally every 2 seconds.

8. Similar to example 5, but with flanging occurring at an audio rate of 55 Hz, and no original sound in the mix. The source
sound is completely distorted, but the modulation rate gives the distortion its fundamental frequency.

Summary
You can provide a continuously varying delay time to tapout~ by sending a signal in its inlet. As the delay time varies, the
pitch of the delayed sound shifts oppositely. You can use a repeating low frequency wave to modulate the delay time,
achieving either subtle or extreme pitch-variation effects. When a sound with a varying delay time is mixed with the original
undelayed sound, the result is a variable comb filtering effect known as flanging. The depth (strength) of the flanging effect
depends primarily on the amplitude of the signal that is modulating the delay time.

See Also
Name Description
noise~ Generate white noise
rand~ Band-limited random signal
tapin~ Input to a delay line
tapout~ Output from a delay line
Chorus
Tutorial 30: Chorus
Open the tutorial.

The chorus effect


Why does a chorus of singers sound different from a single singer? No matter how well trained a group of singers may be,
they don't sing identically. They're not all singing precisely the same pitch in impeccable unison, so the random,
unpredictable phase cancellations that occur as a result of these slight pitch differences are thought to be the source of the
chorus effect.

We've already seen in the preceding chapter how slight pitch shifts can be introduced by varying the delay time of a signal.
When we mix this signal with its original undelayed version, we create interference between the two signals, resulting in a
constantly varying filtering effect known as flanging. A less predictable effect called chorusing can be achieved by
substituting a random fluctuation of the delay time in place of the sinusoidal fluctuation we used for flanging.

Low-frequency noise: rand~


The noise~ object (introduced in Tutorial 3) produces a signal in which every sample has a randomly chosen value between -
1 and 1; the result is white noise, with roughly equal energy at every frequency. This white noise is not an appropriate signal
to use for modulating the delay time, though, because it would randomly change the delay time so fast (every sample, in fact)
that it would just sound like added noise. What we really want is a modulating signal that changes more gradually, but still
unpredictably.

The rand~ object chooses random numbers between -1 and 1, but does so less frequently than every sample. You can specify
the frequency at which it chooses a new random value. In between those randomly chosen samples, rand~ interpolates
linearly from one value to the next to produce an unpredictable but more contiguous signal.

Random values chosen every sample Choosing values less frequently

The output of rand~ is therefore still noise, but its spectral energy is concentrated most strongly in the frequency region
below the frequency at which it chooses its random numbers. This low-frequency noise is a suitable signal to use to
modulate the delay time for a chorusing effect.

Unpredictable variations using rand~

The tutorial patch for this chapter is substantially similar to the flanging patch in the previous chapter. The main difference
between the two signal networks is that the cycle~ object for flanging has been replaced by a rand~ object for chorusing. The
scope~ object in this patch is just for visualizing the modulating effect of the rand~ object.
Multiple delays for improved chorus effect
We can improve this chorus effect by increasing the number of slightly different signals we combine. One way to do this as
we have done in this patch is to feed the randomly delayed signal back into the delay line, where it's combined with new
incoming signal. The output of tapout~ will thus be a combination of the new variably delayed (and variably pitch shifted)
signal and the previously (but differently) delayed/shifted signal.

Increasing the number of voices using feedback to the delay line

The balance between these signals is determined by the settings for LFeedback and RFeedback, and the combination of
these signals and the undelayed signal is balanced by the DryWetMix value. To obtain the fullest choir with this patch, we
chose delay times (17 ms and 23 ms) and a modulation rate (8 Hz, a period of 125 ms) that are all mutually prime numbers,
so that they are never in sync with each other.

Technical detail: One can obtain an even richer chorus effect by increasing the number of different delay taps in
tapout~, and applying a different random modulation to each delay time.

Click on the toggle to turn audio on. Send some sound into the audio input of the computer to hear the chorusing effect.
Experiment by changing the values for the different parameters. For a radically different effect, try some extreme values
(longer delay times, more feedback, much greater chorus depth, very slow and very fast modulation rates, etc.).

Summary
The chorus effect is achieved by combining multiple copies of a sound -- each one delayed and pitch shifted slightly
differently -- with the original undelayed sound. This can be done by continual slight random modulation of the delay time
of two or more different delay taps. The rand~ object sends out a signal of linear interpolation between random values (in
the range -1 to 1) chosen at a specified rate; this signal is appropriate for the type of modulation required for chorusing.
Feeding the delayed signal back into the delay line increases the complexity and richness of the chorus effect. As with most
processing effects, interesting results can also be obtained by choosing outrageous extreme values for the different
parameters of the signal network.

See Also
Name Description
rand~ Band-limited random signal
tapout~ Output from a delay line
Comb Filter
Tutorial 31: Comb Filter
Comb filter: comb~
The minimum delay time that can be used for feedback into a delay line using tapin~ and tapout~ is determined by the
signal vector size. However, many interesting filtering formulae require feedback using delay times of only a sample or two.
Such filtering processes have to be programmed within a single MSP object.

An example of such an object is comb~, which implements a formula for comb filtering. Generally speaking, an audio filter
is a frequency-dependent amplifier; it boosts the amplitude of some frequency components of a signal while reducing other
frequencies. A comb filter accentuates and attenuates the input signal at regularly spaced frequency intervals -- that is, at
integer multiples of some fundamental frequency.

Technical detail: The fundamental frequency of a comb filter is the inverse of the delay time. For
example, if the delay time is 2 milliseconds (1 / 500 of a second), the accentuation occurs at intervals of 500 Hz
(500, 1000, 1500, etc.), and the attenuation occurs between those frequencies. The extremity of the filtering effect
depends on the factor (between 0 and 1) by which the feedback is scaled. As the scaling factor approaches 1, the
accentuation and attenuation become more extreme. This causes the sonic effect of resonance (a ringing sound) at the
harmonics of the fundamental frequency.

The comb~ object sends out a signal that is a combination of a) the input signal, b) the input signal it received a certain time
ago, and c) the output signal it sent that same amount of time ago (which would have included prior delays). In the inlets of
comb~ we can specify the desired amount of each of these three (a, b, and c), as well as the delay time (we'll call it d).

You can adjust all the parameters of the comb filter

Technical detail: At any given moment in time (we'll call that moment t), comb~ uses the value of the
input signal (x t ), to calculate the output y t in the following manner.

y t = ax t + bx(t-d) + cy (t-d)

The fundamental frequency of the comb filter depends on the delay time, and the intensity of the filtering depends on the
other three parameters. Note that the scaling factor for the feedback (the right inlet) should usually not exceed 1, since that
would cause the output of the filter to increase steadily as a greater and greater signal is fed back.

Trying out the comb filter


The tutorial patch enables you to try out the comb filter by applying it to different sounds. The patch provides you with three
possible sound sources for filtering -- the audio input of your computer, a band-limited pulse wave, or white noise -- and
three filtering options -- unfiltered, comb filter with parameters adjusted manually, or comb filter with parameters
continuously modulated by other signals.
Choose a sound source and route it to the desired filtering using the pop-up menus

Click on the buttons of the preset to try out some different combinations, with example parameter settings. Listen to the
effect of the filter, then experiment by changing parameters yourself. You can use MIDI note messages from your synth to
provide pitch and velocity (frequency and amplitude) information for the pulse wave, and you can use the mod wheel to
change the delay time of the filter.

A comb filter has a characteristic harmonic resonance because of the equally spaced frequencies of its peaks and valleys of
amplification. This trait is particularly effective when the comb is swept up and down in frequency, thus emphasizing
different parts of the source sound. We can cause this frequency sweep simply by varying the delay time.

Band-limited pulse
The effects of a filter are most noticeable when there are many different frequencies in the source sound, which can be
altered by the filter. If we want to apply a comb filter to a pitched sound with a harmonic spectrum, it makes most sense to
use a sound that has many partials such as a sawtooth wave or a square wave.

These mathematically ideal waves may be too perfect for use as computer sound waves

The problem with such mathematically derived waveforms, though, is that they may actually be too rich in high partials.
They may have partials above the Nyquist rate that are sufficiently strong to cause inharmonic aliasing. (This issue is
discussed in more detail in Tutorial 5.)

For this tutorial we're using a waveform called a band-limited pulse. A band-limited pulse has a harmonic spectrum with
equal energy at all harmonics, but has a limited number of harmonics in order to prevent aliasing. The waveform used in this
tutorial patch has ten harmonics of equal energy, so its highest frequency component has ten times the frequency of the
fundamental. That means that we can use it to play fundamental frequencies up to 2,205 Hz if our sampling rate is 44,100
Hz. (Its highest harmonic would have a frequency of 22, 050 Hz, which is equal to the Nyquist rate.) Since the highest key of
a 61-key MIDI keyboard plays a frequency of 2,093 Hz, this waveform will not cause aliasing if we use that as an upper limit.

Playing a band-limited pulse wave with MIDI

Technical detail: In an idealized (optimally narrow) pulse wave, each cycle of the waveform would consist of a single
sample with a value of 1, followed by all samples at 0. This would create a harmonic spectrum with all harmonics at
equal amplitude, continuing upward infinitely. It's possible to make an MSP signal network that calculates -- based on
the fundamental frequency and the sampling rate -- a band-limited pulse signal containing the maximum number of
possible harmonics without foldover. In this case, though, we have chosen just to use a stored waveform containing ten
partials.

Velocity-to-amplitude conversion: gain~


The subpatch pPulse_Wave contains a simple but effective way to play a sound in MSP via MIDI. It uses a poly object to
implement voice stealing, limiting the incoming MIDI notes to one note at a time. (It turns off the previous note by sending
it out with a velocity of 0 before it plays the incoming note.) It then uses mtof to convert the MIDI note number to the
correct frequency value for MSP, and it uses the MSP object gain~ to scale the amplitude of the signal according to the MIDI
velocity.

Converting MIDI pitch and velocity data to frequency and amplitude information for MSP

The gain~ object takes both a signal and a number in its left inlet. The number is used as an amplitude factor by which to
scale the signal before sending it out. One special feature of gain~ (aside from its utility as a user interface object for scaling
a signal) is that it can convert the incoming numbers from a linear progression to a logarithmic or exponential curve. This is
very appropriate in this instance, since we want to convert the linear velocity range (0 to 127) into an exponential amplitude
curve (0 to 1) that corresponds roughly to the way that we hear loudness. Each change of velocity by 10 corresponds to a
change of amplitude by 6 dB. The other useful feature of gain~ is that, rather than changing amplitude abruptly when it
receives a new number in its left inlet, it takes a few milliseconds to progress gradually to the new amplitude factor. The time
it takes to make this progression can be specified by sending a time, in milliseconds, in the right inlet. In this patch, we
simply use the default time of 20 ms.

Choose one of the preset example settings, and choose Pulse Wave from the Sound Source pop-up menu. Play long notes
with the MIDI keyboard. You can also obtain a continuous sound at any amplitude and frequency by sending numbers from
the pitch and velocity number box objects (first velocity, then pitch) into the inlets of the pPulse_Wavesubpatch.

Varying parameters to the filter


As illustrated in this patch, it's usually best to change the parameters of a filter by using a gradually changing signal instead
of making an abrupt change with single number. So parameter changes made to the Adjusted By Hand comb~ object are
sent first to a line~ object for interpolation over a time of 25 ms.
The Modulated comb~ object has its delay time varied at low frequency according to the shape of the band-limited pulse
wave (just because it's a more interesting shape than a simple sinusoid). The modulation could actually be done by a varying
signal of any shape. You can vary the rate of this modulation using the mod wheel of your synth (or just by dragging on the
number box). The gain of the x and y delays (the two rightmost inlets) is modulated by a sine wave ranging between 0.01
and 0.99 (for the feedback gain) and a cosine wave ranging from 0.01 to 0.49 (for the feedforward gain). As the amplitude of
one increases, the other decreases.

Experimenting with different combinations of parameter values may give you ideas for other types of modulation you might
want to design in your own patches.

Summary
The comb~ object allows you to use very short feedback delay times to comb filter a signal. A comb filter creates frequency-
dependent increases and decreases of amplitude in the signal that passes through it, at regularly spaced (i.e., harmonically
related) frequency intervals. The frequency interval is determined by the inverse of the delay time. The comb filter is
particularly effective when the delay time (and thus the frequency interval) changes over time, emphasizing different
frequency regions in the filtered signal.

The user interface object gain~ is useful for scaling the amplitude of a signal according to a specific logarithmic or
exponential curve. Changes in amplitude caused by gain~ take place gradually over a certain time (20 ms by default), so that
there are no unwanted sudden discontinuities in the output signal.

See Also
Name Description
comb~ Apply a comb filter effect
gain~ Exponential scaling volume slider
The dsp Object -- Controlling and Automating MSP
In order to provide low-level control over the MSP environment from within Max, a special object named dsp has been
defined. This object is similar to the object max that can accept messages to change various options in the Max application
environment. Sending a message to the dsp object is done by placing a semicolon in a message box, followed by dsp and
then the message and arguments (if any). An example is shown below.

Turn the audio on or off without a dac~ or adc~ object

You need not connect the message box to anything, although you may want to connect something to the inlet of the message
box to supply a message argument or trigger it from a loadbang object to configure MSP signal processing parameters when
your patcher file is opened.

Here is a list of messages the dsp object understands:

Message Parameters

; dsp start Start Audio

; dsp stop Stop Audio

; dsp set N N = 1, Start Audio;

N = 0, Stop Audio

; dsp status Open Audio Status Window

; dsp open Open Audio Status Window

; dsp sr N N = New Sampling Rate in Hz

; dsp iovs N N = New I/O Vector Size

; dsp sigvs N N = New Signal Vector Size

; dsp debug N N = 1, Internal debugging on;

N = 0, Internal debugging off

; dsp takeover N N = 1, Scheduler in Audio Interrupt On;

N = 0, Scheduler in Audio Interrupt Off

; dsp wclose Close Audio Status window

; dsp inremap X Y Maps physical device input channel Y to logical input X

; dsp outremap X Y Maps logical output X to physical device output channel Y

; dsp setdriver D S If D is a number starting at 0, a new audio driver is chosen based on its index into the currently
generated menu of drivers created by the adstatus driver object.
If D is a symbol, a new driver is selected by name (if D names a valid driver). The second argument S is optional and names
the subdriver. For instance, with ASIO drivers, ASIO is the name of the driver and PCI-324 is an example of a subdriver
name.

; dsp timecode N N = 1 or 0 to start/stop timecode reading by the audio driver (only supported currently by ASIO 2
drivers).

; dsp optimize NN = 1 or 0 to turn Altivec optimization on/off

; dsp cpulimit NSets a utilization limit for the CPU, above this limit, MSP will not process audio vectors until the utilization
comes back down, causing a click. N is a number between 0 and 100. If N is 0 or 100, there is no limit checking.

Certain audio drivers can be controlled with the ; dsp driver message. Refer to the Audio Input and Output section for more
information on drivers that support this capability.
What is Compression?
Introduction: What is Compression?
Dynamic compression is about level control. As an example, imagine recording a trumpet playing with a guitar. If you set the
levels for the trumpet, the guitar will sound very quiet when played alone. If you set the levels for the guitar, the trumpet will
be distorted when it comes in. So you ride gain, watching the trumpet player and turning the knob down when he's about to
play. Compressors try to do this for you, adjusting the gain to keep the signal at a good strong level.

VU and Knob

Any compression device has two parts: a circuit that measures the incoming signal, and a controlled amplifier that adjusts
the gain of the output signal. The level measurement is connected to the gain control of the amplifier. This measurement is
compared to a threshold setting to determine what the device will do. There are several options:
Most compressors used in recording reduce the gain of signals that are above the threshold. A compressor that
completely flattens out all signal above the threshold is called a limiter.
Some compressors increase the gain of signals that are below the threshold, leaving signals above the threshold alone.
Compressors used in radio broadcasting boost soft signals and limit overly strong ones. These devices may be called
comp/limiters or AGCs for automatic gain control.
Multiband compressors combine compression and graphic EQ, treating each frequency band independently. Multiband
limiters are also available.
If the device reduces the gain of signals that measure below the threshold, it is expanding. The most common example
of expansion is the noise gate, which has a very low threshold to shut off grunge in quiet moments.
In communications systems, signals are often compressed before they are sent and expanded upon reception. This helps
reduce noise. The whole process is called companding.
This is all done to lesser or greater degrees based on a control that sets the amount of gain change. Gain change is expressed
as a ratio. If this ratio is 2:1, a compressor would reduce a signal that is 6 dB above the threshold by half, until it is 3 dB
above the threshold. If the ratio is 3:1, a +12 dB signal would be reduced to +4 dB.

The time it takes a compressor to respond to a change in signal level is important. It needs to be at least as long as a cycle of
the lowest frequency coming in, which would be 1/30th of a second for a 30Hz tone. On the other hand, a rim shot is over in
the same amount of time. A compressor fast enough to cover that would just pump up and down on the low tone. To handle
this variety in material, compressors have controls for the speed of response. Usually there are two, attack time and release
time, because musical sounds tend to start quickly and end slowly.

Threshold, ratio, attack time and release time are the vital parameters of a compressor. These determine what is heard and
when. Most compressors have additional controls that set the details of measurement, input and output level, range of gain
change and other options.

The patcher C0. Building a Compressor shows how a compression system is built. The signal coming in is split to a level
measuring circuit and a gain control circuit. The measurement is done using the average~ object in rms mode. This is
converted to dB for the gain calculations, which arent too complicated. In the subpatcher, the difference between the signal
level and threshold is multiplied by a factor derived from the ratio. The result is converted back to absolute level and offset to
create a gain correction value.

Back in the main patcher, a >~ object determines if the correction will be applied. This will switch abruptly from unity to
corrected gain, a technique known as hard knee compression. (Most commercial units ease gently into gain reduction
mode, providing soft knees.) The rampsmooth~ object slows down the gain changes. Note that the attack time of the
compressor is set with a rampdown message. Thats because the gain is reduced when the compressor kicks in.

The final gain is multiplied by the input signal to provide the output.

Decibels measure the ratio between sound levels. Sound levels vary tremendously, from about a watt down to a
picowatt. This is a 1,000,000,000,000:1 ratio. With this wide a range, all you really need to know is the number of
zeros in the ratio. A handy way of taming this number is to use logarithms. The formula for the dB relationship between
two signal amplitudes is:

20 log (A/B)

Usually B is some standard reference. With this formula, the dB value is positive if A is larger than the reference; if A is
smaller, the value is negative. When the signals are the same, you get 0 dB. The reference in digital systems is almost
always the full strength, so most signals are negative dB. In MSP a signal of 1.0. is 0 dB.

Gain is a ratio between the signal coming in and the signal going out. This is usually in dB. If you chuck some common
numbers into the dB formula, you find a doubling of the signal amplitude is a gain of 6 dB, and if it is increased
tenfold, the change in dB is +20. Multiplying an MSP signal by 0.001 produces a reduction of 60 dB.

Decibels are a useful way to measure signals because a change of 6 dB sounds about the same with soft sounds as with
loud ones.

Measuring Signals
The level of a signal is tricky to measure. Since the waveform is a rapidly changing curve, there are various things to measure:

Peak amplitude is the highest sample value seen. (Or lowest- since samples are positive and negative, it's the absolute
value we are interested in.)
Average amplitude is the average of the samples taken over some period of time.
RMS is the root mean square of absolute values of the sample values. That means square each sample, average those,
then take the square root of the average. This math duplicates the action of an analog circuit that measures level.
The type of measurement made will also affect the action of a compression device. Usually limiters respond to peak levels,
and compressors respond to averages.

Intermodulation Distortion
Intermodulation distortion, or IM, occurs when low frequency signals modulate the level of high frequency signals, or vice
versa.

This is a pretty raw sound, as it includes components that are the sum of the two frequencies and the difference between the
two frequencies. IM is quite common in electronic circuits and speakers, but it is usually a fraction of a percent of the
original signal. Anything over 1% IM is noticeable, and 3% is downright annoying.

See Also
Name Description
average~ Multi-mode signal average
rampsmooth~ Smooth an incoming signal
Peak Limiting
Peak Limiting
Open the tutorial.

The patcher C1mPeakLimiting illustrates the use of the omx.peaklim~ object. You can see it in action by applying any
signal with varying levels. Most pop music is heavily compressed, and won't do much here. Try raw drum recordings if you
have any, or classical music or recordings of spoken word

The meters show the level of the input, the action of the amplifier, and the output level. If you increase the input gain, you
will see the level increase to a point, but then the gain slams down so that the output won't be allowed to reach the distortion
point. You can then lower the output gain to get the original signal level with the peaks removed, as shown in the figure
below.

Figure 1. Peak limiting before (top) and after (Input +10 Threshold -1, output 10.)

If you raise the threshold, distortion can occur and will be very audible. If you lower the threshold, the gain indicator will be
mostly in the low position, and the overall effect will be a lot quieter. Raising the output gain will restore the original signal
level, but you will find quiet spots in the input contain things you didn't notice before. The overall impression of loudness
should be much stronger than before. This is heavy limiting.

Figure 2 shows the before and after of heavy limiting on a drum track. You can see how the pop of the drums is stretched
into a nearly continuous sound.

Figure 2. Input + 20, threshold - 12, output 0

The omx.peaklim~ object has two modes that switch response times. Mode 0 is very fast and will suppress the shortest of
transients. However, if the limiting is kicking in and out a lot, you will hear the signal get chopped up. Mode 1 is a bit more
leisurely. This will allow peaks through in percussion tracks, but will sound nicer with vocal or instrumental material. The
change is too subtle to show on the meters, but you should be able to hear it.

Peak limiting is often used as a safety net when recording unpredictable musicians. Many recorders have peak limiting built
in. Heavy limiting gives a very full sound, but the increase in between-the-notes grunge makes the mix muddy. Generally, for
sweetening sounds you will want to use a compressor that has more finesse.
See Also
Name Description
omx.peaklim~ OctiMax Peak Limiter
Basic Compression
Basic Compression
Open the tutorial.

The C2mBasicCompression patcher demonstrates some of the features of the compressor section of the omx.comp~ object,
which produces broadcast type compression and limiting. The signal source for this patch is in the steptone subpatcher. It
generates a simple pattern of tones that gets louder and softer in 6 dB steps. The level of signal is shown in the meter labeled
input. When the compressor is bypassed, this set of tones is heard with no processing. Uncheck the bypass box to hear the
compressor in action.

Threshold
With the opening settings in this patch, the compressor will keep all of the tones pretty much the same level at the output.
Play with the threshold and you will see this level change. The center meter shows the internal action of the compressor.
Gain is reduced as the bar drops.

If you have good speakers, you will notice the step tone generator produces a bit of distortion on the loudest notes. When the
compressor is working, this distortion is heard on those same notes, no matter what the threshold setting. The moral
illustrated here is that compression cannot fix problems that occur upstream in the recording process.

Ratio
If you adjust the ratio down from the extreme setting, you will find the output levels begin to vary when input is below the
threshold. (Parts of the signal above the threshold are still limited.) At a 1:1 ratio the output will follow the input. The most
usable settings are generally 2:1 to 5:1, since this will maintain some shape to the phrase. You will see this when we start
compressing actual signals.

There is a practical limit to how much a signal can be amplified. Below a certain point, all you are doing is bringing up noise.
This limit is adjustable on the omx.comp~, from 36 dB to 0. You'll find the range adjustment in the subpatcher labeled
tweaks, which contains some (but by no means all) of the special parameters of the omx.comp~ object. In hardware these
are usually internal adjustments.

Attack
Set the threshold to -10 and the compression ratio around 20:1. Now listen carefully to the attack portion of the tones.
Compare this with the bypassed tone. It seems that the compressor is somehow accentuating the percussive aspect of the
tone. Now reduce the attack rate a bit (this is the same as increasing attack time). You will hear even more pop in the sound.
In fact, it will distort badly when the attack rate is too slow. Why? At the start of the sound, the compressor is amplifying as
much as it can because there's no signal. When the sound level coming in increases faster than the compressor can respond,
the internal gain will briefly be in the wrong mode, amplifying when it should be reducing. This will exaggerate the
percussion effect. This kind of setting is known in the trade as punching, and is often applied to kick drums to give a strong
sense of beat without overwhelming the band. This effect can be achieved with a bit more subtlety using the delay parameter
as found in the tweaks subpatcher. The delay control delays the signal to the level detector. Naturally, threshold and ratio
strongly affect this effect.

There is another tweak called smoothGain that will also affect this. Gain smoothing applies an envelope to the gain control. If
you set gain smoothing to zero you will immediately hear why: the gain is actually changing in steps which produce a noise
like a zipper. Gain smoothing affects the attack and release rates identically.

Release
The step tone generator will also produce a steady low-pitched drone at -30 dB. If you turn it on while the step tones are
running, you will hear the effect of the release rate Notice that the drone disappears when the step tone is above the
threshold. That's to be expected, since the compressor is turning the entire signal down. In fact, if you watch the gain meter,
you will note it accurately indicates the level of the drone. Listen to how the drone comes in it comes up gradually, as the
compression effect goes away. Now increase the ratio. The drone is louder between notes, and the pumping effect is more
pronounced. Playing with the release time will provide some entertaining effects. At very short releases the drone pumping is
quite noticeable, but if the release is too long, the step tones never get very loud and lose sync with the input. At the longest
settings the drone goes away altogether.

Pumping makes background noise more annoying and can affect the reverberation on a voice or the sustain of a guitar.
When an instrument with bass frequencies is mixed in with a sustaining instrument, the pumping effect is even worse. This
is because a bass signal has to be stronger to 'sound' as loud as a signal in the treble range. As a result, even a reasonably soft
bass sound will affect a piano.. You can hear this effect by setting the swap toggle. This makes the stepped tone low
frequency and the steady tone high frequency.

The omx.comp~ object overcomes this problem by dividing the bass signals off and treating them separately. The message
dualBandEnable 1 as found in the tweaks subpatcher will turn this feature on. When dual band is enabled, bass signals have
a lessened effect on the main band. (The gain indicator splits into two sections to show this.) Note that middle frequency
signals will still control the bass level. Compression is often applied to individual bass tracks to control the resonance of
open strings and add a bit of punch to uprights. If you are doing that, you don't want to be in dual mode

Pumping makes background noise more annoying and can affect the reverberation on a voice or the sustain of a guitar.
When an instrument with bass frequencies is mixed in with a sustaining instrument, the pumping effect is even worse. This
is because a bass signal has to be stronger to 'sound' as loud as a signal in the treble range. As a result, even a reasonably soft
bass sound will affect a piano.. You can hear this effect by setting the swap toggle. This makes the stepped tone low
frequency and the steady tone high frequency.

See Also
Name Description
omx.comp~ OctiMax Compressor
Tweaking Compression
Tweaking Compression
Open the tutorial.

There are more messages used to control the omx.comp~ object than are found on many compressors. Using these
messages gives you unprecedented access to the inner workings of the object and let you adjust the behavior for a wide
variety of sounds. In addition to Threshold, ratio, Attack, and Release, the following messages are available: (Try them out in
patcher C3mTweakingCompression.)
channelCoupling: Stereo signals naturally have different levels on each side. If one channel triggers compression but
the other does not, the relative levels of the channels will be changed. This will result in a movement of the sound
image. Therefore equal compression is applied to both channels even if only one needs it. Normally, the amount of
compression is determined by the stronger channel at any moment. If channelCoupling is set to 1, compression will
follow the left channel. On 2 the right channel determines the action.
SmoothGain: Since the level detector works in discrete steps, applying the level measurement directly to the gain
control would result in stepped action or zipper noise. To prevent this, an envelope (similar to line~) is applied to the
control signal. SmoothGain controls the time of this envelope.
Delay: This message delays the application of the measurement to the amplifier control. This will allow fast peaks
through for an extra punchy sound. Combined with a fast attack time, this will produce strong but very short drum
kicks, perfect for hip hop.
Sidechain: A Sidechain filter applies the inverse vocal EQ described in tutorial 4 to the measurement circuit. This will
reduce the effect of vocals on the output level, useful if you are compressing a full mix. It will keep the voice from
pushing down sustaining parts such as organ.
NoiseGate: Noise gating is almost always necessary when you compress audio from the real world. For instance, if you
are recording a guitar amp, the compressor will emphasize the amp hum between notes. To help prevent this, the
omx.comp~ has a built-in noise gate. When enabled, this applies downward expansion to any signal below the
ngThreshold. There are no attack and release controls because gating is normally applied to very quiet signals.
Release: The three messages gatingLevel, freezeLevel, and progressiveRelease make automatic adjustments to the
release timer based on the input signal. Signals below the freeze level will not trigger any amplification. Signals above
this but below gating level will have a slow release. Progressive release speeds up the release time on stronger inputs.
This means that softer signals (where the ear is less sensitive to dynamic change) will not be as compressed as loud
ones.
LimEnabled: This message puts an absolute limit on the strength of the output signal. This prevents a signal overload
when the controls are set for punching.

Parameter Messages
The OMX objects send messages from the third outlet when parameters are changed. These are in parameter lists, which
contain 7 fields:

1. Scope 0 = global, 1 = presetable, 2 = end of list.

2. Name of parameter.

3. Current value.

4. Maximum value.

5. Minimum value

6. Display value.

7. Units this is arbitrary for most items.

The parameter values are arbitrarily scaled, most from 0 to 100. Some of these can be converted to familiar units. Any dB
parameter can be converted by looking at the value shown when set at 0 thats the minimum value (100 corresponds to 0
dB). Divide 100 by this value to get the scaling factor. Then to set a value, add the absolute of the minimum and multiply by
the absolute of the scaling factor, like this:
To convert agcThreshold (range from 36 to 0) use an expr object with the following arguments: (36 + $i1) * 2.77.
To convert ngThreshold (range from 90 to 0) use an expr object with the following arguments: (90 + $i1) * 1.11. Its
probably easier to capture the numbers coming out in the parameter messages and display those.
Ratio uses exponential values. To convert the numbers given to ratio use an expr object with the following arguments:
ln($f1) / ln (1.04).

Presets
With so many parameters, some method for recalling combinations of settings is essential. The compressors have a few
presets built in (selectable using the ChoosePreset message), but the ultimate solution will be to save the entire setup in a
coll or pattr object. The SaveSettings message will give you a dump of all of the parameters.

Metering
The right outlet provides gain metering if enabled with the meters message. The outputs are a list ready to be connected to a
multislider object. The list for the omx.comp~ shows left and right values for AGC gain, noise gate and limiter. The
meterRate message determines how often these are sent. Alternately, you can get the values using the meterData message.
The meters for the 4-band and 5- band compressors are quite elaborate.

See Also
Name Description
omx.comp~ OctiMax Compressor
Compression on Real Instruments
Compression on Real Instruments
Open the Building A Compressor example.

Compressors can be used on any recording where there is a need for them. In the recording industry compression is
routinely used on vocals, drums and bass. To try these out, you can open and use the the C0mBuildingCompressor tutorial
patch again, get some raw materials and create your own compressor patch with an omx.comp~ object, or use your favorite
VST plug-in compressor

Vocals
Using compression on vocal tracks can help make the lyrics more understandable. Singers will typically shape a phrase
something like this:

This might sound lovely taken by itself, but when mixed with a typical band or piano accompaniment the weaker syllables
oh and where will be masked out. Either that or you will get a Bing Crosby mix where the band sounds like it is in the
next room. If you ask the singer to even the phrase out, they will be so uptight that there will be no expression at all. You can
help these folks out with a bit of subtle processing.

The first processing you can apply is equalization. If the tracks are equalized properly, they can be made clear with minimal
compression. Vocal equalization is a mild boost (3 dB or so) somewhere between 2 and 4 kHz. You tune it to the specific
voice and what you are listening for is clear vowels. You then put the inverse equalization (a 3 dB cut at the same frequency)
on all other tracks that might interfere (such as guitars), making a window in the spectrum for the voice to come through.
With only a 3 dB change, you haven't made an obvious difference in the voice or any single instrument. Many microphones
already have this sort of EQ boost built in, but you still need to cut the other tracks. (In fact, if they were recorded with the
same microphones, youll need to cut them even more.)

The next thing to do is to add some compression. What you want to do is maintain as much of the singer's inflection as you
can, while bringing out every syllableor nearly every syllable. Play the track in bypass mode first and watch the meters.
Make a note of the range covered and particularly the reading of the loudest spots. Set the threshold a bit below the loudest
mark so the compressor is not working very hard. It will recover fastest and distort the least if it never gets into extreme
change. (Remember, the omx.comp~ object is a limiting compressor. Set the threshold at 0 and boost the input until the
high point is just below this.)

Start with gentle (2:1) ratio and fast attack and release. Increase the ratio until the meters show the phrases have flattened
out enough, generally within 12 to 6 dB throughout, and then slowly increase the attack time (reduce the rate). There will be
a point where the voice suddenly starts jumping out. Keep it if you like it, but it will sound more natural if you back off of
the setting a bit. Now increase the release time (decrease the rate) until the notes sustain well but you aren't getting bursts of
breath.

For some singers, this procedure may be totally wrongwhat you need to do is learn how the ratio, attack and release work
with voices in general so you can respond to what you hear. Here are some situations to watch for:
A singer who does not sustain tones will benefit from short release times. Short release works like a guitar sustain
pedal. On the omx.comp~ you may want to tweak the gating threshold or progressive release parameters when you do
this.
Some singers belt certain syllables. This is where the omx.comp~ object shinesjust reduce the threshold until the
phrase evens out. With other devices, you may have to patch in a second limiter.
Some singer/microphone combinations will produce a lot of sibilance. A few compressors have a de-essing feature,
which boosts the highs going into the measuring circuit. The hiss will then trigger extra gain reduction. The
omx.4band~ object can be used to do this.

Bass
Bass players have to work hard to keep all of the notes even on their instrument. One reason for this is that the open notes
are much more resonant than fretted ones. Amplifiers contribute their share of problems, and by the time you add the
strangeness of close mic-ing a loudspeaker cone, the levels can vary widely. Compression can help; the amount of
compression to use depends on the individual player, but it generally doesnt have to be too heavy. When working with rock,
youll need a lot to keep the bottom solid. The attack will vary according to the type of music. Jazz bass requires a smooth
sound, so a quick attack will be used, but in hip hop the bass is almost a percussion part. Slow down the attack time to get a
punchy sound. Avoid stretching the notes with slow releaseitll sound muddy.

Drums
If you only use overhead microphones for a drum set, all you want is peak limiting, because compression on cymbals usually
sounds terrible. A snare microphone may be compressed if the head is dead or you want extra snare rattle, but a more
effective approach is gating with a rather high threshold. That way most of the snare sound comes from the overheads, but
the pop from the snare microphone will happen just a bit earlier and will give the rhythm a crisper sound. The gate keeps any
leakage from the high hat out of the mix. To gate with the omx.comp~, object, enable noise gating but not AGC.
Kick drum processing could fill an entire chapter of a book. In general, you are trying to find a balance between punch and
mud. The compressor is used to suppress the ring while keeping or even amplifying the strike. A slow attack is indicated here,
with the amount of compression determined by the length of ring from the drum.

Many times you will be trying to make up for the strange things drummers do to the kick drum to keep the sound from
bleeding into other tracks. An untamed bass drum will ring quite a long time, and that very low frequency gets in
everywhere. The result is you often see kicks with heads removed, holes cut in them, and various mutes attached. (The last
one I recorded had a ten pound pillow in it.) The resulting sound is best described as phlub. One common trick is to use
gated reverb. A fairly thick reverb is applied to the drum and fed through a compressor set up for external gating. The gate is
controlled by the unprocessed sound of the drum, so you get a lot of extra sound, but it does not tail off like normal reverb.
Some reverbs have gated settings, but you have little control over the effect.

See Also
Name Description
omx.comp~ OctiMax Compressor
omx.4band~ OctiMax 4-band Compressor
Multiband Compression 1
Multiband Compression 1
Open the tutorial.

Its usually the case that the bass, drums, vocals and other instruments are individually compressed before they are mixed
together. Sometimes this is not possible or desirable. For instance, a radio station or a DJ may wish for a louder and more
consistent sound than assorted CDs happen to provide. Simple compression is seldom satisfactory for this situation, because
sustained parts will be pumped by the vocals and drums. To prevent this, a multiband compressor treats each section of the
audio spectrum independently; you can have a full bass and constant rhythm while still letting the voice be heard.

The multiband compressor has found creative uses beyond the original intent of spicing up FM radio. If you start with a fairly
intense broadband headbanger mix, you can use the device to cram every last dB into every octave for that solid wall-of-
sound effect. Or, with a bit of restraint, you can master a recording to give a comfortable experience on a wide range of
playback systems.

Spectral Balancing
Good arrangers know how to orchestrate a score to give a balance between bass and treble that is satisfying and keeps the
listeners attention. This is called spectral balance. A similar effect can be achieved by compressing bass, midrange, treble,
and high frequencies for consistency and adjusting the levels of each to fit a curve that matches mid and treble, leaves
slightly less bass, and somewhat lower top end. This curve comes from analyzing the overall response of many successful
albums.

The 4-band compressor does a good job of solidifying a mix. The patch C5mMultibandComp4band shows the omx.4band~
object in action. This is a really complex gadget, far more than four compressors lashed together. There is quite a bit of
processing before the band-specific auto gain controls (AGCs).

There is a downward expander first, with an adjustable threshold to sweep away noise and dirt. This is followed by an
overall AGC, then the signal is split into four bands that are (approximately) deep bass, normal bass, midrange (where most
of the music occurs) and highs. There is a second downward expander on the high section, since high frequency noise is
especially annoying. Each band has a control for drive (the threshold is fixed at 0, so more gain here means more
compression), attack, release, and level into the final mix. Theres a final limiter to prevent any peaking.

Start by trying the three presets on some commercial music (probably already sort of squashed). Play with the outmix faders
to get a sense of where the bands are. Now try some raw tracks and adjust drive, attack and release to get the sound as full as
possible. As always, you get the most obvious effects when the meters are dancing.

The meters are rather enigmatic, but heres what they mean, left to right:
Left/right input. Provide enough signal to get these pretty high.
Release gating. This locks all release times when the input gets lowit helps prevent pumping of background noise. The
indicator goes high when release gating is on. (Note how the gain bars all stall.)
The two expanders, wideband and highs. This shows the gain of the expanders, so when they drop, signal is being shut
down.
The left and right master AGC gain. Usually you want the attack and release fairly slow, as these are just meant to keep
the overall level in the center of the dial.
The gain in the four bands. Unity gain is the lowest position.
Left and right limiting action. If these are pushing the floor, back off on the input.
Left and right output levels.
After a bit of practice you should be able to produce a full satisfying sound on any kind of material. The best test is to get it to
sound like the same music when played back softly or loud.

See Also
Name Description
omx.4band~ OctiMax 4-band Compressor
Multiband Compression 2
Multiband Compression 2
Open the tutorial.

Mastering
Mastering for different qualities of playback gear is a special art. The major difference between systems is the bass response
of the speakers. We would all like true response down to the limit of hearing, but physics and economics work against that.
Most budget speaker systems bottom out at 100 Hz or so, the bass drivers resonant frequency. If a speaker is resonant at
100 Hz, a 50 Hz signal will excite that resonance, and so will a 55 Hz signal. The result is that anything lower that the speaker
is equipped to handle will just add mud to the low end. Mastering engineers know this and roll off the signal below 75 Hz or
so. So, whats left to offer someone who spends the money to get speaker with a good bass response? Instead of just
throwing out the deep bass, we want to control it so that theres something for good speakers to reproduce without getting
the less expensive speakers overly excited. A multiband compressor is just the thing, because we can keep the bass full
without crossing the line. (To do this properly you have to listen to the mix on appropriate speakers, which is why you often
see low-end Radio Shack and Yamaha boxes in million dollar recording rooms.)

We also usually roll off the high end just a bit, as compressed highs keep the attacks crisp. However, if the level is too high
the effect is overly bright.
The omx.5band~ object compressor is detailed enough to provide this kind of fine control. (See the patcher
C6mMultibandComp5band.)

In addition to the features of the 4 band, the 5 band compressor features:


Five bands. The midrange is split into two, and the low bands are a bit lower.
An individual downward expander (noise gate) on each band.
Individual threshold and limiting on each band.
A switch on each band that sets what happens at the threshold. Amplification happens below the threshold, but you
have your choice of limiting or unity gain above.
The Overall AGC is split into two bands, with the lower labeled Bass Enhancement. These are slow-acting circuits that
keep the input where the compression can have best effect.
An extra soft clipper on the deep bass. Set this so small speakers arent thrown into resonance by notes below their
range.
A spatial enhancer. This separates the channels of mixes that are nearly but not quite mono. (A very common mixing
style, especially over the radio.) It does so by subtracting a bit of left from the right signal and vice versa, but only when
the two are nearly the same. The parameters for this are desired difference between the side signal and the combined
(mono) signal, maximum gain on the difference signals, and speed of response to changes in separation.
The presets in the for the omx.5band~ object illustrate various kinds of processing curves. The Universal setting is just a
general boost to the sound, with a 3-to-1 compression and no limiting. Bass enhancement is switched in for a bit of warmth.
The Pop setting, on the other hand, sets a 50:1 compression with hard driven limiting in the lowest two bands. The gives a
solid bottom to the sound. The Hit Radio settings are a compromise between the two. You will note that the times are all
about the same, with appropriately slower attack and release in the low bands. FM Radio differs primarily in the high end,
which is compressed a bit tighter than the pop and hit settings.

Since the omx.5band~ object uses seven times as much CPU as the four-band version, it may not be appropriate for
everyday usebut it will be perfect for a few tough tasks.

See Also
Name Description
omx.4band~ OctiMax 4-band Compressor
omx.5band~ OctiMax 5-band Compressor
Keying
Keying
Open the tutorial.

In keying, one sound turns another on (keying is sometimes referred to as side-chain gating and the key is sometimes
called the side-chain signal). This can produce some interesting electronic music effects, such as drum rhythms imposed on
a chorus. The patcher C7mKeying shows the compression patcher modified for keying. This did not require many changes
simply the separation of the control signal from the processed signal and the removal of the switch that triggers unity gain at
the threshold. One more thingthe sense of the gain calculation (difference between the control and the threshold) is
reversed by exchanging the leads on the math subpatch. Thus the amplification of the left signal is set by the level minus the
threshold. When the control level is below the threshold this is negative, giving a reduction in gain.

This kind of patch can be fussy about levels, so an output gain is provided to give extra boost if needed.

With this setup, a signal in the left channel will not pass through unless a signal is present on the right channel. The ratio
determines how much effect the control has on the left signal. If the ratio is set to 1:1, there is no effect at all. For ratios
much above 2:1, there may be some distortion. The threshold determines how strong the control has to be to turn the left
input on.

See Also
Name Description
rampsmooth~ Smooth an incoming signal
Microsounds
Microsounds
Open the tutorial.

We usually use the noise gate to keep from amplifying things that should not be heard when compressing. Sometimes these
in-between sounds are very interesting in themselves. I like to record very tiny sounds, like the ticking of a mechanical
stopwatch. When doing that, I use quite a lot of compression to bring up the ting of the spring while keeping the grind of the
winding at a reasonable level. The patcher C8mMicrosounds is set up for this. Compression is applied to signals that are
below the threshold, and signals above are unchanged. This leaves the notes essentially alone, but the sounds between the
notes are brought out. (This is how a guitar sustain pedal works.) Of course there is a lot of junk at very low levels we dont
want to hear, so the patch has a second threshold; levels below this threshold are unaffected.

Expansion
The C8mMicrosounds patcher has one more trick. The ratio can be set below 1:1. Fractional ratios give expansion, where soft
sounds are made softer. This can restore tracks that have been over compressed, or separate out the loudest sounds in a
pattern.

See Also
Name Description
rampsmooth~ Smooth an incoming signal
Ducking
Ducking
Open the tutorial.

Sometimes you use one sound to control the loudness of another. An example would be the automatic ducking you hear on
talk radio. The caller alone sounds loud and clear, but as soon as the host speaks, the caller is turned down. This can be done
using the patcher C9mDucking. Its just like the previous patcher, but with the control level again subtracted from the
threshold. The action of the patch is reversed, with the signal getting through the left only on the lack of control. Again, the
ratio affects the amount of gain change and the threshold sets the trip point.

See Also
Name Description
rampsmooth~ Smooth an incoming signal
Controlling Feedback
Controlling Feedback
Open the tutorial.

Delayed feedback is one of the most common MSP tricks, but we all know how hard it can be to keep the echoes from
building up and overwhelming everything. If you add a omx.comp~ object in the feedback path, as shown in the
C10mFeedback patcher, you can forget about the levels and concentrate on getting the rhythm right. Compressing and gating
have a lot to offer looping patches too.

This is just the tip of the compression iceberg. Most engineers practice and experiment with compressors throughout their
careers, and develop a wide repertoire of tricks. Compression can add impact to sound effects like thunder and breaking
glass, make a sleepy announcer sound lively, and balance the backup singers in a band. Many groups and producers owe their
signature sound to some magic compression setting, and it helps transmit the voices of operatic tenors safely over
television. In short, compression is one of the fundamental tools of modern audio technology.

See Also
Name Description
omx.comp~ OctiMax Compressor
Jitter Tutorials - Table of Contents
Topics
Jitter - What is a Matrix?
Attributes - Editing Jitter object parameters

Tutorials
Jitter Tutorial 1 - Playing a QuickTime Movie
Jitter Tutorial 2 - Create a Matrix
Jitter Tutorial 3 - Math Operations on a Matrix
Jitter Tutorial 4 - Controlling Movie Playback
Jitter Tutorial 5 - ARGB Color
Jitter Tutorial 6 - Adjust Color Levels
Jitter Tutorial 7 - Image Level Adjustment
Jitter Tutorial 8 - Simple Mixing
Jitter Tutorial 9 - More Mixing
Jitter Tutorial 10 - Chromakeying
Jitter Tutorial 11 - Lists and Matrices
Jitter Tutorial 12 - Color Lookup Tables
Jitter Tutorial 13 - Scissors and Glue
Jitter Tutorial 14 - Matrix Positioning
Jitter Tutorial 15 - Image Rotation
Jitter Tutorial 16 - Using Named Jitter Matrices
Jitter Tutorial 17 - Feedback Using Named Matrices
Jitter Tutorial 18 - Iterative Processes and Matrix Re-Sampling
Jitter Tutorial 19 - Recording QuickTime movies
Jitter Tutorial 20 - Importing and Exporting Single Matrices
Jitter Tutorial 21 - Working With Live Video and Audio Input
Jitter Tutorial 22 - Working With Video Output Components
Jitter Tutorial 23 - Controlling Your FireWire Camera
Jitter Tutorial 24 - QuickTime Effects
Jitter Tutorial 25 - Tracking the Position of a Color in a Movie
Jitter Tutorial 26 - MIDI Control of Video
Jitter Tutorial 27 - Using MSP Audio in a Jitter Matrix
Jitter Tutorial 28 - Audio Control of Video
Jitter Tutorial 29 - Using the Alpha Channel
Jitter Tutorial 30 - Drawing 3D text
Jitter Tutorial 31 - Rendering Destinations
Jitter Tutorial 32 - Camera View
Jitter Tutorial 33 - Polygon Modes, Colors and Blending
Jitter Tutorial 34 - Using Textures
Jitter Tutorial 35 - Lighting and Fog
Jitter Tutorial 36 - 3D Models
Jitter Tutorial 37 - Geometry Under the Hood
Jitter Tutorial 38 - Basic Performance Setup
Jitter Tutorial 39 - Spatial Mapping
Jitter Tutorial 40 - Drawing in OpenGL using jit.gl.sketch
Jitter Tutorial 41 - Shaders
Jitter Tutorial 42 - Slabs and Data Processing on the GPU
Jitter Tutorial 43 - A Slab of Your Very Own
Jitter Tutorial 44 - Flash Interactivity
Jitter Tutorial 45 - Introduction to using Jitter within JavaScript
Jitter Tutorial 46 - Manipulating Matrix Data using JavaScript
Jitter Tutorial 47 - Using Jitter Object Callbacks in JavaScript
Jitter Tutorial 48 - Frames of MSP signals
Jitter Tutorial 49 - Colorspaces
Jitter Tutorial 50 - Procedural Texturing & Modeling
Jitter Tutorial 51 - Jitter Java
Jitter Tutorial 52 - Jitter Networking
Jitter Tutorial 53 - Jitter Networking (part 2)

Appendices
Appendix A - QuickTime Confidential
Appendix B - The OpenGL Matrix Format
Appendix C - The JXS File Format
Appendix D - Building Standalone Applications with Jitter

Bibliography
Jitter Bibliography - For Your Further Reading Pleasure
What is a Matrix?
What is a Matrix?
A matrix is a grid, with each location in the grid containing some information. For example, a chess board is a matrix in
which every square contains a specific item of information: a particular chess piece, or the lack of a chess piece.

White has just moved a pawn from matrix location e2 to location e4.

For the sake of this discussion, though, let's assume that the "information" at each location in a matrix is numeric data
(numbers). Here's a matrix with a number at each grid location.

A spreadsheet is an example of a two-dimensional matrix.

We'll call each horizontal line of data a row, and each vertical line of data a column. On roadmaps, or on chessboards, or in
spreadsheet software, one often labels columns with letters and rows with numbers. That enables us to refer to any grid
location on the map by referring to its column and its row. In spreadsheets, a grid location is called a cell. So, in the example
above, the numeric value at cell C3 is 0.319.

The two pictures shown above are examples of matrices that have two dimensions, (horizontal) width and (vertical) height.
In Jitter, a matrix can have any number of dimensions from 1 to 32. (A one-dimensional matrix is comparable to what
programmers call an array. Max already has some objects that are good for storing arrays of numbers, such as table and
multislider. There might be cases, though, when a one-dimensional matrix in Jitter would be more useful.) Although it's a
bit harder to depict on paper, one could certainly imagine a matrix with three dimensions, as a cube having width, height,
and depth. (For example, a matrix 3 cells wide by 3 cells high by 3 cells deep would have 3x3x3="27" cells total.)
A 3x3x3 matrix has 27 cells.

And, although it challenges our visual imagination and our descriptive vocabulary, theoretically (and in Jitter) one can even
have matrices of four or more dimensions. For these tutorials, however, we'll restrict ourselves to two-dimensional matrices.

A Video Screen is One Type of Matrix


A video screen is made up of tiny individual pixels (picture elements), each of which displays a specific color. On a computer
monitor, the resolution of the screen is usually some size like 1024 pixels wide by 768 pixels high, or perhaps 800x600 or
640x480. On a television monitor (and in most conventional video images), the resolution of the screen is approximately
640x480, and on computers is typically treated as such. Notice that in all of these cases the so-called aspect ratio of width to
height is 4:3. In the wider DV format, the aspect ratio is 3:2, and the image is generally 720x480 pixels. High-Definition
Television (HDTV) specifies yet another aspect ratio16:9. In these tutorials we'll usually work with an aspect ratio of 4:3,
and most commonly with smaller-than-normal pixel dimensions 320x240 or even 160x120, just to save space in the Max
patch.

Relative sizes of different common pixel dimensions

A single frame of standard video (i.e., a single video image at a given moment) is composed of 640x480="307,200" pixels.
Each pixel displays a color. In order to represent the color of each pixel numerically, with enough variety to satisfy our eyes,
we need a very large range of different possible color values.

There are many different ways to represent colors digitally. A standard way to describe the color of each pixel in computers is
to break the color down into its three different color components red, green, and blue ( a.k.a. RGB)and an additional
transparency/opacity component (known as the alpha channel). Most computer programs therefore store the color of a
single pixel as four separate numbers, representing the alpha, red, green, and blue components (or channels). This four-
channel color representation scheme is commonly called ARGB or RGBA, depending upon how the pixels are arranged in
memory.
Jitter is no exception in this regard. In order for each cell of a matrix to represent one color pixel, each cell actually has to
hold four numerical values (alpha, red, green, and blue), not just one. So, a matrix that stores the data for a frame of video
will actually contain four values in each cell.

Each cell of a matrix may contain more than one number.

A frame of video is thus represented in Jitter as a two-dimensional matrix, with each cell representing a pixel of the frame,
and each cell containing four values representing alpha, red, green, and blue on a scale from 0 to 255. In order to keep this
concept of multiple-numbers-per-cell (which is essential for digital video) separate from the concept of dimensions in a
matrix, Jitter introduces the idea of planes.

What is a Plane?
When allocating memory for the numbers in a matrix, Jitter needs to know the extent of each dimensionfor example,
320x240and also the number of values to be held in each cell. In order to keep track of the different values in a cell, Jitter
uses the idea of each one existing on a separate plane. Each of the values in a cell exists on a particular plane, so we can
think of a video frame as being a two-dimensional matrix of four interleaved planes of data.

The values in each cell of this matrix can be thought of as existing on four virtual planes.

Using this conceptual framework, we can treat each plane (and thus each channel of the color information) individually
when we need to. For example, if we want to increase the redness of an image, we can simply increase all the values in the
red plane of the matrix, and leave the others unchanged.

The normal case for representing video in Jitter is to have a 2D matrix with four planes of dataalpha, red, green, and blue.
The planes are numbered from 0 to 3, so the alpha channel is in plane 0, and the RGB channels are in planes 1, 2, and 3.

The Data in a Matrix


Computers have different internal formats for storing numbers. If we know the kind of number we will want to store in a
particular place, we can save memory by allocating only as much memory space as we really need for each number. For
example, if we are going to store Western alphabetic characters according to the ASCII standard of representation, we only
need a range from 0 to 255, so we only need 8 bits of storage space to store each character (because 2 8 = 256 different
possible values). If we want to store a larger range of numbers, we might use 32 bits, which would give us integer numbers in
a range from -2,147,483,648 to 2,147,483,647. To represent numbers with a decimal part, such as 3.1416, we use what is
called a floating point binary system, in which some of the bits of a 32-bit or 64-bit number represent the mantissa of the
value and other bits represent the exponent.

Much of the time when you are programming in Max (for example, if you're just working with MIDI data) you might not
need to know how Max is storing the numbers. However, when you're programming digital audio in MSP it helps to be
aware that MSP uses floating point numbers. (You will encounter math errors if you accidentally use integer storage when
you mean to store decimal fractions.) In Jitter, too, it is very helpful to be aware of the different types of number storage the
computer uses, to avoid possible math errors.

A Jitter matrix can store numbers as 64-bit floating-point (known to programmers as a double-precision float, or double),
32-bit floating point (known simply as float), 32-bit integers (known as long int, or just int), and 8-bit characters (known as
char). Some jit objects store their numerical values in only one of these possible formats, so you will not have to specify the
storage type. But other Jitter objects can store their values in various ways, so the storage type must be typed in as an
argument in the object, using the words char, long, float32, or float64.

Important concept: In cases where we're using Jitter to manipulate video, perhaps the most significant thing to know
about data storage in Jitter matrices is the following. When a matrix is holding video dataas in the examples in the
preceding paragraphsit assumes that the data is being represented in ARGB format, and that each cell is thus likely
to contain values that range from 0 to 255 (often in four planes). For this reason, the most common data storage type is
char. Even though the values being stored are usually numeric (not alphabetic characters), we only need 256 different
possible values for each one, so the 8 bits of a char are sufficient. Since a video frame contains so many pixels, and
each cell may contain four values, it makes sense for Jitter to conserve on storage space when dealing with so many
values. Since manipulation of video data is the primary activity of many of the Jitter objects, most matrix objects use
the char storage type by default. For monochrome (grayscale) images or video, a single plane of char data is sufficient.
Editing Jitter object parameters
What are attributes?
Attributes are a new way to specify the behavior of Max objects. Most Jitter objects use attributes for the different variables
that make up their current internal state.

The good old Max counter object

Many Max objects, such as the counter object shown above, take a number of arguments to determine how they behave.
The order of these arguments after the object's name determines how the object interprets them. In the example above, the
first argument to counter sets the direction in which the object counts; the second and third arguments determine the
minimum and maximum values that the object counts between. Since these values are simply given to the object as
numbers, their ordering is important. With some Max objects (counter is one of them) the number of arguments you give
has some effect on the way in which they are interpreted. If you supply counter with only two arguments, they will be
understood by the object as the minimum and maximum count, not the direction and minimum count. Because the position
and number of arguments are crucial, there is no way, for example, to create a counter object with a predefined direction
and maximum count using only two arguments.

The arguments to an object are often seen as initial values, and Max objects typically have ways to modify those values
through additional inlets to the object or special messages you send the object. You can change the direction and maximum
count of a counter object by sending integers into its second and fifth inlets, respectively. These will override the default
values supplied by the arguments. Similarly, you can change the minimum count of the object by sending the message min
followed by an integer into the left inlet.

While this system works well when a Max object only has two or three variables that define its behavior, Jitter objects often
have many, many more variables (sometimes dozens). If all of these variables depended on the order of inlets and object
arguments, you would spend all day searching the reference manual and never have time to do any work with Jitter!

Setting Attributes
Jitter objects, unlike Max objects, can be told how to behave by using attributes. You can type attributes into an object box
along with the Jitter object's name, or you can set (and retrieve) attributes through Max messages after the object is created.

A Jitter object with attributes after the object name

The Jitter object shown above, called jit.brcosa, has three typed-in attributes. Typed-in attributes are set in object boxes by
using the @ symbol followed by the name of the attribute and one or more arguments (which could be any kind of Max data:
ints, floats, symbols, or lists). You can enter as many attributes as the object recognizes, in any order, after the object's
name. While you may not know what the jit.brcosa object does yet, you can infer a little bit about the object based on the
names of the attributes and what type of data they have assigned to them.

Important: There is no space between the @ sign and the name of the typed-in attribute you want to set. The @
character tells the Jitter object to interpret the word attached to it as an attribute name instead of an argument value
for a previous attribute.

Also Important: Jitter objects can have both typed-in attributes and typed-in arguments. See the Jitter Object
Arguments section below for details.

As with Max objects, the information you give a Jitter object to set its initial behavior is generally something you can change
after the object is created. Attributes can be changed at any time by sending messages to the object as shown below.
Attributes can be changed with Max messages

This jit.brcosa object has its brightness attribute set to 1.1 initially, but we've changed it to 1.0 by sending the message
brightness 1 into the object's left inlet. You can change virtually any attribute by sending a message with the attribute's
name, followed by the relevant arguments, into a Jitter object's left inlet.

As with Max objects, Jitter objects have default values for their parameters. The jit.brcosa object above only has typed-in
attributes initializing its brightness value, but other attributes are set to their default values. Well show you how to find out
what attributes an object uses below. In the example above, we can change the values of the object's contrast and
saturation attributes using messages, overriding whatever default values the object has supplied.

Jitter Object Arguments


There are four pieces of information that most Jitter objects use that can be entered either as typed-in attributes or typed-in
arguments. In fact, they are always attributes, but Jitter objects automatically handle them correctly when they are used as
arguments.

Jitter objects can have arguments, too!

The jit.rota object, shown above, clearly has one attribute initialized: theta. But what does the other stuff mean?
If you supply arguments for a Jitter object that processes Jitter matrix data (and most Jitter objects do), the arguments are
interpreted as:

1. The planecount of the output matrix. 2. The type of the output matrix. 3. The size, or 'dimension list' (dim), of the output
matrix.
Now that we know this, we can determine that the jit.rota object above will output a matrix that is made up of 4 planes of
char (8-bit integer) data with two dimensions of 320 by 240 cells.

Important: Jitter object arguments, if used, must appear before any attributes are set. Otherwise the Jitter object will
misinterpret the arguments as values for the attribute, not arguments to the object.

These arguments can also be set by attributes that are consistent for all Jitter objects that output matrix data: planecount,
type, and dim. They can be set as unordered typed-in attributes or changed with messages. The three objects below, for
example, are identical.

Arguments or attributes? You decide.

The first object has its output matrix attributes set using typed-in arguments. The second object has the planecount and
type set using typed-in arguments, but uses a typed-in attribute for the dimension list. The third object uses a typed-in
attributes to set everything.

If you prefer, you can initialize an objects attributes using messages triggered from a loadbang object as shown below.
Yet another way to initialize your attributes

Querying Attributes and Object State


An additional (and very useful) feature of attributes is that you can ask a Jitter object to tell you what value it currently has
stored for any given attribute. You do this by querying the attribute with the Max message get followed (with no space) by
the name of the attribute you want to know about. The resulting value is output by the Jitter object as a message (beginning
with the attribute's name), sent out the object's right outlet.

Querying an attribute for a Jitter object

Using get to find the values of attributes lets you discover the current value of an attribute, even if you never set the
attribute in the first place. For example, the patch below discovers some of the default values of the jit.plur object. The Max
route object lets you easily separate the values for each of the attributes.

Finding out the default values of object attributes

Two messages you can send to any Jitter object, getattributes and getstate, output all the attributes used by the object.

Finding out your options

The getattributes message causes the Jitter object to output the message attributes followed by a list of all the attribute
symbols that Jitter object understands. Experimenting with a few Jitter objects will quickly show you that many of these,
such as outputmode, type and dim, are fairly standard. Others (such as mask in the jit.brass object) will have special
meaning for the object that uses them.

The getstate message dumps out all the attributes for the Jitter object as if every conceivable attribute query had been
performed all at once.
Finding an object's state

You can then use route, unpack, and other Max objects to extract the attributes as you need them. Later in the tutorials, you
will encounter several Jitter objects where the attributes change based on calculations performed on the input matrix (or a
file that has just been opened by the object). Querying the relevant attributes is how you can find out the result of the
object's calculation.

Jitter attributes are a powerful tool for managing the parameters of complex objects. You can use attributes to initialize,
change, and find out the current values stored in Jitter objects, and the attachment of each value to a fixed attribute name
eliminates the need to remember typed-in argument ordering or the role of each inlet in a complex object.
Playing a QuickTime Movie
Tutorial 1: Playing a QuickTime Movie
This first tutorial demonstrates one of the simplest yet most useful tasks you can perform with Jitter: playing a QuickTime
movie in a window.
Open the tutorial.

There are two Jitter objects in this patch: jit.qt.movie and jit.window. The jit.window object automatically opens a window
on your computer screen. The jit.qt.movie object allows you to open an existing QuickTime movie, and begins to play it.
Click on the message box containing the message read countdown.mov. This causes the jit.qt.movie object to open the
QuickTime movie file countdown.mov and begin reading from it.

The read message opens a QuickTime movie file.

By default a jit.qt.movie will begin playing a movie as soon as it opens it. (Alternatively, you can alter that behavior by
sending a jit.qt.movie object an autostart 0 message before opening the file, but for now the default behavior is fine.)
Notice, however, that even though we've said that the jit.qt.movie object is playing the movie, the movie is not being shown
in the Movie window. Here's why:

Each object in Jitter does a particular task. The task might be very simple or might be rather complicated. What we casually
think of as "playing a QuickTime movie" is actually broken down by Jitter into two tasks:

1. Reading each frame of movie data into RAM from the file on the hard disk 2. Getting data that's in RAM and showing it as
colored pixels on the screen.
The first task is performed by the jit.qt.movie object, and the second by the jit.window object. But in order for the
jit.window object to know what to display, these two objects need to communicate.

How Jitter Objects Communicate

Important Concept: The most important thing that Jitter objects communicate to each other is a name, referring to a
matrixa place in memory where data is stored. (We'll explain the meaning of the word "matrix" in more detail in the
next tutorial chapter.) Jitter objects output a message that only other Jitter objects understand. That message is the
word jit_matrix followed by a space and the name of a matrix where data is stored. This message is communicated
from one Jitter object to another through a patch cord in the normal Max manner. (But, just as MSP objects' patch
cords look different from other Max patch cords, the patch cords from Jitter obejcts' outlets that send the jit_matrix
message have their own unique look.) The receiving Jitter object receives the message in its inlet (most commonly the
left inlet), gets the data from the specified place in memory, modifies the data in some way, and sends the name of the
modified data out its left outlet to all connected Jitter objects. In this way, tasks are performed by each object without
necessarily knowing what the other objects are doing, and each object gets the data it needs by looking at the
appropriate place in memory. Most Jitter objects don't really do anything until they get a jit_matrix message from
another Jitter object, telling them to look at that matrix and do something with the data there.

In many cases a Jitter object will generate a unique name for its matrix on its own. In other cases, it is possible (and
even desirable) to tell an object what name to use for a matrix. By explicitly naming a matrix, we can cause objects to
use that same memory space. You will see examples of this in future tutorial chapters.

Causing Action by Jitter Objects


What causes one Jitter object to send a jit_matrix message to another object? Most Jitter objects send out a jit_matrix
message when they receive the message outputmatrix or bang. (These two messages have the same effect in most Jitter
objects.) The other time that an object sends out a jit_matrix message is when it has received such a message itself, and has
modified the data in some way; it then automatically sends out a jit_matrix message to inform other objects of the name of
the matrix containing the new data.

To restate the previous paragraph, when an object receives a jit_matrix message, it does something and sends out a
jit_matrix message of its own. When an object receives outputmatrix or bang, it sends out a jit_matrix message without
doing anything else.

So, in our example patch, the jit.qt.movie object is "playing" the QuickTime movie, constantly storing the current frame of
video, but the jit.window object will only display something when it receives a jit_matrix message from the jit.qt.movie
object. And that will only happen when jit.qt.movie receives the message bang (or outputmatrix). At that time, jit.window
will display whatever frame of video happens to be currently playing in the movie (that is, the frame that's currently stored
by jit.qt.movie).
In order to make jit.window update its display at the desired rate to show a continuously progressing video, we need to send
the message bang to jit.qt.movie at that rate.

The movie is playing in jit.qt.movie,


but we need to send it a bang each time we want to display a frame.

Click on the toggle object marked "Play" to start the metro object. This will send out bang at the rate of 25 times per
second (every 40 milliseconds). That should be fast enough to display every frame of this video. As long as the bang
messages continue, you will see the movie displayed in the Movie window.

jit.window displays the contents of a matrix: in this case a frame of a QuickTime movie.

Click on the toggle to stop the metro. The jit.window object stops updating the Movie window, so you will now just see a
still image of whatever frame was last displayed. The movie is still "playing"and jit.qt.movie is still updating its memory
frame-by-framebut jit.window is now oblivious because jit.qt.movie is no longer sending messages.
You can verify that the movie is still progressing by clicking on the button object just below the metro. This will cause
jit.qt.movie to send a jit_matrix message to jit.window, which will update the Movie window with the current frame. If you
do this a few times, you will see that the movie has progressed in between clicks of the mouse. (The movie is a ten-second
countdown, playing in a continuous loop.)

To summarize, jit.qt.movie is continually reading in one video frame of the QuickTime movie, frame by frame at the movie's
normal rate. When jit.qt.movie receives a bang, it communicates the location of that data (that single frame of video) to
jit.window, so whatever frame jit.qt.movie contains when it receives a bang is the data that will be displayed by
jit.window.
Arguments in the Objects
The jit.qt.movie object in this tutorial patch has two typed-in arguments: 320 240. These numbers specify the horizontal
and vertical (width and height) dimensions the object will use in order to keep a single frame of video in memory. It will
claim enough RAM to store a frame with those dimensions. So, in the simplest case, it makes sense to type in the dimensions
of the movie you expect to read in with the read message. In this case (since we made the movie in question ourselves) we
happen to know that the dimensions of the QuickTime movie countdown.mov are 320x240.

If we type in dimension arguments smaller than the dimensions of the movie we read in, jit.qt.movie will not have claimed
enough memory space and will be obliged to ignore some of the pixels of each frame of the movie. Conversely, if we type in
dimension arguments larger than the dimensions of the movie we read in, there will not be enough pixels in each frame of
the movie to fill all the memory space that's been allocated, so jit.qt.movie will distribute the data it does get evenly and will
fill its additional memory with duplicate data.

The jit.window object has five typed-in arguments: Movie 5 41 325 281. The first argument is a name that will be given to
the matrix of data that jit.window displays. That name will also appear in the title bar of the movie window. It can be any
single word, or it can be more than one word if the full name is enclosed between "smart single quote" characters. (Smart
single quotes are the characters and , obtained by typing option-] and shift-option-] on a Macintosh system or typing ALT
0145 and ALT 0146 for the left and right single quotes on a Windows system. The next two arguments indicate the x,y screen
coordinates of the upper-left corner of the display region of the movie window, and the last two arguments provide the x,y
coordinates of the lower-right corner of the display region. (Another way to think of these four numbers is to remember
them as the coordinates meaning "left", "top", "right", and "bottom".) We have chosen these particular numbers because a)
they describe a display region that is 320x240 pixels, the same size as the movie we intend to display, and b) when we take
into account the dimensions of the window borders, title bar, and menu bar that the OS imposes, the entire window will be
neatly tucked in the upper-left corner of our useable desktop. (It's possible to make the window borders and title bar
disappear with a border 0 message to jit.window, but the default borders are OK for now.)
We have typed the value of 40 in as an argument to metro to cause it to send out 25 bang messages per second. The
QuickTime movie actually has a frame rate of exactly 24 frames per second, so this metro will trigger the jit.qt.movie object
frequently enough to ensure that every frame is made available to jit.window and we'll get to see every frame.
The jit.qt.movie object actually understands many more messages besides just bang (way too many to try to explain here).
In the upper-right corner of the Patcher window, we've included an example of one more message, simply to demonstrate
that the progress of the QuickTime movie can be controlled in jit.qt.movie independently of the rate at which the metro is
sending it bang messages. The message time, followed by a number, causes jit.qt.movie to jump immediately to a specific
time location in the movie.

Click on the button object labeled "Restart". This sends a message of time 0 to jit.qt.movie. causing it to jump to the
beginning of the QuickTime movie, and then sends a 1 message to the toggle to start the metro and begin displaying the
movie.

To play a QuickTime movie, use the jit.qt.movie object to open the file and read successive frames of the video into RAM,
and use the jit.window object to display the movie in a separate window. Use typed-in arguments to specify the dimensions
of the movie, and the precise coordinates of the display area on your screen.

Jitter objects communicate the information about a particular frame of video by sending each other the name of a matrixa
place in memory where that information is located. When a Jitter object gets a matrix name, it performs its designated task
using the data at that location, then sends out the name of the modified data to other Jitter objects. Almost all Jitter objects
send out a name (in a jit_matrix message) when they receive the message bang (or outputmatrix). Thus, to show
successive frames of a video, send bang messages at the desired rate to ajit.qt.movie object connected to a jit.window
object.

Tracing the messages and roles of each object

See Also
Name Description
jit.qt.movie Play or edit a QuickTime movie
jit.window Display data in a window
metro Output a bang message at regular intervals
Create a Matrix
Tutorial 2: Create a Matrix
What's a Matrix?
This tutorial chapter demonstrates some ways to manage numerical data in a matrix.

If you are in doubt about what a matrix is, please first read the chapter titled "What's a Matrix?" in the Topics section. To
summarize here, a matrix is a scheme for storing and modifying large sets of numerical data, by placing the values in a
virtual grid. By storing data in a matrix, we can easily identify a particular value by its location in the grid, and we can modify
many values at once by referring to all or part of a matrix.

In the previous tutorial chapter, we used thejit.window object to open a window and display the contents of a matrix as
colored pixels. The matrix being displayed was from the jit.qt.movie object, an object that continually fills its matrix with
the current frame of a QuickTime video. The fact that jit.window was displaying a video, however, was just because that
happened to be the contents of the matrix it was being told to display; but in fact any numerical values in a matrix can be
visualized similarly. The example patch for this tutorial will show an even simpler example that should help strengthen your
understanding of a matrix, the central idea of Jitter.

The jit.matrix object


Open the tutorial.

Create a 16x12 storage space for single 8-bit values.

The jit.matrix object simply creates a matrix, a storage space in memory. We can then store and retrieve numerical values in
the matrix, and we can use other objects to print the values or display them visually. The arguments for jit.matrix are an
optional [name] argument (not included in this example), the [planecount] (how many values will be stored in each cell of
the matrix), the [type] of data (how many bytes to use to represent each number), and then the [dim] (short for
"dimensions", describing how large the matrix will be). We use the brackets [] to indicate that this is not the actual word you
type in as an argument, but rather a description of the meaning of the argument. The object in this example will create a
matrix with 1 plane (one number in each matrix location), using the char data type (single-byte values), with dimensions
16x12 (which equals 192 cells). From this we can deduce that the matrix is capable of holding 192 individual numerical
values, with each value ranging from 0 to 255 (that's the range of a single byte).

Note: We always describe the dimensions of a two-dimensional matrix in x,y (width, height) format, meaning that we
first state the extent of the horizontal dimension, then the vertical dimension. This is consistent with the way these
dimensions are commonly discussed in video and computer screen layout (a 640x480 video image, for example). An
alternative way to think of this is that we first state the number of (vertical) columns of data, then the number of
(horizontal) rows. You might want to note, however, if you're applying matrix techniques of linear algebra in Jitter,
that this formatcolumns, rowsis different from the way matrices are commonly described in linear algebra, which
states rows first, then columns.

We've connected a button object to the inlet of jit.matrix. You'll recall that Jitter objects send out their matrix name when
they receive a bang message in their left inlet, so this button will permit us to trigger jit.matrix to send out its matrix name
(in the form of a jit_matrix message).

The jit.print object

Create a 16x12 storage space for single 8-bit values.


Beneath the jit.matrix object there is another new Jitter object, jit.print. This object accepts a matrix name (i.e., a
jit_matrix message) in its inlet, and formats the values of the matrixthe sheer number of which can be pretty unwieldy
for printing in the Max window. It prints the formatted values directly to the Max window, much like Max's print object, and
then passes the matrix name out its left outlet in a jit_matrix message (in the normal manner for Jitter objects).

Click on the button object marked "output". This causes the jit.matrix object to communicate its matrix name to jit.print,
which formats the values and prints them in the Max window.

In the Max window you will now see the text left: jit_matrix [somename]. The word left shows us that this was printed by
the print left object, so we can see that that is what came out of the outlet of jit.matrix. Because we didn't choose a name for
that matrix (we didn't provide a name as the first typed-in argument to jit.matrix), jit.matrix assigned a name of its own
choosing. It tries to generate a unique name that's not likely to be used elsewhere, so it usually chooses something strange
like "u330000007". In this case we don't really care what the name is, but it does tell the jit.print object what matrix of
data to format for printing.

Below that, you will see all of the values in this particular matrix, formatted neatly in 16 columns and 12 rows. Those came
from jit.print. They're all 0 right now, because we haven't placed anything else in the matrix yet.

Setting and querying values in a matrix


In the previous chapter we saw how an entire matrix could be filled automatically with frames of color data from a
QuickTime movie. It is also possible to place numerical values in specific individual cells of the matrix, and retrieve values
from specific locations. The objects immediately above jit.matrix in this example show a few messages you can use for
setting and getting values in a matrix.

The messages setcell and getcell allow you to access specific values in a matrix.

You can store values in a particular matrix location with the setcell message. The syntax for doing so is: setcell [cell
coordinates] val [value(s)]. For example, the message setcell 0 0 val 127 to our jit.matrix would set the value of the very
first cell of the matrix (i.e., the cell in the upper-left corner) to 127. This is because we number the cell coordinates in each
dimension starting with 0 and going up to 1 less than the extent of that dimension. So, in this matrix, locations in the x
dimension are numbered from 0 to 15 and locations in the y dimension are numbered 0 to 11. Thus, the cell in the lower
right corner would be described with the cell coordinates 15 11.

The combination of the pack 0 0 0 object and the message box helps us to format a proper setcell message for
jit.matrix. First we set the x and y positions where we want to store the value, then we specify a value to be stored there.
With the x and y positions at 0 0, use the number box labeled "value" to send the number 127 into the left inlet of pack 0
0 0. This will cause the message setcell 0 0 val 127 to be sent from the message box to the jit.matrix.

The message setcell 0 0 val 127 sets the value of cell position 0, 0 to 127.

(If there were more than one plane in this matrix, we could set the values in a particular plane of a cell, or in all planes of the
cell. However, this matrix has only one plane, so we'll leave that for another time.)

Just to demonstrate what we said earlier about the numbering of cell positions, try sending the message setcell 15 11 val
255 to jit.matrix. First enter the number 15 into the "x position" number box and the number 11 into the "y position",
then enter the number 255 in via the "value" number box. Now click on the button marked "output" to see how the matrix
has been changed. Once again the entire matrix will be printed in the Max window via jit.print. Notice that the values in cell
positions 0, 0 and 15, 11 have been changed to 127 and 255.

The message setcell 15 11 val 255 sets the value of cell position 15, 11 to 255.

In your Patcher window you may have noticed a change in the black rectangular region. The upper-left and lower-right
corners of it have changed. (If you covered it with your Max window, you may have to click the "output" button once more
to see this change.)

The jit.pwindow object displays numerical values as colors (or greyscale values).

This region is a user interface object called jit.pwindow. In the object palette it appears like this:

The jit.pwindow cursor in the object palette

When you choose this object from the palette and click in the Patcher window, it creates a small rectangular object. (You can
click in the grow bar in the lower-right corner of the object to adjust its dimensions.) This object is pretty much equivalent in
function to the jit.window object, but it displays matrix data inside the Patcher window, rather than in a separate window.
So, here we see quite literally the display of numerical values (in this case, char data in the range from 0 to 255) as color.
Because there is only one plane in this matrix we're displaying, the display is monochromethat is, greyscale. The 0 values
are totally black, and the other values are some level of gray, up to 255 which is totally white. Thus, the 255 value at cell 15,
11 is displayed as white, and the 127 value at 0, 0 is displayed as a 50% gray, halfway between black and white.

You might say, "That's all very well, but it will be pretty tedious to fill a large matrix this way." And you'd be right. But of
course Max allows us to write another part of the program that will automate the process.

Filling a matrix algorithmically


Double-click on the patcher fillmatrix object to open the subpatcher window fillmatrix. This subpatcher generates 192
different values, one for each position in the matrix, by feeding different numbers into a mathematical expression.
You can generate values algorithmically to fill the cells of a matrix.

When the uzi 12 object receives a bang (from the button labeled "fill" in the main Patcher window) it quickly counts from 1
to 12 out its right outlet and sends a bang for each count out its left outlet. Those bangs trigger the uzi 16 object, so that it
sends out numbers from 1 to 16 each time. We subtract 1 from these numbers so that they actually go from 0 to 11 and from
0 to 15, and we use the resulting numbers as y and x positions in the matrix. For each of the 12 y positions, the uzi 16 object
specifies all the x positions, and then uses those numbers in a mathematical expression (in expr) to calculate the value to be
stored at that position. These numbers are sent out the outlets, and are used to create well-formed setcell messages in the
main patch, just as we did by hand earlier.

The mathematical expression here is relatively unimportant. It could be any formula that generates an interesting pattern of
data. In this case we have chosen a formula that will produce a sinusoidal gradation of brightness in each column, and the
will cause the overall brightness of the columns to increase from left to right (i.e., as x increases).

Close the fillmatrix subpatch window and click on the button labeled "fill". The matrix is filled with values (generated by
the uzi objects in the subpatch) in a single tick of Max's scheduler. Now click on the button labeled "output" to view the
contents of the matrix. The numerical values will be printed in the Max window, and displayed in the jit.pwindow.
Even for a small 16x12 matrix like this, it's tough for us to perceive a trend in numerical data just by looking at a printout of
numbers in the Max window. However, the display in the jit.pwindow gives us a very clear and immediate idea of how the
values vary within the matrix. This demonstrates one of the benefits of visualization of numerical data.

You can no doubt imagine other ways to fill a matrix algorithmically in Max, and in fact we'll demonstrate other ways in later
tutorial chapters.

Other messages to jit.matrix


There are many other messages understood by jit.matrix, more than we can demonstrate fully here. On the right side of the
Patcher we show a couple of other handy messages for filling a jit.matrix instantly with all the same values. The clear
message to jit.matrix sets all its values to 0, and the setall message (the word setall followed by a value) sets every position
in the matrix to that value.

We also demonstrate the getcell message. The word getcell followed by a location in the matrix (x and y positions) will
cause jit.matrix to send the cell coordinates and value of that position out its right outlet.
Enter a y value and then an x value into the number boxes above the getcell $1 $2 message box, and observe what is
printed in the Max window. Note that the value at that matrix position is reported out the right outlet of jit.matrix.
Query the value(s) at matrix position 8, 6; reports cell 8 6 val [value(s)]

In future tutorial chapters you will see various ways to use values retrieved from a matrix.

The jit.matrix object creates a storage space for a named matrix of data, with whatever dimensions, planes, and data type
you specify. This matrix can be filled with data from another Jitter object (such as jit.qt.movie), or by messages such as
setall [value] to set the value in all cells or setcell [position] val [value(s)] to set a specific cell. You can use an algorithm
elsewhere in the patch to fill the matrix according to a formula or a set of rules.

To get the data in a specific cell, you can use the getcell [position] message. To see all of the numerical data printed out in
the Max window, use the jit.print object to format the matrix data and print it. To see the matrix data displayed as colors,
use the jit.pwindow object. This is similar to the use of the jit.window object demonstrated in Tutorial 1.
In this tutorial we viewed numerical data that we generated ourselves, rather than digital video as in the preceding chapter.
The principle of storage is the same in both cases. Whether a matrix is used to store color information for each pixel from a
frame of digital video, or abstract numbers which we wish to view as color, the numbers in both chapters are stored in a
two-dimensional matrix and are easily displayed in a jit.window or jit.pwindow.

See Also
Name Description
expr Evaluate a mathematical expression
jit.matrix The Jitter Matrix!
jit.print Print a matrix in the Max window
jit.pwindow Show data in a patcher
pack Create a list
print Print any message in the max window
uzi Send many bang messages
Math Operations on a Matrix
Tutorial 3: Math Operations on a Matrix
This tutorial shows how you can perform simple mathematical operations on the data stored in a Jitter matrix. We'll show
you how to use the jit.op object to perform arithmetic scaling of matrix cells, or of individual planes within those cells.
Open the tutorial.

The tutorial patch is split into three simple examples of mathematical operations you can perform with the jit.op object. The
jit.op object performs mathematical operations on entire matrices of data at a time rather than individual numbers.

Adding a constant value to all cells in a matrix.

The first example shows a jit.matrix object hooked up to a jit.op whose output is viewable by a jit.pwindow object.
Everytime you change the number box hooked up to the right inlet of the jit.op object a bang will put out a new matrix from
the jit.matrix object. As you can see from its arguments, the jit.matrix object is generating a 4x3 matrix of single-plane char
data (i.e. data in the range 0-255). The jit.pwindow object will visualize this matrix for you as a greyscale image. Dragging
the number box will change the level of grey shown in the jit.pwindow from black (0) to white (255).
It's important to realize that the jit.matrix object is putting out a Jitter matrix that has all its cells set to 0. If you were to
connect the jit.matrix and jit.pwindow objects together and bypass the jit.op, you would see a black image, no matter how
many times you send a bang message to the jit.matrix object. The jit.op object is adding a value (as defined by the number
box) to all the cells in the Jitter matrix sent between the jit.matrix and the jit.op objects.

Operation @-Sign
We said above that the jit.op object adds a value to all the cells in its input matrix. The jit.op object adds a value (rather
than, say, dividing or multiplying) because of the value of its op attribute. The op attribute is a symbol (or a list of symbols,
as we'll see in a moment) that defines what math the jit.op performs on its input matrix. In this case, we can see that the op
attribute is set to the value of +, which means that it performs simple addition on any matrix that arrives in its left inlet. The
integer value in the right inlet is added to all the cells in the matrix. This value is referred to as a scalar, because it adds the
same value to the entire matrix (in Tutorial 9 we show how jit.op can do math using two Jitter matrices as well).

Important note: Changing the scalar value in the right inlet of the jit.op object does not output a new matrix. If you
were to disconnect the patch cord between the number box and the button object, the jit.pwindow object would stop
showing you anything new. The reason for this is that as with most Max objects, most Jitter objects only output data
when something comes into their leftmost inlet. In the case above, each time you change the number box, the jit.op
object stores the new scalar value. As soon as that happens, the button object sends a bang to the jit.matrix object,
causing it to send a new Jitter matrix (with all its values set to 0) into the left inlet of the jit.op object, triggering an
output matrix which you can see. If you choose the Enable command from the Trace menu, and then step through the
message order with the Step command (-T), you will see how this plays out. (See the "Debugging" chapter of the
Max 4.0 Tutorials and Topics manual for details about how to trace Max messages with the Trace feature.)

The scalar value can also be supplied as a constant by using the val attribute of jit.op. For example, if we always wanted to
add 134 to all the cells of an incoming Jitter matrix, we could use this object and dispense with the number box:

Setting a scalar as an attribute.


Similarly, if we wanted to change the mathematical operation performed by any given jit.op object, we could send the
message op followed by the relevant mathematical symbol into the object's left inlet.

Math Operations on Multiple Planes of Data


The second example shows a more complicated instance of using jit.op to add values to an incoming matrix.

Using separate scalars for each plane of a matrix

This patch is similar to the first one, with the important difference that we are now working with a 4-plane matrix. This is
shown by the first argument to the jit.matrix object that generates the matrix we're using. The jit.pwindow now shows
things in color, interpreting the four planes of Jitter matrix data as separate color channels of alpha, red, green, and blue.
Our jit.op object in this example has a list of four symbols for its op attribute: each symbol sets the mathematical operation
for one plane of the incoming matrix. In this patch we're going to pass the first (alpha) plane through unchanged, and add
numbers to each of the other planes. (You can mix and match operators like this to your heart's content.)

The pak object feeding the right inlet of our jit.op object takes four integers and packs them into a list. The only difference
between pak and the Max pack object is that pak will output a new list when any number is changed (unlike the pack
object, which needs a new number or a bang in the left inlet to output a new list). The four numbers in the list generated by
pak determine the scalars for each plane of the matrix coming into the jit.op object. In the example above, plane 0 will have
nothing added to it (the first argument of the op attribute is pass). Planes 1, 2, and 3, will have 161, 26, and 254 added to
them, respectively. Our jit.pwindow object will interpret the cells of the output matrix as lovely shades of magenta (even
though we see only one color, there are in fact 12 different cells in the matrix, all set to the same values).

Important Note: If we decided to use only one value for the op attribute of the jit.op object above (and only used one
number as a scalar), jit.op would use that mathematical operator and scalar value for all planes of the incoming
matrix.

Modifying the Colors in an Image


The third example shows a use of jit.op on a matrix that already has relevant data stored in it:

Multiplying individual planes with scalars

Click the message box importmovie colorbars.pict. The importmovie message to jit.matrix loads a single frame of an
image from a picture or QuickTime movie file into the Jitter matrix stored by the object. It will scale the picture on the disk
to the dimensions of its own matrix (in this case, 320 by 240).

Clicking the button object shows you image calibration colorbars in the jit.pwindow on the right of the patch. In this case,
our jit.op object has its arithmetic operators set to pass for the alpha plane and * (multiply) for the other planes. Since we're
working with a 4-plane image, we set each of the scalars using a list of 4 floating-point numbers. Values of 1. in planes 1
through 3 will show you the image as it appears originally:

All scalars at 1.

If you set the scalars to 1., 0., and 0., you should see the following image:

The mean reds.

All of the planes (except plane 1) of the matrix containing the colorbars have been multiplied by 0. This will eliminate the
alpha, green, and blue planes of the matrix, leaving only the red (plane 1) behind.

Setting intermediate values (such as 0., 0., 1. and 0.5) as the scalars for jit.op will give you an image where the colorbars
look different:

Pretty, isn't it?

In this case, the alpha channel is ignored and the red channel is zeroed. The blue plane's values are all half of what they
were. The green channel (plane 2) is left untouched.

Important Note: Some mathematical scalars in jit.op are expressed as floating-point numbers, and some are
expressed as integers. This depends on the relevant operator (defined by the op attribute), as well as the type of the
input matrix. Since all the examples in this tutorial use char matrices, it makes sense to use integers when adding to
them (any floating-point numbers will be truncated, as the matrix data needs to remain as integers in the range 0-
255). If we were using a float32 matrix as our input, it would make perfect sense to add floating-point numbers to it.
Similarly, it's reasonable to multiply a char matrix by a floating-point scalar (240 * 0.5 = 120, an integer). However,
since the matrix output by jit.op will still be a char matrix (see note below), you will still only get values in the range of
0-255.

If you experiment with the scalar values you will see that you can easily make some of the colorbars disappear or merge with
neighboring bars. This is because the colorbars are all set to standard color values with similar ranges. If you show only one
channel at a time (by setting all planes but one to 0), four of the seven bars along the top will show color.

We have demonstrated the + and * operators in this tutorial, but in fact the jit.op object can perform a great many other
math operations. For a complete list of the possible operators, see the reference page, or double-click on the p op_list
subpatch in the jit.op help file.

Sizing it Up
When you create a jit.pwindow object, it will appear in the Max window as 80 pixels wide by 60 pixels tall. You can change
its size using its grow box, just like many of the user interface objects in Max. If you want to change its size precisely, you
can do so using its Inspector or by sending it the size message followed by a width and height, in pixels:

Changing the size of a jit.pwindow

If you send a jit.pwindow object of a certain size (in pixels) a matrix with a different size (in cells), the jit.pwindow object
will scale the incoming matrix to show you the entire matrix. If you send a very small matrix to a very large jit.pwindow, you
will see pixelation (rectangular regions in the image where the color stays exactly the same). If you send a small jit.pwindow
a large matrix, varying degrees of detail may be lost in what you see.

Important Note: in the example above, our jit.matrix holding the colorbars had a size (specified by its dim list) of
320 by 240 cells, a planecount of 4, and a type of char. The jit.op object (and most Jitter objects you will encounter)
recognizes that information and adapts to perform its calculation on the entire matrix and output a matrix of the same
specifications. If we were to change the jit.matrix object to some different size, the jit.op object would instantly
recognize the change and re-adapt. The jit.pwindow object also adapts to the incoming matrix, but in a slightly
different way. If the incoming matrix is smaller than its own dimensions, it uses duplicate data to fill all of its pixels.
(This results in the pixelation effect described in the previous paragraph.) If the incoming matrix is larger than its own
dimensions, it will be obliged to ignore some of the data, and will only display what it can. So, even though the
jit.pwindow objects in the Tutorial patch never match the size (in cells) of their matrix input, they do their best to
adapt to the size of the jit.op object's matrix. The jit.pwindow in the last example shows you as much as it can of the
entire matrix output by the jit.op object, but it has to ignore every other row and column in order to fit the 320x240
matrix it receives into its own 160x120 display area.

The jit.op object lets you perform mathematical operations on all the data in a Jitter matrix at once. You can perform
calculations on the matrix cells in their entirety or on each plane separately. The mathematical operation that jit.op will
perform is determined by its op attribute, which can be typed in as an @op [operator] attribute argument or provided by an
op [operator] message in the left inlet. For multiple-plane matrices (such as color pictures and video), you can specify the
operation for each plane by providing a list of operators (e.g. op pass * * *), and you can provide different scalar values for
each plane. In Tutorial 9 you will see how you can use a second Jitter matrix to act in place of a simple scalar.

You can set the size of a jit.pwindow object with a size [width] [height] message. The jit.pwindow will do its best to adapt
to the size of any matrix it receives. It will duplicate data if the incoming matrix is smaller than its dimensions, and it will
ignore some data if the incoming matrix is larger than its own dimensions. Most Jitter objects do their best to adapt to the
dimensions, type, and planecount of the matrix they receive. In the case of jit.op, it does not have specified dimensions of its
own, so it adapts to characteristics of the incoming matrix.

See Also
Name Description
jit.matrix The Jitter Matrix!
jit.op Apply binary or unary operators
pak Output a list when any element changes
Controlling Movie Playback
Tutorial 4: Controlling Movie Playback
This tutorial expands on what we've learned thus far about playing back QuickTime movies in Jitter. We'll learn how to get
some useful information about the movie that you're playing, as well as how to manipulate the playback of the movie by
changing its speed, volume, and loop points.
Open the tutorial.

The two Jitter objects in this patch should already be familiar to you: jit.qt.movie and jit.pwindow. The rest of the patch
will let you experiment with changing the playback behavior of the movie you have loaded into the jit.qt.movie object.
The left side of the patch should seem very familiar to you from the very first tutorial:

Open and play the movie.

Open the file crashtest.mov by clicking the message box that says read crashtest.mov.
The movie clip should begin playing as soon as it is read into the jit.qt.movie object. Since this movie has a soundtrack, you
should begin to hear some music as soon as the movie is loaded. The movie soundtrack will come out of the Sound Manager.
If you normally use an ASIO driver with MSP, you will need to connect and set up your Sound Manager outputs so that you
can hear them.

You won't see anything in the jit.pwindow because, even though the movie is playing, the jit.qt.movie object needs a bang
message to send a matrix out to the jit.pwindow. Start the metro object by clicking on the toggle box connected to its inlet.
You will see the movie's image appear in the jit.pwindow object. Don't worry about the gettime message yet; we'll get to
that below.

Obtaining Some Information About the Movie


The first thing we want to do with this QuickTime movie is get some information about it. The Jitter attribute system lets us
query information about Jitter objects at any time, and use that information in our Max patch. Attribute information is
always retrieved by sending get messages to a Jitter object's left inlet. We then parse the Max messages the object sends out
its rightmost outlet in response (see What Are Attributes? for more details).
Automatically querying the jit.qt.movie object.

The middle of the tutorial patch contains a Max route object connected to the right outlet of the jit.qt.movie object in our
patch. Jitter attributes are always output by objects in the same format that you would set them with in your patch: the
name of the attribute followed by whatever information the object needs to set that attribute.

When you tell a jit.qt.movie to open a movie for playback (by sending it the read message), the object sends a message out
its right outlet to tell you that it has found your movie and understood how to play it. If you were to connect a print object to
the right outlet of the jit.qt.movie in the patch and reload the movie in the patch, you would see the following printed in the
Max window:

read crashtest.mov 1

If for some reason the object can't locate the crashtest.mov file, you will see a number other than 1 after the name of the file.
This message has two purposes: first, to let you know that the movie file has been successfully located and opened; second,
so that you can use this message to trigger subsequent actions in the Max patch.

If we look at the first argument to the route object, you will see that we've told it to look for a message that begins with read.
The rest of that message is sent to an unpack object which splits up the remaining list of a symbol (containing the name of
the movie) and a number, which indicates success (1) or failure (-1) in opening the movie. The select object then sends out
a bang message if the movie is opened successfully. The bang then triggers the message box above it, which is in turn
connected back to the jit.qt.movie object.
The message box contains the following list of attribute queries, which are parsed by the same route object that dealt with
the read message described above: getfps, gettimescale, fps, timescale, duration, rate, and vol. We don't know what
those mean yet, but we now have a mechanism by which we can get these attributes every time we successfully load in a new
movie into the jit.qt.movie object.

Starting, Stopping, and Slowing Down

Some simple movie playback controls

The top of the tutorial patch contains some controls to change the playback behavior of the jit.qt.movie object. Sending a
stop message to jit.qt.movie will freeze the movie's playback at the current point in the movie. Sending a start message will
resume playback where you last left off. Any soundtrack that exists in the movie file will stop playing when the movie's
playback is halted. Stopping and starting the movie has no effect on the jit.qt.movie object's matrix output, which is still
controlled by the metro object. If you stop the movie with the metro on, you will still receive a new matrix at the rate of the
metro object (in this case, 25 times per second), even though all the matrices will be the same.

Changing the rate of the movie will change the speed at which it plays back its video and audio content. Positive rate values
will make the movie go forward, with a value of 1 signifying normal playback speed. Negative values will make the movie go
backwards. A rate of 0 will stop the movie. The jit.qt.movie object takes a floating-point number as the argument to its rate
attribute, so a value of 0.5 will make the movie play at half speed, and a value of -2.3 will make the movie play backwards
at a bit more than double speed. If you play around with this value, you will note that the soundtrack will speed up, slow
down, and play backwards to remain in sync with the video. Once the movie reaches its last frame (or first frame, if you're
playing it backwards), it will loop to the opposite end of the file. This behavior can be changed by setting the loop attribute
of the jit.qt.movie object with a value of 0 (no looping), 1 (regular looping), or 2 (palindrome looping).
The vol attribute controls the volume (loudness) of any soundtrack component the movie has. A value of 1 equals full
volume, and a value of 0 will turn the sound off.

In this patch, both the rate and the vol attributes are initialized by the message box in the middle of the patch when the
film is loaded. This way they will reflect the values stored in each new QuickTime movie (see below).

Time is on My Side
When a jit.qt.movie object opens a new movie, it reads in a lot of information (contained in the movie's header) about the
movie, including how long it is, how many frames of video are in the movie, and how fast it is meant to be played. We use
this metadata to control the movie's playback.

Important note: unlike many Jitter attributes, which are set either by you or the object itself, many attributes used by
jit.qt.movie are dependent on the current movie file. Different movie files will generate different settings for many of
the attributes discussed in this tutorial.

The first three attributes we queried, duration, timescale, and fps, tell us about how the movie file deals with timing. The
duration attribute tells us the total length of the movie. This value is not expressed in milliseconds or frames, but in
QuickTime time units. The actual length of each time unit depends on the timescale of the movie. The movie's timescale is
the timing resolution of the movie per second. Dividing the duration of a movie by its timescale will tell you the
approximate length of the movie, in seconds. Our crashtest.mov file, for example, has a duration of 2836 time units and a
timescale of 600. The movie should run for about 4.73 seconds. If we want to move two seconds into the movie, we could
set the jit.qt.movie object the messagetime 1200 (1200 time units divided by a timescale of 600 units/second gives us 2
seconds).

The fps, or frames per second, of a movie tells us how many individual video images exist in the movie every second. The
higher the fps of a movie, the smoother the apparent motion of the movie will be (assuming, that is, that the individual
frames are all in some way unique). Some common fps rates are 15, 24, 29.97, and 30. Our movie file in this example runs
at 15 frames per second, which works out to a new frame of video every 40 time units, or about every 66.7 milliseconds. If we
divide the duration of crashtest.mov by the number of time units per frame in the movie, we can determine that the movie
file has 70 frames. If we wanted to, we could get the total number of frames in the movie by querying the jit.qt.movie object
with the getframecount message, but then we wouldn't get to do the fun math!

Scrubbing and Looping

Displaying and setting the current playback frame

The area at the bottom of the patch contains two controls for further manipulating the movie's playback. The number box on
the left displays the frame that the movie is currently playing. This value is being updated by the gettime message sent into
the jit.qt.movie object by the metro object at the top of the patch; each time a new frame is output the time is updated. If
you stop the movie's transport (by sending jit.qt.movie a stop message), you can "scrub" through the movie by dragging on
the number box. The movie will jump to the frame specified as an argument to the frame message.

Setting loop points in a movie

Loop points (pairs of time values which specify the beginning and end of a loop) can be sent to a jit.qt.movie object by
setting the looppoints attribute with two integer arguments. The rslider in the tutorial patch lets you select regions of the
movie that the jit.qt.movie object will loop between. The size of the rslider has been set to the duration of the movie
through the attribute query we performed when the movie was loaded. You can reset loop points by sending jit.qt.movie a
looppoints message with no arguments (an example of this is at the top of the patch, along with a query message that
highlights the entire rslider).

Summary
The jit.qt.movie object offers a number of simple attributes that allow you to change the way QuickTime content is played.
You can stop and start movie playback with those messages. The rate attribute lets you change the speed and direction of
movie playback. You can control the volume of a movie's soundtrack with the vol attribute.

You can get important information about the current movie loaded into the jit.qt.movie object by querying attributes such
as duration, timescale, and fps. You can go to specific frames in a movie with the frame message, and you can set and
retrieve looppoints for the movie. You can query the current time position of a movie by sending jit.qt.movie a gettime
message.

More powerful functions, such as editing and saving movies, can be accomplished and will be discussed in later tutorials.

See Also
Name Description
jit.qt.movie Play or edit a QuickTime movie
metro Output a bang message at regular intervals
pack Create a list
route Select outlet based on input matching
unpack Break a list into individual messages
ARGB Color
Tutorial 5: ARGB Color
Color in Jitter
In this chapter we'l l discuss how color is handled in Jitter. We'll focus on the numerical representation of a color, and
conversely the visualization of numbers as color. A thorough discussion of color theoryknowledge of how light and matter
produce our sensation of coloris well beyond the scope of this tutorial, as is a discussion of the many ways to represent
color information digitally. If you wish to learn more about color theory and/or digital representations of color, you can find
some other sources of information listed in the Bibliography.

Here we present one method of representing color and how that representation is handled in Jitter matrices.

Color Components: RGB


It's possible to produce any desired color by blending three colors of lightred, green, and blueeach with its own intensity.
This is known as additive synthesisgenerating a color by adding unique amounts of three "primary" colors of light. (The
opposite of this is subtractive synthesis: mixing colored pigments, such as paint, which absorb certain colors of light and
reflect the rest.) Thus, we can describe any colored light in terms of its intensity at the three frequencies that correspond to
the specific colors red, green, and blue.

In Jitter, this is the most common way to describe a color: as a combination of exact intensities of red, green, and blue. For
each pixel of an imagebe it a video, a picture, or any other 2D matrixwe need at least three values, one for each of the
three basic colors. Therefore, for onscreen color images, we most commonly use a 2D matrix with at least three planes.

The Alpha Channel


A fourth plane is often useful for what is known as the alpha channela channel that stores information about how
transparent a pixel should be when overlaid on another image. We won't deal with the alpha channel specifically in this
tutorial chapter, but we mention it here because its inclusion is standard in most Jitter objects that deal specifically with
representations of color. In most cases, the alpha channel is stored in the first plane (which is plane 0, because planes of a
matrix are numbered starting from 0), and the RGB values are in planes 1, 2, and 3.

Color Data: char, long, or float


It's fairly standard in computer applications to use 8 bits of information per basic color value. 8 bits gives us the ability to
express 256 (2 to the 8th power) different values. This means that if we use 8 bits for red, 8 for green, and 8 for blue, we can
express 16,777,216 (2 24) different colors. That's a sufficient variety of colors to cover pretty thoroughly all the gradations
we're able to distinguish.

So, if we only need 8 bits of resolution to represent each basic color value, that means that the 8-bit char data type is
sufficient to represent the value in each plane of a four-plane matrix of color information. We could use the long, float32, or
float64 data type, and Jitter will certainly let us do that, but we'd be using much larger data types than we really need. Since
a full-frame video image can contain a very large number of pixels (a 640x480 image has 307,200 pixels), it often makes
most sensein order to conserve memory and speed up processingto use the char data type.

When a matrix contains 8-bit char data, we can think of those 8 bits as representing numbers from 0 to 255, or we can think
of them as representing gradations between 0 and 1 (i.e. as a fixed-point fractional number). When a Jitter object containing
char data receives numerical values from other Max objects, it usually expects to receive them in the form of floats in the
range 0 to 1. It will make the internal calculations necessary to convert a float from Max into the proper char value. (There
are a few exceptions to this rule. For example the jit.op object can accept either floats in the range 0-1 or ints in the range
0-255 in its right inlet, as demonstrated in Tutorial 3.) For more on the use of the char data type in Jitter matrices, see the
manual chapter "What's a Matrix?".

Isolating Planes of a Matrix


Open the tutorial.

At the top of the patch you are given two different colorful source materials. One is a video of an arcade game, and the other
is the standard set of color bars for used for video calibration. You can choose to see one or the other by turning on the one
of the metro objects (to repeatedly bang the object containing the matrix you want to see).
View a video or a still image

Click on the toggle marked "Show movie" above the metro30 object to view the video.
This example patch breaks up a 4-plane matrix of color information into four 1-plane matrices, in order to allow you to see
and modifyeach plane individually. We achieve this with an object called jit.unpack. Just as the Max object unpack
breaks a list into individual numbers, jit.unpack breaks a multi-plane matrix into individual 1-plane matrices. You can type
in an argument to tell jit.unpack how many planes to expect in the incoming matrix, but by default it expects four planes
since that's the norm for color data. We're interested in seeing the contents of the red, green, and blue planes, so we send
planes 1, 2 and 3 to individual jit.pwindow objects. In this case we're not interested in the alpha channel, so we don't bother
to display plane 0.

Unpacking a multi-plane matrix as single-plane matrices

Here you can see the content of each color plane, in the form of three monochrome images. The lighter pixels indicate higher
values for that color. By sending each matrix to a jit.op object, we obtain individual control over the strength of each color,
and can alter the color balance. We then send the individual (altered) matrices to a jit.pack object to recombine them as a 4-
plane matrix, for display in the jit.pwindow.
Try, for example, reducing the intensity of green and blue to 0.12, to create a redder image.

Reducing the intensity of certain colors to alter the color balance

Color Rotation
To demonstrate another color trick, we've sent each color plane through a gate object, so that each matrix can be routed to a
different inlet (color plane) of jit.pack. In this way, the meaning of each plane can be reassigned, and we can try all the
permutations of possible color assignments by choosing a setting from the coll object on the left side of the patch.
Drag on the number box marked "Rotate RGB planes" to try different reassignments of the three color planes. (Note that
plane 0 is sent directly through from jit.unpack to jit.pack; it's the jit_matrix message coming in the left inlet of jit.pack
that triggers output of the matrix to the jit.pwindow.) If you choose item 3 in the coll, you get the result shown below.

The individual color planes are reassigned; the red and green planes are swapped here.

The example above shows the original green and blue planes reduced by a factor of 0.12, and the gates are set so that the
red and green planes are swapped when they're sent to jit.pack, resulting in an image with more green in it. The coll object
contains all the possible permutations of assignments of the RGB planes.

Double-click on the coll object to see its contents.


0, 0 0 0;

1, 1 2 3;

2, 1 3 2;

3, 2 1 3;

4, 2 3 1;

5, 3 1 2;

6, 3 2 1;

Permutations of RGB plane assignments

The elements in the list coming out of the coll are unpacked and sent to assign the outlets of the three gate objects. The
number sent into coll is also sent to a umenu (in Label mode) to show the color rotation in wordsin this case "Green-Red-
Blue".

Automated Color Changes


For one more exercise in color modification, we've made an automated process for continually changing the scaling and
rotation of colors.

Click on the toggle marked "Automate color changes". The scaling factors for the three color planes all change continually.
Double-click on the patchercolorgames object to see the contents of the subpatch.
[colorgames] subpatch

The subpatch uses line objects to send values that progress from 0.5 to 1 for each of the color scaling factors. The red factor
changes over the course of 3 seconds, green in 4 seconds, and blue every 5 seconds. (The three line objects thus come into
sync once every 60 seconds.) Every 60 seconds, a new color rotation is selected by the metro-counter combination.
Close the [colorgames] subpatch window. You can try all of these same color modifications on different source material.
Click on the toggle marked "Show movie" to stop the metro. (Note that we also use this toggle to start and stop the movie
playing in the jit.qt.movie object. There's no reason to keep the movie playing if we're not even watching it.) Now click on
the toggle marked "Show colorbars" to display the colorbars. Experiment with changing the scaling factors and rotation on
this image.

Summary
When a jit.window or jit.pwindow receives a single-plane 2D matrix, it displays the values as a monochrome (greyscale)
image. When it receives a 4-plane 2D matrix, it interprets the planes as alpha, red, green, and blue values, and displays the
resulting colors accordingly. This ARGB representation in a 4-plane matrix is the most common way of representing colors
in Jitter.

Because each of the basic colors only requires 8 bits of precision to represent its full range, it's common in Jitter to use the
char data type for color data. Thus, most of the QuickTime-related objects (such as jit.qt.movie) and many of the objects
specifically designed for manipulating colors (such as jit.brcosa and jit.colorspace, which are demonstrated in later tutorial
chapters) expect to receive 4-plane 2D matrices of char data. (Many other objects adapt readily to other types of data,
though. Check the reference documentation for the object in question when you're in doubt.) You can think of the char data
as representing values 0 to 255, or you can think of them as representing fractional values from 0 to 1. Most of the time,
objects that contain char data expect to receive numerical values from other Max objects specified as floats in the range 0 to
1.

The jit.unpack object splits a multi-plane matrix into individual single-plane matrices. The jit.pack object combines single-
plane matrices into a single multi-plane matrix. By treating each plane spearately, you can control the color balance of an
image, or even reassign the meaning of the individual planes.

See Also
Name Description
coll Store and edit a collection of data
counter Keep count based on bang messages
jit.matrix The Jitter Matrix!
jit.op Apply binary or unary operators
jit.pack Make a multiplane matrix out of single plane matrices
jit.pwindow Show data in a patcher
jit.qt.movie Play or edit a QuickTime movie
jit.unpack Make multiple single plane matrices out of a multiplane matrix
line Generate timed ramp
metro Output a bang message at regular intervals
Adjust Color Levels
Tutorial 6: Adjust Color Levels
jit.scalebias
This tutorial elaborates on the color discussion of the previous chapter, and introduces an object that is specially designed
for modifying the ARGB color planes of a matrix: jit.scalebias.
The term scale in this instance refers to the process of scaling values by a certain factor; that is, multiplying them by a given
amount. The term bias refers to offsetting values by adding an amount to them. By combining the processes of
multiplication and addition, you can achieve a linear mapping of input values to output values.

Because jit.scalebias is concerned with modifying ARGB color information in an image, it handles only 4-plane matrices of
the char data type. (See Tutorial 5 for a discussion of ARGB color and char data.)

Math with char data


As mentioned in the previous chapter, 8-bit char data can be represented as whole number values from 0 to 255 or as
fractional values from 0 to 1. In Tutorial 2, for example, we saw that the jit.print object reports char data as integer values
from 0 to 255. However, in many cases where we modify char values within a matrix (by changing one of its attributes), the
Jitter object will expect to receive the attribute value as a float. Because this can be a little confusing, we've provided a
demonstration in this tutorial patch.

Open the tutorial patch 06jAdjustColorLevels in the Jitter Tutorial folder. Click on the patcher explain_scalebias object
in the middle of the patch to see the contents of the subpatch [explain_scalebias].

A demonstration of float math on char data.

In the above example, we have created a very small matrix. It has 4 planes of char data, but it has only a single cell. This will
to allow us focus on what happens to a single numerical value in the matrix. You can see that we have set the value in plane
2 (the green plane) to 100. At the left side of the example, you can see how this whole number value would be represented
as a fractional value between 0 and 1: in this case it's 0.392, which is 100/255 of the way from 0 to 1.

The jit.scalebias object will multiply the values by a certain amountspecified by the scale attributeand then will add a
certain amount to the valuesspecified by the bias attribute. When that matrix is altered by the jit.scalebias object, all of
the values will be treated as floats for purposes of calculation, then will be re-stored in the matrix as char data.

The scale and bias attributes are set here with the scale 2.0 and bias 0.2 messages. The scaling factor (the multiplier)is 2.0
in this case, and the bias (the offset that gets added afterward) is 0.2. So, to understand what is going on inside jit.scalebias,
we have to think of the green value as 0.392 times 2.0 plus 0.2, which equals 0.984. The jit.iter object reports the values in
each plane of each cell (there's only one cell in this matrix), and we can see that the value (when stored in the matrix as a
char) is 251 (or 0.984 on a scale from 0 to 1).

(Just as a mental exercise, can you calculate the values jit.scalebias will produce in the red and blue planes in the above
example? Since the values in those planes in the original matrix are 0, the values in the resultant matrix will be 0 times 2.0
plus 0.2, which equals 0.2, which is equal to 51 on a scale from 0 to 255. So the RGB values being displayed by the
jit.pwindow object at the bottom are 51 251 51.)

data
If the preceding explanation was crystal clear to you, you might want to skip over these additional examples. But in case
you're still not totally clear on how math operations with char data (and jit.scalebias in particular) work, here are a few
more examples.

One by one, click on each of the presets in the preset object, proceeding from left to right. In the paragraphs below we
explain each of the preset examples.

1. The value in the green plane of the original matrix is 255. (This is equal to 1.0 on a scale from 0 to 1.) The jit.scalebias
object multiplies this by 0.5, which results in an internal value of 127.5; however, when storing the value as a char,
jit.scalebias truncates (chops off) the fractional part, and stores the value as 127.

This yields a rather imprecise result. (127 on a scale from 0 to 255 is equal to 0.498 on a scale from 0 to 1, as opposed
to the 0.5 we would expect.) But that's the best we can do with 8-bit char data. In cases where you need greater
precision than that, char data is not for you. You would need to use a matrix of long, float32, or float64 data, and use
jit.op@op * and jit.op@op + objects instead.

2. The original value is 100, and we double it (scaling factor 2.0) and get the expected result of 200. There is no loss of
precision in this case. 3. The original value is 100 (0.392). We scale it by a factor of 1.0, which leaves it unchanged, then we
add -0.2 to itthat is, we subtract 0.2 from itto get a result of 49 (that is, 0.192). 4. 0.392 times 2.0 plus 0.2 = 0.984. On a
scale from 0 to 255, that's 251. 5. This example and the next one show what happens when the result of the multiplication
and addition operations exceeds the capacity of an 8-bit char. jit.scalebias will simply clip (limit) the result to the
maximum or minimum limit of a char. Here, 0.392 times 4.0 equals 1.568 (that is, 100 times 4 equals 400), so the result is
set to the maximum allowable, 255. 6. In the other direction, 0.392 minus 0.5 equals -0.108, so the result is set to 0. 7. It's
noteworthy that these imprecisions and limits only occur at the point when the result is re-stored as a char. Up until then,
the values are calculated internally as floats, so the precision is retained. Even though the multiplication takes the internal
value beyond the 0-1 range, no limiting occurs internally, and the addition operation can bring it back into range. Here,
0.392 times 3.0 (= 1.176) minus 0.5 equals 0.676. When this is stored as a char, however, a small imprecision occurs. 0.676
on a scale from 0 to 255 equals 172.38, but the fractional part is truncated and the stored value is 172 (i.e., 0.675). 8. For no
change, the scaling factor should be 1 and the bias offset should be 0.
Try some more values yourself, until you're satisfied that you understand jit.scalebias and the results that occur with 8-bit
char data. When you have finished, close the [explain_scalebias] window.

Adjust Color Levels of Images


Now let's apply jit.scalebias to color images. In the top left corner of the tutorial patch, you can see a familiar configuration:
a jit.qt.movie object with a read message box to load in a movie and a metro object to trigger jit_matrix messages from
jit.qt.movie. In this patch we'll modify the matrices with multiplications and additions in jit.scalebias.

Load in a picture or a movie.

Click on the message box read chilis.jpg to read in a JPEG picture. Note that we're reading a still imagenot a video
into the jit.qt.movie object. QuickTime can handle a wide variety of media formats, including still images in PICT or JPEG
format. jit.qt.movie treats still images just as if they were 1-frame-long videos.
The output of jit.qt.movie will go to jit.scalebias for processing, and will then be displayed in the jit.pwindow. (You can
ignore the jit.matrix object for now. We'll discuss its use later in this chapter.) The scale and bias values can be changed by
modifying the scale and bias attributes of jit.scalebias.
Click on the toggle to start the metro. Try dragging on the number box above the scale $1 message box, to increase the
value of the scale attribute to 1.25.
Boost the brightness of the image; with scale , higher values get boosted more.

This will increase all non-zero values in all four planes of the image by a factor of 1.25 (a 25% increase). Note that
multiplication has the effect of increasing larger values by a greater amount than smaller values. For example, if the red
value of a particular cell in the original matrix is 200, it will be increased to 250 (a net increase of 50), while the blue value
of the same cell might be 30 and would be increased to 37 (a net increase of 7).

Try increasing the scale attribute to a very large value, such as 20. Values that were 13 or greater in the original matrix will
be pushed to the maximum of 255 (and even the very small values will be increased to a visible level), creating an artificially
"overexposed" look.

Try decreasing the scale attribute to a value between 0 and 1. As you would expect, this darkens the image. A scale value of
0 or less will set all values to 0.

Return the scale attribute to 1. Now try adjusting the bias attribute. This adds a constant amount to all values in the
matrix. Positive values lighten the image, and negative values darken it.

Boost (or reduce) the level of all values by a constant amount.

Here are a couple of more extreme scale and bias settings you might want to try. Set the scale value to 40 and the bias
value to -20. This has the effect of pushing almost all values to either 255 or 0, leaving only a few colors other than white or
black. Now try setting the scale value to -1 and the bias value to 1. This has the effect of inverting the color scheme by
making all high values low and all low values high. Reducing the scale value even further (to, say, -4 or -8) creates a similar
inversion, but only values that were low in the original will be boosted back into the 0-1 range by the positive bias value.

Adjust planes individually


You can adjust the levels in each plane individually in jit.scalebias, using the attributes ascale, abias, rscale, rbias, etc.
Set the scale value back to 1 and the bias value back to 0. Then experiment with adjusting each color plane independently
by providing new values for the appropriate attributes.

Adjust levels for each color plane

We've made the process a bit more "interactive" by giving you a controller that lets you adjust the scaling of all three color
planes at once. When you click or drag in the swatch object, it sends out a three-item list representing the RGB color values
at the point where your mouse is located. Those values are expressed on a scale from 0 to 255, so we use the vexpr object to
change all values in the list to the 0 to 1 range. We then use unpack to break that list into three separate floats, and we use
those values to alter the rscale, gscale, and bscale attributes of jit.scalebias.
Values from swatch used as attribute values for jit.scalebias

Drag on the swatch object to scale the RGB planes all at the same time. (Since this produces scaling values in the range 0
to 1, you're effectively reducing all the levels, so this will generally darken the resulting image somewhat.)

You can try all of these operations on different images. Read in some other colorful images such as colorswatch.pict or
wheel.mov (or any other image) and experiment with adjusting the color levels.

Reassign planes of a matrix


In the previous tutorial we used jit.unpack and jit.pack to reassign the planes of a matrix. There is another way to do that,
using the planemap attribute of the jit.matrix object. In this example, we pass the matrix output of jit.qt.movie through a
jit.matrix object just so that we can demonstrate the planemap attribute.

We can reassign the planes of a matrix as it goes through jit.matrix

The planemap attibute of jit.matrix allows us to "map" (assign) any plane of the incoming matrix to any plane of the
outgoing matrix. The word planemap is followed by as many numbers as there are planes in the matrix (four in this case).
Each place in the list stands for an output plane (the first place stands for output plane 0, the second place for output plane
1, etc.), and the value of that number states the input plane that will be assigned to it. By default, the planemap values are 0
1 2 3 (etc.), so that each plane in the input matrix is assigned to the same plane in the output matrix. But we can change
those assignments as we like. For example, if we send jit.matrix the message planemap 0 3 2 1, we are assigning input
plane 3 to output plane 1 (since the value 3 is in the list location for output plane 1), and input plane 1 to output plane 3.
Effectively, we're swapping the red and blue color planes of the image.

Click on the message box read wheel.mov and start the metro to display the movie. (Set the scale attribute of
jit.scalebias to 1 and the bias attribute to 0, so that you're seeing an unaltered image in the jit.pwindow.) Now, in the
bottom right portion of the patch, click on the message box planemap 0 3 2 1 to swap the red and blue planes in the
matrix. Click on the message box planemap 0 1 2 3 to go back to the normal plane mapping.
If we set all three of the RGB output planes to the same input plane, we get equal values in all three RGB planes, resulting in
a greyscale image.

Click on the message box planemap 0 1 1 1 to see this effect. The value 1 is in the list location for each of the three RGB
planes, so the red plane of the original is used for all three RGB planes of the output matrix.

To rotate through all of the different color plane rotations, we've filled a coll object with various plane mappings (similarly to
the way we did in the previous chapter), and we will send those assignments to the jit.matrix to change the settings of its
planemap attribute.

Double-click on the patcher rotatecolorplanes object to see the contents of the subpatch. It simply counts from 1 to 6, to
step through the different mappings stored in the coll object in the main patch. (And when it's turned off it sends out the
number 1 to reset to the default plane mapping.) Close the [rotatecolorplanes] window.

Click on the toggle above the patcher rotatecolorplanes object to step through the different plane mappings at the rate
of one setting per second. Change the rate number box above the right inlet to a smaller value (say, 80) to see a flickering
effect from rapid plane reassignment.

In the next tutorial chapter, you'll see how to rotate image hue in a subtler way, using jit.hue, and you'll see other ways to
adjust color levels with the jit.brcosa object.

Reading and Importing Images


In this tutorial patch, we loaded three different kinds of images into the jit.qt.movie object: PICT and JPEG still images, and
a QuickTime movie. It may seem a little strange to read still images into an object made for playing movies, but in fact
QuickTime can read many types of media files, and jit.qt.movie knows how to read them all. (You could even read an AIFF
audio file into jit.qt.movie, listen to it with start and stop messages, jump to different locations with the time attribute,
etc.! Of course, you won't see any visual matrix info in that case.)

For still images, it's just as easy to load them directly into a jit.matrix object with the importmovie message, as
demonstrated in Tutorial 3. If you import a QuickTime movie that way, only one frame of the movie will be stored in the
jit.matrix.

In this patch, we used jit.qt.movie to load in all the images. The first reason is because one of the things we wanted to load
was a movie (not just one frame of the movie). The second reason is because we wanted to demonstrate the planemap
attribute of jit.matrix. The planemap attribute is only appropriate if there is an actual input matrix (a jit_matrix message
coming in the left inlet). If we imported the images directly into jit.matrix with importmovie, the planemap attribute
would have no effect.

Summary
The jit.scalebias object uses multiplication and addition to modify all the values in a particular plane of a 4-plane char
matrixor all planes at the same time. The scale attribute is a factor by which each value in the matrix will be multiplied;
the bias attribute is an amount to be added to each value after the multiplication takes place. The scale and bias attributes
affect all four planes of the matrix. To affect only one plane at a time, use the attributes for that particular plane, such as
ascale, abias, rscale, rbias, etc.

You must supply the values for these attributes as floats (numbers containing a decimal point). To perform the
multiplication and addition operations, jit.scalebias treats the char values as fractional values in the range 0 to 1, performs
the math with floats, then converts the results back to chars (whole numbers from 0 to 255) when re-storing them. Results
that exceed the range 0 to 1 will be limited to 0 or 1 before being converted back to char.

You can reassign planes of a matrix using the planemap attribute of jit.matrix. The arguments to planemap are the output
planes listed in order, and the values in the list are the input planes to be assigned to each output plane. So, for example to
assign the plane 1 of an input matrix to all four planes of the output matrix, the attribute setting should be planemap 1 1 1
1.
jit.scalebias provides a powerful tool for adjusting color levels in a 4-plane char (ARGB color) matrix. More such tools are
presented in the next tutorial chapter.

See Also
Name Description
jit.iter Iterate a matrix as lists or values
jit.matrix The Jitter Matrix!
jit.pwindow Show data in a patcher
jit.qt.movie Play or edit a QuickTime movie
jit.scalebias Multiply and add
metro Output a bang message at regular intervals
preset Store and recall settings
swatch Select and display RGB colors
vexpr Evaluate a math expression for a list
Image Level Adjustment
Tutorial 7: Image Level Adjustment
This tutorial shows how to adjust levels of brightness, contrast, and saturation in Jitter matrices that contain image data. We
will also look at the concept of hue and hue rotation.
Open the tutorial.

The tutorial patch has two new objects in it: jit.brcosa, which allows you to control brightness, contrast, and saturation of an
image stored in a Jitter matrix, and jit.hue, which lets you rotate the hue of an image:

Open and view the image.

Open the file colorwheel.pct by clicking the message box that says read colorwheel.pct. View the movie by clicking the
toggle box to start the metro.

You should see a color wheel appear in the jit.pwindow at the bottom of the patch:

The Color Wheel of Fortune

The jit.pwindow object shows us the image after it has passed through our two new objects. We'll talk about jit.brcosa first,
and then get to jit.hue.

Brightness, Contrast, and Saturation


The jit.brcosa object takes a 4-plane char Jitter matrix and, treating it as ARGB image data, allows you to alter the
brightness, contrast, and saturation of the processed matrix. The three attributes are called, not surprisingly, brightness,
contrast, and saturation. The default values of 1.0 for the three attributes result in the matrix passing out of the object
unchanged:

Using the jit.brcosa object

Change the attributes of the jit.brcosa object and observe how the output matrix changes.
The brightness of an image refers to its overall lightness or darkness when compared to a reference color (usually black).
Changing the brightness attribute is equivalent to multiplying the values in the matrix by that value. A brightness value of
0 will turn the image to black; values above 1.0 will gradually increase all non-0 cell values until they clip at white (255). A
value of 0.5 will significantly darken the image, reducing its natural range of 0-255 to 0-127. Some brightness values are
shown below on the color wheel:
The color wheel with brightness values of 0.5 , 1.5 , and 10 , respectively

Note that cell values clip at 0 and 255 when altered in this way. This is why the rightmost image, with a brightness of 10, is
mostly white, with color showing only in areas where one or more of the visible color planes (RGB, or planes 1, 2, and 3) are
0 in the original matrix.

Image contrast can be expressed as the amount the colors in an image deviate from the average luminosity of the entire
original image (see below). As the contrast attribute of jit.brcosa is increased above 1.0, cell values above the average
luminosity of the entire matrix are lightened (increased), and values below the average are darkened (decreased). The result
is a dynamic expansion of the matrix image so that light values get lighter and dark values get darker. Settings for contrast
below 1.0 reverse the process, with darker tones getting lighter and lighter tones getting darker until, at a contrast value of
0.0, you only retain the average grey luminosity of the entire image. Negative values invert the color of the image with the
same amount of overall contrast.

Technical Detail: The average luminosity of a matrix can be computed by averaging the values of all the cells in the
matrix, keeping the planes separate (so you get individual averages for Alpha, Red, Green, and Blue). The three visible
planes are then multiplied by the formula:

L = .299*Red + .587*Green + .114*Blue

The value L will give you the average luminance of the entire matrix, and is used by jit.brcosa to determine the
threshold value to expand from when adjusting contrast.

Here are some example contrast settings:

The color wheel with contrast settings of 0.3 , 2 , -1 , and 100

The first example shows the color wheel with its contrast drastically reduced (the cell values are all close the average
luminosity of the matrix). The second example shows an increased contrast. Note how the lighter shades in the middle of
the color wheel begin to approach white. The third example shows a negative contrast setting. The colors are inverted from
the original, but the average luminosity of the matrix is the same as in the original. The last example shows the result of a
massive contrast boost. Cell values in this example are polarized to 0 or 255.

Image saturation reflects the ratio of the dominant color in a cell to the less dominant colors in that cell. As saturation
values decrease below 1.0, all color values in a cell will become more similar and thus de-saturate towards grayscale. Values
above 1.0 will push the colors farther away from one another, exaggerating the dominant color of the cell. As with contrast,
a negative value for the saturation attribute will invert the colors but retain the same luminosity relationship to the original.
The color wheel with saturation values of 0.2, 2 and -1

The first image is de-saturated, so each cell value in the matrix is being drawn toward the value of the luminosity of that cell.
The second image is over-saturated, so the individual colors are much brighter (or darker) than their originals. The third
image maintains the original luminosity of the color wheel but inverts the colors.

Hue and Cry


The jit.hue object allows you to rotate the hue of the input matrix. Setting the hue_angle attribute rotates the hue of the
input matrix a specified amount in degrees:

The hue_angle attribute rotates the hue of the input matrix.

The hue of a matrix cell can be thought of as its basic color (e.g. magenta). Image hue is visualized as a rainbow (or a color
wheel like the one we've been using) which goes from red to green to blue and back to red again. This value (which is
specified in degrees from 0-360), along with the saturation and lightness of the image, can be used to describe a unique
color, much in the same way that a specific series of RGB values also describe a unique color. By rotating the hue of an image
forward, we shift the red part of the color spectrum so that it appears green, the green part of the spectrum to blue, and the
blue part to red. A negative hue rotation shifts red into blue, etc. Hue rotations in increments of 120 degrees will transpose
an image exactly one (or more) color planes off from the original hue of the image.

Technical Detail: Our eyes perceive color through specialized receptors in our retina called cones (another type of
receptor exists that responds to low levels of light but doesn't distinguish colorthese receptors are called rods). Cones
in our eyes are differentiated by the wavelength of light they respond to, and fall into three categories: L-sensitive
receptors which respond to long wavelength light (red), M-sensitive receptors which respond to medium wavelength
light (green), and S-sensitive receptors which respond to short wavelength light (blue). Just as our auditory system is
weighted to be more perceptive to frequencies that are within the range of human speech, the distribution of cones in
our eyes is weighted towards the middle wavelengths which are most crucial to perceiving our environment. As a result,
we have roughly twice as many green receptors in our eyes as the other two colors. This explains why the luminance
formula (above) allocates almos t 60% of perceived luminosity to the amount of green in an image. Camera technology
has been developed to emulate the physiology of our eyes, so cameras (and film) are also more sensitive to green light
than other colors.

Click the toggle box to automate the hue_angle of the color wheel. Note that when the hue_angle reaches 360 degrees,
the original matrix image is restored.

Our color wheel at various hue rotations (0-360 degrees)


Summary
The jit.brcosa and jit.hue objects allow you to modify the brightness, contrast, saturation, and hue of an input matrix. You
use the two objects to perform tasks such as dynamic level adjustment (e.g. autoexposure), color correction, or idiosyncratic
hue displacement.

See Also
Name Description
jit.brcosa Adjust image brightness/contrast/saturation
jit.hue Rotate hue
jit.pwindow Show data in a patcher
jit.qt.movie Play or edit a QuickTime movie
metro Output a bang message at regular intervals
Simple Mixing
Tutorial 8: Simple Mixing
Mixing Two Video Sources
One of the most common and useful things to do with video is to mix two images together.

The simplest form of video mixing is achieved by just adding the two images together, with the intensity of each of the two
images adjusted in whatever proportion you desire. By fading one image up in intensity while fading the other down, you can
create a smooth crossfade from one image to the other.

Jitter provides an object that accomplishes mixing and crossfading for you, called jit.xfade.

Technical Detail: This type of mixing involves adding each value in one matrix to the corresponding value in the other
matrixcell-by-cell and plane-by-planeand outputting a matrix that contains all the sums. If we just did that,
however, we would get an output image in which all the values are greater than in either of the input images, so the
result would be lighter than the originals (and some of the values might even clip at 255 if the matrices contain char
data). Therefore, it's normal to scale down the intensity of one or both of the images before adding them together. For
example, to get an equal mix of the two images, we would scale them both down by an equal amount (say, by a factor of
0.5) before adding them.

jit.xfade
The jit.xfade object takes a matrix in each of its two inlets, scales the values of each matrix by a certain amount, adds the
two matrices together, and sends out a matrix that contains the resulting mix. The scaling factor for each of the two input
matrices is determined by the object's xfade attribute. The xfade value is a single (float) number between 1 and 0. That
value determines the scaling factor for the matrix coming in the right inlet. The matrix coming in the left inlet is scaled by a
factor of 1-xfade. So, if you gradually increase the xfade value from 0 to 1, the output matrix will crossfade from the left
input to the right input.

Open the tutorial patch 08jSimpleMixing in the Jitter Tutorial folder. Two source videos are read in automatically by the
loadbang object. Start the metro. You'll see only the left video at first. Drag on the slider to change the xfade value, which
will give you a mix of the left and right matrices.

A value of 0.5 gives an equal mix of left and right matrices

Automated Crossfade
A crossfade is one of the most common ways of making a transition from one image to another. It might be very gradual
over the course of several secondsor it might be quite rapid, lasting a fraction of a second, to make a sudden transition that
is slightly smoother than a jump cut.

In the upper left portion of the patch, we've made an automated fader from video A to video B (or vice versa). The crossfade
can take any amount of time; you can specify the transition time with the number box.
Automated process to send a continuously changing xfade value

Using the number box, set a slow transition time (say, 5000 ms) so that you can see the effect of the crossfader. Click on
right side of the Go To switch to fade to video B.

The Go To switch is actually a small slider with a range of 2 and a multiplier of 100, so the only two values it can send out
are 0 and 100. Clicking on the right side of the switch sends out the value 100, the pack object sends out the message 100
5000, and the line object sends out continuous values from 0 to 100 (one new value every 50 ms) over the course of five
seconds. Those values are then multiplied by 0.01 to give a smoothly changing xfade value from 0 to 1.

Summary
Adding two matrices together is the simplest way to do A-B mixing of video images. To achieve the desired balance of the
two images, you first scale each matrix by a certain factor. You can crossfade from one image to another by decreasing the
scaling factor of one image from 1 to 0 as you increase the scaling factor of the other image from 0 to 1.

The jit.xfade object makes it easy to mix and/or crossfade two matrices. Its xfade attribute determines the balance between
the two matrices. Changing the xfade value continuously from 0 to 1 performs a smooth A-B crossfade. You can use line or
any other Max timing object to automate crossfades.

See Also
Name Description
jit.xfade Crossfade between 2 matrices
line Generate timed ramp
pack Create a list
prepend Add a message in front of input
slider Move a slider to output values
More Mixing
Tutorial 9: More Mixing
Mixing and Crossfading Made Explicit
In the previous chapter we explained how the jit.xfade object uses scaling (multiplication) and addition to mix two matrices
together in varying proportions. In this tutorial we'll use the jit.scalebias and jit.op objects to perform those mathematical
operations ourselves.

This will provide us with a few advantages. First, it will allow us to demonstrate the mathematics of mixing and crossfading
explicitly. Second, it will allow us to demonstrate how jit.op can perform math operations using two matrices as its inputs.
(In Tutorial 3 we showed jit.op in action with scalar values operating on a single matrix.) Third, it will allow us to specify
balance settings (scaling factors) for the two matrices independently, providing more flexibility than the jit.xfade object.
Finally, because jit.op can implement so many different kinds of math operations, we can try other means of combining
matrices to see different visual effects.

Mixing Revisited
Open the tutorial patch 09jMoreMixing in the Jitter Tutorial folder.

Multiplication and addition to mix /crossfade matrices (replicating jit.xfade )

Here you see each of two different videos being scaled down (darkened) by some factor between 0 and 1 with jit.scalebias.
Below that, you see a slightly new wrinkle in the use of jit.op: the input to both inlets is a matrix. When we do this, jit.op
performs the specified math operation on every single value individually, pairing each value in the left matrix with the
corresponding value in the right matrix. This lets us add all the values in the two matrices, effectively mixing the images.

, values in the right matrix will have their fractional part truncated before calculations are performed.) .
The result of these multiplications and this addition is comparable to what the jit.xfade object performs internally. You can
verify this by using the controls in the top right part of the patchwhich are nearly identical to those of the previous chapter
to crossfade the videos.

Start the metro and use the Mixer slider to perform a crossfade from video A to video B.
Note that we send the crossfade value directly as the scale attribute for the B video, and at the same time we use a !-1
object to scale the A video by 1 minus that value. That way, the sum of the two scaling factors always equals 1, as it does in
jit.xfade.

Combine Matrices Using Other Operators


Addition is perhaps the most obvious operation to perform with two matrices, but it's not the only one possible. By changing
the op attribute of the jit.op object, we can try out many other operations to see what kind of visual effect they create.
Set a very gradual crossfade time in the Transition Time number box (say, 10000 ms). Choose an operator other than +
in the Operator pop-up menu. Now click on the Go To switch to begin the crossfade. You can see how that particular
operator looks when implemented with two video matrices.

The pop-up menu contains a few of the many operators provided by jit.op. Here's a brief description of each operator in the
menu.

+Add the values of B to A.

-mSubtract the values of B from A, then perform a modulo operation to wrap the result back into the desired range.

maxUse whichever value is greater, A or B.


absdiffSubtract the values of B from A, then use the absolute value of that difference.

|"Bitwise Or"; using binary number values, whenever a bit is 1 in either A or B, set it to 1 in the result.

^"Bitwise Exclusive Or"; using binary number values, whenever the bits of A and B are not the same, set that bit to 1 in the
result, otherwise set the bit to 0.

>If the value in A is greater than the value in B, set the result to 1 (or char 255), otherwise set it to 0.

<If the value in A is less than the value in B, set the result to 1 (or char 255), otherwise set it to 0.

>pIf the value in A is greater than the value in B, use the A value in the result, otherwise set it to 0.

<pIf the value in A is less than the value in B, use the A value in the result, otherwise set it to 0.

If you want to see what other operators are available, check the Object Reference documentation for jit.op.
If you'd like, you can drag directly on the number boxes above the jit.scalebias objects, to set the balance levels
independently (i.e. differently from the way our crossfade scheme sets them). You can also try values that exceed the 0 to 1
range.

jit.scalebias vs. jit.op @op *


We chose to use the jit.scalebias object in this patch to perform the scaling multiplications instead of using jit.op with the *
operator. Why? When jit.op is performing operations on char data (as we are doing in this patch), it limits its val attribute
to the range 0.-1. (when specified as a float) or 0-255 (when specified as an int). In cases where we want to multiply char
data by some amount from 0. to 1., jit.op is just fine. But if we want to multiply char data by some other amount, then
jit.scalebias is the correct object to use because it permits scale factors that exceed the 0 to 1 range. jit.scalebias is only for
handling 4-plane char matrices, but that's OK because that's what we're scaling in this example. So, in this patch, since we're
operating on 4-plane char matrices, and since we want you to have the ability to try scaling factors that exceed the 0 to 1
range, we have used jit.scalebias.

Summary
You can use the jit.op object to perform various math operations using the the values from two different matrices. jit.op
performs the specified math operation on every value individually, pairing each value in the left matrix with the
corresponding value in the right matrix. When the dim, planecount, and type attributes of the two matrices differ, jit.op
uses the attributes of the matrix in the left inlet. Different math operators can create a variety of visual effects when used to
combine two video images.

See Also
Name Description
jit.op Apply binary or unary operators
jit.qt.movie Play or edit a QuickTime movie
jit.scalebias Multiply and add
Chromakeying
Tutorial 10: Chromakeying
This tutorial explains how to perform chromakeying with two source movies using the jit.chromakey object. We will also
learn how to find out the color of any pixel on the screen.
Open the tutorial.

When you open the tutorial patch, Max will automatically read two movies (oh.mov and traffic.mov) into two jit.qt.movie
objects by sending appropriate read messages to those objects with a loadbang:

Initializing the patch via loadbang.

Additional parameters we need for this patch are also initialized by the loadbang, which is connected to the message box
on the right of the patch. The message box initializes the rest of the patch by sending messages to named receive objects
elsewhere in the patch (see Tutorial 25: Managing Messages, in the Max4TutorialsAndTopics.pdf).

Click the toggle box to start the metro. You should see images appear in the three jit.pwindow objects in the patch. Note
that the toggle box not only starts and stops the metro, but also starts and stops the movie transport of the two
jit.qt.movie objects.

The lower half of the tutorial patch (with two of the three jit.pwindow objects) looks something like this:

The jit.chromakey object

Click with the mouse on the blue region of the left-hand jit.pwindow object (i.e. the area behind the man's head in the
movie).

The third jit.pwindow object (in the lower-right hand of the patch) will look like this:
How the heck did he get in front of that fence?

The jit.chromakey object


Chromakeyingthe process of superimposing one image on top of another by selective replacement of coloris
accomplished in Jitter by the jit.chromakey object. By specifying a color and a few other parameters, jit.chromakey detects
cells containing that color in the first (left-hand) matrix and replaces them with the equivalent cells in the second (right-
hand) matrix when it constructs the output matrix. The result is that cells from the first matrix are superimposed onto the
second.

Since any color is fair game for the chromakey, try clicking elsewhere in the lefthand jit.pwindow. Different colors will be
knocked out of the man's face to reveal the traffic.

The disappearing face trick (part one)

Historical note: Bluescreen compositing, or the process of shooting live footage against a blue matte background
only to replace the blue with a separate image later, has been around since the late 1930s. Originally a very expensive
film process involving expensive lithographic color separation, bluescreen (and its slightly less common sibling,
greenscreen) has evolved into the most commonplace (and effective) special effect in film, television, and video. The
ability to perform chromakeying (the technical term for the process) using analog (and later digital) video
superimposition has only made it more ubiquitous. Video chromakeying is often referred to in the television industry
as CSO (Colour Separation Overlay), the name given to the process by the BBC team that developed it in the 1960s.
Petro Vlahos, a bluescreen innovator in the 1960s, was awarded a Lifetime Achievement Award by the Academy of
Motion Picture Arts and Sciences in 1994, an acknowledgment of how indispensible the technology had become.

The jit.chromakey object uses the color attribute to define the center color to in the chromakey (called the reference color).
This attribute is set as a list of values for as many planes as exist in the matrices that are being keyed. The tol attribute
specifies a range of values around the key color. Colors within this range will be keyed as well. When using jit.chromakey
with char matrices (e.g. video), the attributes are specified in a floating point range 0 to1, which is then mapped to the 0-
255 range necessary for char data. To set the color attribute for a solid green chromakey, therefore, you would set the
attribute as color 0 0 1.0 0, not 0 0 255 0. A tol range of 0.5 will key all values within half of the chromatic distance from
the reference color (computed as the sum of the magnitudes of difference in each plane between the reference color and the
actual cell value). A tol range of 0 will treat only the exact reference color as part of the chromakey.

Try clicking on the blue region in the lefthand movie again, and play with the tol attribute to see how the chromakey
output changes. At low tolerance, some of the bluescreen in the left image will remain in the keyed output. At a very high
tolerance, parts of the man's face may disappear.

In the tutorial patch, the color attribute to jit.chromakey is set by clicking on an invisible object. If you unlock the patch,
you will see a region of concentric red squares that sit on top of the left-hand jit.pwindow object:

The suckah object

The region is a Max user interface object called suckah, which appears on the object palette like this:

The suckah object in the object palette

The suckah object reports the RGB values of any pixel on the screen that the suckah object overlays. It reports these values
as a list of integers out its outlet when you click in the object in a locked patch. For example, clicking on a region of solid blue
that has a suckah on top of it will cause the suckah to send out the list 0 0 255.
To set the color attribute for our jit.chromakey object, we take the RGB list that comes out of the suckah object and send it
through a prepend 0, which adds an alpha value of 0 to the front of the list. The resulting ARGB list is then divided by 255
using the vexpr object to scale it to the range of 0-1. The message is then completed by the prepend color. The final
message is then sent to jit.chromakey.

The Blue Screen of Death


The jit.chromakey object has additional attributes: minkey, maxkey, and fade. When a matrix arrives in the left inlet,
jit.chromakey creates a greyscale (1-plane) mask internally, based on that matrix. Cells in the incoming matrix that have
color values within the tolerance (tol) range are set to the maxkey attribute's value (the default is 1) in the mask. Regions
outside the tolerance range are multiplied by the minkey attribute (default is 0). If the minkey and maxkey are set to 0 and
1, the resulting image should look white where the keying should take place, and black where the original image is to be
retained.

The resulting mask and its inverse are then multiplied by the right and left matrices, respectively. The results of the
multiplication are then added to form the composite image. The following diagram shows you a pictorial overview of the
process:

The two sources, their masks (with minkey at 0 and maxkey at 1 ) and the composite chromakey.

As you can see, the maxkey attribute sets the strength of the righthand matrix in the output, while the minkey attribute sets
the strength of the lefthand matrix. If we were to reverse the minkey and maxkey attributes, the chromakey would be
reversed, and the following would happen:

The composite effect with the minkey at 1 and the maxkey at 0 (reverse chromakey).
The fade attribute allows for an amount of interpolation between the area being keyed and the area not being keyed. This
lets you create a soft edge to the chromakey effect. Colors in the left matrix that are slightly out of bounds of the key
tolerance range, yet that are within the range of tol + fade from the reference color, are interpolated between their original
(unkeyed) color and the color in the same cell of the right matrix. The amount of interpolation is based on how great the
fade value is, and how far the color in question lies outside the tolerance range.

Try experimenting with different tol, fade, minkey, and maxkey values for different colors. Watch how the five attributes
interact for different keying effects, and how the minkey and maxkey values complement one another.

Accurate chromakeying can be a challenging process. Correct values for the tol and fade attributes are essential to make
sure that the correct regions in the first image are keyed to the second image. In general, very detailed key images will show
slight aliasing in spots where the colors rapidly move between keyed and non-keyed regions. In addition, a single key color
(e.g. blue) almost never suffices for a complete key, so a range of values must always be used. You will often find, however,
that the color you want keyed out of part of the image is somewhat present in the region you want to retain! Balancing all of
these factors to get the most convincing effect is the hardest part of using the jit.chromakey object.

Summary
The jit.chromakey object lets you do two-source chromakeying in Jitter. You can set a color range for the key using the
color and tol attributes, and use the fade, minkey, and maxkey values to define how the two matrices work in a composite.
The suckah user interface object allows you to easily select colors as they appear on the screen by setting the object over a
jit.pwindow. Clicking the suckah object will give you the color of the pixel just clicked on the screen.

See Also
Name Description
jit.chromakey Key images based on chromatic distance
jit.pwindow Show data in a patcher
jit.qt.movie Play or edit a QuickTime movie
loadbang Send a bang when a patcher is loaded
metro Output a bang message at regular intervals
prepend Add a message in front of input
suckah Get a pixel from the display
vexpr Evaluate a math expression for a list
Lists and Matrices
Tutorial 11: Lists and Matrices
This tutorial shows how to use Max lists to fill all or part of a matrix , and how to retrieve all or part of a matrix's contents as
a list. We will also demonstrate the use of matrix names to access the contents of a matrix remotely, a concept that will be
demonstrated further in Tutorials 12, 16, and 17.

Matrix Names
Open the tutorial.

In the yellow region in the upper left corner of the patch, you'll see a blue jit.matrix object. The first argument gives the
matrix a specific name, smallbox. The remaining arguments say that the matrix will have 1 plane of char data, and that the
matrix will have only one dimension with 12 cells.

This matrix has a unique name: smallbox .

In Tutorial 2 we explained that every matrix has a name. If we don't give a matrix a name explicitly, Jitter will choose a
name arbitrarily (usually something strange like "u040000114", so that the name will be unique). The name is used to refer
to the place in the computer's memory where the matrix's contents are stored. So, why give a name of our own to a matrix?
That way we'll know the name, and we can easily tell other objects how to find the matrix's contents. By referring to the
name of a matrix, objects can share the same data, and can access the matrix's contents remotely, without actually receiving
a jit_matrix message.

Jitter's use of the matrix name to refer to its memory location is analogous to the way Max's value object works. You
can have many value objects with the same name, and you can store a numeric value in any one of them and retrieve
the same value from any other one of them. But there is really only one memory location for that name, so they are all
sharing the same data. In a like manner, you can have more than one jit.matrix object with the same name, and they
will all share the same data. Some other objects, such as jit.fill, can access the contents of that matrix just by knowing
its name.

jit.fill
In Tutorial 2 we showed how to place a numeric value in a particular matrix location using the setcell message, and how to
retrieve the contents of a location with the getcell message. Now we will show how to use the jit.fill object to place a whole
list of values in a matrix. (Later in this chapter we'll also show how to retrieve many values at once from a matrix.)

In the upper left corner of the patch there is a message box containing a list of twelve numeric values. It's attached to a
jit.fill smallbox object. The smallbox argument refers to a matrix name.

jit.fill puts a list of values in the named matrix

Click on the message box to send the list of values to the jit.fill smallbox object. The jit.fill smallbox object places those
values in the matrix named "smallbox". To verify that this is true, click on the button above the jit.matrix smallbox object
to display the contents of the "smallbox" matrix. The values are printed in the Max window by jit.print, and displayed as
levels of gray by jit.pwindow.
In this example, the list was exactly the right length to fill the entire matrix. That need not be the case, however. We can
place a list of any length in any contiguous portion of a 1D or 2D matrix.

The offset attribute


By default, jit.fill places the list of values at the very beginning of the matrix. You can direct the list to any location in the
matrix, though, by setting jit.fill's offset attribute. The portion of the patch numbered 2 demonstrates the use of the offset
feature.

First specify the offset, then provide the list

This example chooses a cell index at random, uses that random number as the argument to an offset message to the jit.fill
graybox object, then sends a 16-element list to be stored starting at that index in the graybox matrix.

Click on the toggle to start the metro. Every half-second, the 16-element list will be written to a new location in the
"graybox" matrix. Find the jit.matrix graybox 1 char 256 object in the center of the window. Click on the button above it
to display its contents in the jit.pwindow.

The list has been written to four locations in the "graybox" matrix

You can use the clear message to zero the contents of the "graybox" matrix, then display it again as the metro writes the
list into new random locations. When you're done, turn off the metro.
Using multiSlider
So far we've shown how to put a predetermined list of values into a matrix. When you want to generate such a list of
numbers interactively in Max and place them in a matrix in real time, you'll need to use a Max object designed for building
lists. We'll look at two such objects: multislider, and zl.
The multislider object displays a set of individual sliders, and it sends out the position of all of its sliders at once as a list of
values. It sends out the whole list when you click in the window to move any of the sliders, and it sends the list again when
you release the mouse button. In part 3 of this patch, we've set up a multislider to contain 256 sliders that send values from
0 to 255, so it's just right for sending a list of 256 char values to the jit.fill graybox object.
Use the mouse to draw in the multislider, setting its 256 sliders. When you release the mouse button, the list of 256 values
is sent out to the jit.fill graybox object. Notice how the brightness of the matrix cells corresponds to the height of the
sliders.

As soon as jit.fill receives a list in its inlet, it writes the values into the named matrix (at the position specified by the offset
attribute). As soon as this is done, jit.fill sends a bang out its left outlet. You can use that bang to trigger another action,
such as displaying the matrix.

In the first two examples we deliberately avoided using the bang from the left outlet of jit.fill, in order to make it quite
clear that jit.fill writes into the named matrix remotely without being physically connected to the jit.matrix object. The
bang out of jit.fill's left outlet is convenient, though, for triggering the output of the matrix as soon as it has been
filled.

Using zl
In some situations you might want to use a matrix to store numeric messages that have occurred somewhere in the patch:
MIDI messages, numbers from a user interface object, etc. The setcell and getcell messages to jit.matrix are useful for that,
but another way to do it is to collect the messages into a list and then place them in the matrix all at once with jit.fill.
The zl object is a versatile list-processing object that can help you collect individual numbers into a list. It has many possible
modes of behavior, depending on its first argument. When its first argument is group, it collects the messages received in its
left inlet until it has amassed a certain number of them, then sends the numbers out as a single list. (The values are grouped
in the order in which they were received.) So, in part 4 of the patch, we have placed a zl group 256 object that will collect
256 values in its left inlet, and when it has received 256 of them it will send them out its left outlet as a list (and clear its own
memory).
Move the slider up and down to generate 256 input values for the zl object. When zl has received 256 numbers, it sends
them as a list to jit.fill graybox which writes them into the "graybox" matrixthen bangs the jit.matrix graybox 1 char
256 object to display the matrix.

zl sends a 256-element list into the "graybox" matrix, then bang s jit.matrix to display the result

If you have OMS installed and have a MIDI keyboard controller attached to your computer, you can use the modulation
wheel of the MIDI keyboard to move the slider. (The interaction between MIDI and Jitter is explored in detail in later
tutorial chapters.)

Values are doubled to occupy the range 0-254, making them useful as char data for the matrix

You can change the length of the list that zl collects, by sending a new list length in the right inlet from the List Length
number box. And you can say where in the matrix you want to put it, by sending an offset message to jit.fill from the
Location number box. By varying the list length and location, you can put any number of values into any contiguous region
of the matrix.

Try changing the List Length of zl (to, say, 100) and setting the Location of jit.fill's offset attribute (to, say 50), then move
the slider some more to put a list of values into that particular location in the matrix.
You can combine parts 2, 3, and 4 of the patch to fill the "graybox" matrix in different ways.

jit.fill with Multiple-plane Matrices


jit.fill works fine with multiple-plane matrices, but it can only fill one plane at a time. The plane that jit.fill will access is
specified in its plane attribute. In part 5 of the patch, we've created another matrix, with four planes of char data this time,
named colorbox. We've set up three multisliders and three jit.fill objects, each one addressing a different color plane of the
"colorbox" matrix.

Filling each plane independently

Drag on the three colored multislider objects to fill each of the three color planes.
This is a convenient way to generate different curves of intensity in the RGB planes of a matrix. The jit.pwindow that's
showing the matrix is actually 256 pixels wide, so each of the 64 cells of the matrix is displayed as a 4-pixel-wide band. If
you turn on the interp attribute of the jit.pwindow, the differences between adjacent bands will be smoothed by
interpolation.
Click on the toggle above the interp $1 message box to send the message interp 1 to jit.pwindow. (Note that this also
sends a bang to jit.matrix to re-display its contents.

The same as the previous example, but with interpolation turned on in jit.pwindow

jit.fill with 2D Matrices


So far, all of our examples have involved one-dimensional matrices. What happens when you use a list (which is a one-
dimensional array) to fill a two-dimensional matrix via jit.fill? The jit.fill object will use the list to fill as far as it can in the
first dimension (i.e. it will go as far as it can the specified row), then it will wrap around to the next row and continue at the
beginning of that row. We've made it possible for you to see this wrapping effect in action.

Click on the button labeled 2D. This will change the jit.matrix colorbox object to contain a two-dimensional 8x8 matrix,
and will also resize the jit.pwindow to a more appropriate shape. Whenever you change the dimensions of a matrix, it loses
its contents, so you will need to click in the three multisliders again to fill the matrix anew. You are still sending a 64-
element list to each of the jit.fill objects, and they fill each of the eight rows of the matrix with eight elements.

Important: Although we don't demonstrate the use of the offset attribute with a 2D matrix in this patch, it's worth
mentioning that when the name attribute of jit.fill names a 2D matrix, the offset attribute requires two arguments:
one for the x offset and one for the y offset.

jit.fill only works for 1D and 2D matrices.

The same example, with each list wrapped around in an 8x8 matrix (shown uninterpolated)
The same example, displayed with interpolation

jit.spill
The complementary object to jit.fill is jit.spill. It takes a jit_matrix message in its inlet, and sends the matrix values out its
left outlet as a Max list. You may have noticed that while you were using part 5 of the patch, the jit.spill object in part 6 was
sending the values of plane 1 (red) out its left outlet and setting the contents of a message box.

The contents of plane 1 of the "colorbox" matrix, displayed as a Max list

Although not demonstrated in the patch, jit.spill also has listlength and offset attributes that let you specify exactly
how many values you want to list, and from exactly what location in the matrix.

If you need to have the values as an immediate series of individual number messages rather than as a single list message, you
can send the list to the Max iter object.

Get a few values from the matrix and make them into separate messages

jit.iter
For times when you need to retrieve every value in a matrix, there is an object called jit.iter. When it receives a jit_matrix
message in its inlet, it sends out an as-fast-as-possible sequence of messages: the cell index (out its middle outlet) followed
by the value(s) in that cell (out its left outlet) for every cell of the matrix in order. For a large matrix, this can be an awful lot
of Max messages to try to send out in a single tick of Max's scheduler, so when it's done reporting all of the values in a
matrix jit.iter sends a done message out its right outlet.
In part 7 of the patch there is a jit.iter object which receives the matrix information from the jit.matrixgraybox 1 char 256
object. We use a swap object to switch the order of the cell index (coming out the middle outlet of jit.iter) and the cell value
(coming out the left outlet of jit.iter). We then use the value of that cell as the y-value we want to store in the table object,
and we use the cell index as the x-axis index for the table .
Click on the multislider object to send its contents to jit.fill (which will in turn bang the jit.matrix object and
communicate its contents to jit.iter. Then double-click the table object to open its graphic window and see that it contains
the same values as the "graybox" matrix.

Note that this technique of using jit.iter to fill a table works well with a modest-sized one-dimensional one-plane matrix
because a table is a one-dimensional array. However, the matrix of a jit.qt.movie object, for example, has two dimensions
and four planes, so in that case the output of jit.iter's middle (cell index) outlet would be a two-element list, and the output
of the left (value) outlet would be a four-element list.

What are ya gonna do with all those numbers?

Still, for one-dimensional matrices, or small 2D matrices, or even for searching for a particular value or pattern in a larger
matrix, jit.iter is useful for scanning an entire matrix.

Summary
For placing individual values in a matrix, or retrieving individual values from a matrix, you can use the setcell and getcell
messages to jit.matrix (as was demonstrated in Tutorial 2). For placing a whole list of values in a matrix, or retrieving a list
of values from a matrix, use the objects jit.fill and jit.spill. These objects work well for addressing any plane of a 1D or 2D
matrix, and they allow you to address any list length at any starting cell location in the matrix.

The multislider and zl objects are useful for building Max list messages in real time. With multislider you can "draw" a list
by dragging on the sliders with the mouse. With zl group you can collect many individual numeric values into a single list,
then send them all to jit.fill at one time.
You specify the starting cell location in the matrix by setting the offset attribute of jit.fill (or jit.spill). The jit.fill object
requires that you set its name attribute (either by sending it a name [name] message or by typing in a [name] argument),
specifying the name of the matrix it will fill. It accesses the matrix using this name, and sends a bang out its outlet whenever
it has written a list into the matrix. You can use that bang to trigger other actions. In Tutorials 12, 16, and 17 we show some
practical uses of accessing a matrix by its name.

To output every value in an entire matrix, you can send the matrix to jit.iter.

See Also
Name Description
ctlin Output received MIDI control values
jit.fill Fill a matrix with a list
jit.iter Iterate a matrix as lists or values
jit.matrix The Jitter Matrix!
jit.print Print a matrix in the Max window
jit.pwindow Show data in a patcher
jit.qt.movie Play or edit a QuickTime movie
jit.spill Unroll a matrix into a list
metro Output a bang message at regular intervals
multislider Display data as sliders or a scrolling display
prepend Add a message in front of input
random Generate a random number
slider Move a slider to output values
zl Process lists in many ways
Color Lookup Tables
Tutorial 12: Color Lookup Tables
In this tutorial we will explore how to use color lookup tables to remap data inside a Jitter matrix. We'll also look at different
strategies for generating lookup tables as matrices.

Lookup tables are simply arrays of numbers where an input number is treated as an address (or position) in the array. The
table then outputs the number stored at that address. Any functiona graph where each x value (address) has a
corresponding y value (output)can be used as a lookup table. Max objects such as funbuff, table, and the MSP buffer~
object are common candidates for use as lookup tables. In this tutorial, we'll be using Jitter matrices in much the same way.
Open the tutorial.

The tutorial patch shows two new objects: jit.charmap, which maps input cell values to new output values according to a
lookup table matrix, and jit.gradient, which generates color gradients.

Read the images

The top left of the patch shows a jit.qt.movie object in which you can read two different files. The object is initialized (via
loadbang) with the file colorwheel.pct loaded into it. You can also load in the movie rain.mov by clicking on the message
box that says read rain.mov. You should feel free to alternate between the two image sources throughout the tutorial.

Start the metro by clicking the toggle box at the top of the patch. You will see the color wheel appear in both the
jit.pwindow at the top and the jit.pwindow at the bottom of the patch. In addition, you will see a gradient appear in a third
(rectangular) jit.pwindow at the bottom.

The output of jit.charmap and the lookup table matrix


The bottom of the patch contains the jit.charmap object, which we will use in this tutorial to remap cell values in the image.
The object has two inlets, the left one of which is connected from our jit.qt.movie object at the top of the patch. The right
inlet has a one-dimensional, four-plane char jit.matrix connected to it with a name (colortable) and a width of 256 cells.
This is the lookup table that jit.charmap uses to remap the color values of the cells in the lefthand matrix. The receive
object (abbreviated r) with the name ctable receives data from elsewhere in the patch and sends it to the jit.matrix. For
example, at the top of the patch, turning on the toggle box will send a bang to the jit.matrix, causing it to send out its
matrix message (jit_matrix colortable) to both the jit.pwindow and the right inlet of jit.charmap.

Lookup Tables
Lookup tables (which are often called transfer functions) are arrays of numbers where an input number is 'looked up' as an
index in the table. The number stored at that index (or address, or position) is then retreived to replace the original number.
The jit.charmap object replaces every value in every plane in every cell of its (leftmost) input matrix with values stored at
the relevant indices in the lookup table that arrives as a matrix in its right inlet.

For example, assume that the matrix we send to jit.charmap contains a cell with the values 100 50 35 20 in its four
planes. The object looks up each plane individually at the relevant position in its lookup table matrix and replaces it. If our
lookup table has the value 73 at cell 100 in the first plane, 25 at cell 50 in the second plane, 0 at cell 35 in the third plane,
and 203 at cell 20 in the fourth plane, our output cell will contain the values 73 25 0 203.

Lookup tables for jit.charmap should be one-dimensional matrices of 256 cells with the same number of planes as the
matrix you want to remap. This is because the possible range of values for char matrices is 0-255, so 256 numbers are need
to cover the full range of the lookup table.

Generating the Lookup Table


The upper-right side of the tutorial patch contains three multislider objects that let you design the transfer functions for
planes 1-3 of the lookup table matrix colortable:

Filling the lookup table matrix with values from a multislider

The multislider objects (which have 256 integer sliders in the range 0-255) send their lists to the jit.fill objects below them.
These objects replace the values currently stored in planes 1-3 (i.e. Red, Green, and Blue) of the matrix colortable with the
values from the multislider objects. (See Tutorial 11.) When the matrix has been edited with the new values, the jit.fill
objects send out a bang, which we send to the jit.matrix on the right of the patch that connects to the right inlet of
jit.charmap. We're ignoring plane 0 in this tutorial because it only contains Alpha values when we treat 4-plane Jitter
matrices as video.

The jit.matrix and jit.fill objects in our patch share the same name (colortable). As a result, the two objects read from and
write to the same matrix, allowing one object (jit.fill) to generate data that the other object (jit.matrix) can read from
without having to copy data between two separate matrices. This is similar to how many MSP objects (e.g. peek~, play~,
groove~) can share sample data stored in a single buffer~. See Tutorials 11, 16, and 17 for more information on using
named matrices.

Do some freehand drawing in the multislider objects, to see how this affects both the lookup table (the smaller of the
jit.pwindow objects) and the output image from the jit.qt.movie object. Remember to switch back and forth between the
two image sources.

If you want to reset any of the planes to a y="x" transfer function (i.e. a straight ascending line that leaves all the values
unchanged), you can click the button object above the relevant multislider object. The subpatchers called p clear initialize
the multislider objects with an uzi.
Important note: Like many Max objects, Jitter objects retain matrices stored in one inlet even if a new matrix arrives in
another inlet. The metro object in this patch, therefore, only needs to trigger the jit.qt.movie object. The jit.matrix
that contains the lookup table to jit.charmap only needs to output its value to the object when the data stored in it
actually changes.

Here are some lookup tables and their results:

Three sets of multislider objects and their resulting color lookup tables and output color wheels

In the first example, the red and blue transfer functions are approximately inverted while the green is normal. The result is
that high values of red and blue in the input image yield low values on the output, and vice versa. This is why the white
background of the color wheel now looks green (the cell values of 0 255 255 255 have been mapped to 0 0 255 0).

The second example has the green plane completely zeroed (the transfer function set to 0 across the entire span of input
values). The red and blue planes are also set to 0 up to a threshold, at which point they ramp up suddenly (the red more
suddenly than the blue). As a result the majority of the colorwheel is black (especially in the 'green' area). The red plane only
becomes visible in very high values (i.e. the magenta in the background of the color wheel).

The third example has the red plane mapped normally. The green plane has a parabolic shape to it, where the extreme values
are mapped high and the medium shades are mapped low. The blue plane is normal except for a range in the midtones,
where it is zeroed. This nonlinearity is visible as a red 'fault line' across the top and down the right side of the colorwheel.

As you can see, there are infinite ways to remap the cell values of these matrices. We'll now investigate another object, which
lets us remap the color values in a more precise manner.

The jit.gradient object


The lower right area of the tutorial patch shows a method for generating lookup tables using the jit.gradient object:

Using the jit.gradient object

The jit.gradient object generates single dimension char matrices that transition smoothly between two specified cell values.
The start and end attributes are lists that specify these cell values. For example, a start attribute of 0 0 0 0 and an end
attribute of 0 0.5 1.0 0.5 will generate a gradient that goes from black (at cell 0 in the matrix) to pale green (at the last cell
in the matrix). We've given our jit.gradient object the relevant arguments to make it 256 cells wide, so that it can be stored
in our colortable jit.matrix when it changes. Note that jit.gradient takes floating point numbers in its attribute lists to
specify char values (i.e. a value of 1.0 in the attribute specifies a char value of 255).

The attributes are formatted by taking the RGB list output of the Max swatch objects and converting them to ARGB floats.
After the attribute has been sent to the jit.gradient object, the object is given a bang from the trigger object to cause it to
output its matrix into the jit.matrix object on the left of the patch.
Try selecting some colors in the swatch objects. The start and end attributes will specify the boundaries of the lookup
table, so values in the input image will have a duotone appearance, morphing between those two colors. The multislider
objects at the top of the patch will reflect the correct lookup tables generated by the jit.gradient object.

Using color gradients as lookup tables

The first example shows an inverted image. The start of the lookup table is white (start 0 1.0 1.0 1.0) and the end of the
lookup table is black (end 0. 0. 0. 0.). As a result, input values of 0 are mapped to 255, and vice versa (y="255-x)."

The second and third examples show duotone gradients that remap the color wheel's spectrum to between red and orange
(example 2) and olive and cyan (example 3). Notice how, depending on the original colors at different points in the color
wheel, the gradient curve becomes steeper or more gradual.

The third attribute of the jit.gradient object is the cheby attribute, which specifies a curve to follow when morphing between
the start and end values in the matrix. The cheby attribute takes a list of floating point numbers as arguments. These
arguments are the amplitudes of different orders of Chebyshev polynomials (see below). These special function curves
create different effects when used in lookup tables. The multislider in the tutorial patch that sets the cheby attribute lets
you specify the relative amplitude of the first eight Chebyshev polynomial curves, which have the following shapes (if you
view them as progressing from black to white):

Gradients generated using Chebyshev orders 1-4 (top row) and 5-8 (bottom row)

Technical note: Chebyshev polynomials are commonly used as transfer functions in waveshaping audio signals in
digital synthesis algorithms (they have special properties that allow them to distort sinusoidal waveforms into
harmonic spectra equivalent to the amplitudes of different orders). The MSP lookup~ object can be used with a
function loaded into a buffer~ to do the equivalent process in audio signal processing that we're doing in this tutorial
with image. See Tutorial 12: Synthesis: Waveshaping in the MSP manual for more details.

Reset the start and end points of the gradient (by clicking the message boxes above them) and slowly change the
multislider that controls the cheby attribute. Watch how the color wheel changes as colors disappear and reappear in
different regions.

When you use the cheby attribute in the jit.gradient object, you can get some very interesting color warping effects even if
you leave the start and end points of the gradient at black and white. Here are some examples with our movie clip
rain.mov:
The effect of different gradient curves on the color spectrum of the rain

The lefthand image shows an unprocessed still image from the rain movie. The middle image shows what happens to the
color spectrum when the gradient is generated using a second order Chebyshev polynomial (the darkest area in the image is
now in the middle of the color spectrum). The righthand image shows a more complex gradient, where the color spectrum
shows numerous peaks and troughs.

The multislider objects at the top of the patch reflect the current state of our lookup table (the matrix generated by
ourjit.gradient object is sent to a jit.iter object inside of the p showit subpatch, where the numbers are grouped to set the
state of the multislider objects). Try generating a gradient and then modifying the lookup table by hand by changing the
multislider objects. This lets you use the jit.gradient object as a starting point for a more complicated lookup table.

Summary
You can map cell values in char Jitter matrices using the jit.charmap object. The right inlet of jit.charmap takes a 256-cell
matrix that defines the lookup table (or transfer function) to be applied to the incoming matrix data. You can define the
lookup table using several strategies, including using jit.fill to generate the matrix from Max lists, or using the jit.gradient
object to generate color gradients between a start and end cell value according to a curve shape specified by the cheby
attribute.

See Also
Name Description
jit.charmap Map 256-point input to output
jit.fill Fill a matrix with a list
jit.gradient Generate Chebyshev gradients
jit.matrix The Jitter Matrix!
jit.pwindow Show data in a patcher
jit.qt.movie Play or edit a QuickTime movie
metro Output a bang message at regular intervals
multislider Display data as sliders or a scrolling display
swatch Select and display RGB colors
uzi Send many bang messages
vexpr Evaluate a math expression for a list
Scissors and Glue
Tutorial 13: Scissors and Glue
In this tutorial we'll learn how to use two simple objects to slice and combine rectangular regions of two-dimensional Jitter
matrices.
Open the tutorial.

The tutorial patch shows two Jitter objects that neatly complement each other: jit.scissors, which cuts a matrix into equally
sized smaller matrices, and jit.glue, which pastes multiple matrices into one matrix. We'll also take a brief look at a Max
object called router, which lets you easily route Max messages from multiple sources to multiple destinations.

Read the movie

The top left of the patch is straightforward enough. The loadbang object automatically sends the read traffic.mov message
to the jit.qt.movie object, which then loads our movie of traffic footage.
Start the metro by clicking the toggle box at the top of the patch. You will see the traffic appear in the large jit.pwindow
at the bottom of the patch. More interestingly, you will see the traffic image cut into quadrants, each of which appears in a
separate jit.pwindow object off to the right side.

Cut it Up
The jit.scissors object is responsible for splitting the Jitter matrix containing the traffic footage into four smaller matrices:

The jit.scissors object

The jit.scissors object cuts a Jitter matrix of any size, type, or planecount into smaller Jitter matrices that are then sent out
independent outlets of the object. The rows and columns attributes specify how many smaller matrices are created each
time the object receives a new matrix in its inlet. In our tutorial patch, the jit.scissors object is splitting the image into four
smaller matrices (2 columns and 2 rows). These separate matrices come out individual outlets of the object in column-
major order (i.e. the object assigns outlets to the smaller matrices from left-to-right and then from top-to-bottom).

Two very important things you should know about jit.scissors:

1) The number of outlets that jit.scissors has is determined at object creation. Therefore the rows and columns
attributes will only create outlets when they are specified in the object box. For example, typing jit.scissors @rows 10
@columns 2 will create an instance of jit.scissors with 20 matrix outlets (plus the usual right outet for attribute
queries), but simply making a jit.scissors object with no arguments will only give you one matrix outlet. You can
change the rows and columns attributes with Max messages to the object, but you won't be able to add outlets beyond
what those initially created by the object.
2) The size (dim) of the matrices put out by jit.scissors is equal to the size of the slices of the matrix, not the entire
original matrix. For example, the four smaller matrices in our tutorial patch are each 160x120 cells, not 320x240.

Routing the Matrices


The four smaller matrices output by jit.scissors in our patch are each sent to two different places: to jit.pwindow objects so
we can see what's going on, and to a Max object in the middle of the patch called router. The colored patchcords illustrate
where each smaller matrix is sent.

The Max router object

The router object is a combination of the Max gate and switch objects. It takes two arguments (the number of routeable
inlets and the number of routable outlets) and is controlled by messages sent to the leftmost inlet. Most of the messages that
router understands are identical to the MSP object matrix~. As a result you can use router with the matrixctrl object with
ease.

The four inlets to the right of the router object take their input from the four matrix outlets of our jit.scissors object. A
receive object assigned to the symbol routeit gets messages from the lower-right of the tutorial patch, which controls our
router object. The four leftmost outlets of the router object are connected to a jit.glue object, which we'll talk about in a
moment.

Controlling the router

Sending the message patch followed by an inlet number and an outlet number to a router object will make a virtual
connection between that inlet and that outlet in the object. Any message arriving at that inlet will be instantly forwarded to
the relevant outlet. If an inlet was previously connected to that outlet, a patch message will sever that connection in favor of
the new one.

The radiogroup objects in this patch control which outlets of the router our four small Jitter matrices (arriving at the
inlets) are sent to. The inlets and outlets number up from 0, so the message patch 2 1 makes a connection between the
third routeable inlet and the second outlet of the router object.
Click on some of the radiogroup controls, and watch how the output image in the lower jit.pwindow changes. Notice how
with the router object you can make the matrices cut from the traffic image appear in any of the four quadrants of the
composite image at the bottom.

The Glue That Keeps It Together


The jit.glue object at the bottom of the patch does the effective opposite of jit.scissors. The rows and columns attributes
specify inlets, not outlets, and a composite matrix is output which is made up of the incoming matrices laid out in a grid.
Sending the same matrix to all four inlets of jit.glue

Important Note: As with jit.scissors, jit.glue can only create new inlets and outlets when the object is created, so the
rows and columns attributes present in the object box will determine how many inlets the object has. Also, the size
(dim) of the output matrix generated by jit.glue will be equal to the size of all the smaller matrices put together (e.g.
our four 160x120 matrices in this patch will yield one 320x240 matrix).

One final point worth making about jit.glue is that its default behavior is to only output a composite matrix when a new
matrix arrives it its leftmost inlet. If we were to disconnect the leftmost inlet of our jit.glue object, we would no longer get
any new output matrices from the object. The syncinlet attribute lets you make jit.glue sent its output in response to a
different inlet. A syncinlet value of -1 will cause jit.glue to output new composite matrices when it gets new matrices at any
inlet. While this sounds like a good idea in theory, it can quickly bog down the frame rate of your Jitter processes with lots of
redundant work.

Summary
The jit.scissors object cuts a matrix into smaller, equal-sized rectangular matrices. The jit.glue object takes equal-sized
rectangular matrices and pastes them back together into a composite matrix. The rows and columns attributes of both
objects determine their number of outlets or inlets, respectively, when given at object creation, as well as the way in which
the matrix is sliced up or composited. The router object lets you arbitrarily connect Max messages from multiple inlets to
multiple outlets in a similar fashion to the MSP matrix~ object.

See Also
Name Description
jit.glue Glue many matrices into one
jit.pwindow Show data in a patcher
jit.qt.movie Play or edit a QuickTime movie
jit.scissors Cut up a matrix into evenly spaced sub matrices
metro Output a bang message at regular intervals
radiogroup Radio button/check box user interface
router Route messages to multiple locations
toggle Switch between off and on (0/1)
Matrix Positioning
Tutorial 14: Matrix Positioning
Positioning Data in a Matrix
In this tutorial we discuss some ways to take a portion of one matrix and place it in some different location in another
matrix. There are various reasons you might want to reposition the location of data. We'll be focusing especially on visual
effects, but the techniques we show here are useful for any sort of task that involves moving matrix data around.

We'll show how to isolate a region of a matrix, place it at a particular position in another matrix, resize it (which can be
useful for visual effects such as stretching, pixelation, and blurring), and move it around dynamically.
Open the tutorial.

jit.window
In the bottom-left corner of the patch there is a jit.window object. We introduced this object in Tutorial 1; it creates a
separate window for displaying the contents of a matrix. In most of the other tutorial chapters we have used the jit.pwindow
object instead.
jit.window and jit.pwindow are pretty similaraside from the obvious difference that one opens a separate window while
the other uses a rectangular region within the Patcher windowand they share many of the same attributes and messages.
There are a few differences, though, so we'll use jit.window this time in order to demonstrate a couple of its unique
characteristics.

You probably can't see the Display window that has been opened by the jit.window object, because it's hidden behind the
Patcher window. However, if we want to, we can make the Display window be a floating windowone that always "floats"
on top of every other window in Max while still letting us interact with the foreground Patcher window. To do this, we must
turn on the floating attribute of jit.window with a floating 1 message. (The floating attribute is 0 by default.)
Click on the toggle box labeled Display as floating window to send a floating 1 message to jit.window.

Make the window "float" in front of all other windows

Note that the screen coordinates we've typed into the jit.window object for the display area450 60 770 300specify a
display area 320 pixels wide by 240 pixels high. (For an explanation of how to specify screen coordinates for jit.window, see
Tutorial 1 and/or the Note later in this chapter.)

From one jit.matrix to another


Now we will load in a picture and try some modifications.

Click on the message box importmovie sunset.jpg to load a picture into the jit.matrix object at the top of the patch.
Turn on the metro labeled Display On/Off to begin sending bang messages to jit.matrix.
The bang sends the matrix (through jit.hue) to a second jit.matrix object before displaying the image with jit.window. In
that second jit.matrix object we'll be able to modify attributes to change what part of the matrix we display.
The matrix goes (through jit.hue ) to another jit.matrix, then to jit.window

We've saved several preset configurations for the window's user interface objects in a preset object in the middle of the
patch.

In the preset object, click on preset 1.


This changes the dimensions of the lower jit.matrix object to 16x12, by sending a dim 16 12 message to it.

The dim message changes the dimensions of the matrix in jit.matrix

The matrix coming in has the dimensions 320x240, but the receiving jit.matrix has dimensions of only 16x12, so it tries its
best to display the entire matrix it receives, but it necessarily has to discard much of the information. This results in a very
pixelated image. (The term pixelation refers to the mosaic effect that results from using an insufficient viewing resolution
an insufficient number of pixelsto represent an image faithfully.) Even though the jit.window object is capable of
displaying the full-resolution 320x240 image (because of the window dimensions typed in as arguments), the matrix it is
receiving is only 16x12 now. It "expands" the 16x12 matrix to 320x240 for display purposes, duplicating pixels as it needs to.

Try dragging on the two number boxes labeled Change actual matrix dimensions to see different pixelation effects.

Interpolation
Now set the number boxes back to 16 and 12, and click on the toggle labeled Interpolate to smooth pixelation in the blue
region at the bottom of the patch to send an interp 1 message to jit.window.

Turn on interpolation in jit.window

Now the jit.window objectinstead of simply duplicating pixels of the 16x12 matrix to make a bunch of 20x20-pixel blocks
interpolates between values in the incoming matrix as it expands it to 320x240. That is, as it expands the image , it creates
a smooth gradation of colors between each cell value and and its neighboring values in the incoming matrix, so all of the
transitions from cell to cell in the displayed 320x240 matrix are as gradual as possible. The interpolation causes extreme
blurring because the size difference between the incoming matrix and the display is so great.

Click on the toggle again to turn off the interpolation. This sends an interp 0 message to jit.window, setting its interp
attribute to 0 (off). Enter some new matrix dimensions into the number boxes labeled Change actual matrix dimensions so
that the image is not quite so pixelated: say, 80 and 60. (You should see that now the pixelated blocks are each only 4x4.)
Click on the toggle to turn interpolation back on. Notice that in this case the blurring is not so extreme because
interpolation occurs over only 4 pixels. Click on the toggle again to turn off the interpolation.
Now find the other toggle with the same label, just above the jit.matrix object, and click on it to turn on interpolation
within jit.matrix (not jit.window).
Interpolation doesn't do much when you're reducing the size of the matrix

Notice that this doesn't have very much effect. That's because jit.matrix still only has a 80x60 matrix to send out.
Interpolation in this case (when we're reducing the size of the matrix rather than enlarging it) is pretty ineffectual.

Click on that toggle again to turn off interpolation in jit.matrix.

Isolate a Part of the Matrix


Now we'll look at ways to focus on a particular portion of a matrix.

In the preset object, click on preset 2. Now you see only a small portion of the picture.

This preset restores the dimensions of our jit.matrix object back to 320x240. But we can still isolate a particular part of the
matrix , without altering the actual dimensions of the full matrix, using some different attributes: srcdimstart, srcdimend,
and usesrcdim. Notice that we have sent three new messages to jit.matrix to set those three attributes: dimstart 40 150,
dimend 119 209, and usesrcdim 1. These messages let us specify a subset of the full matrix coming in the inlet, and send
those values out as a full-sized (in this case 320x240) matrix. This smaller subset of the incoming matrix gets "expanded"
(cells are duplicated as needed) within jit.matrix itself, to fill the size of the outgoing matrix. The srcdimstart and
srcdimend attributes are ignored. In the messages for setting the srcdimstart and srcdimend attributes, the words
srcdimstart and srcdimend are followed by cell indices describing the starting and ending points within each dimension.
With our dimstart 40 150 and dimend 119 209 messages, we have told jit.matrix to use a specific 80x60 region from cell
40 to 119 (inclusive) in the horizontal dimension and from cell 150 to 209 in the vertical dimension.

Note: In this chapter we've discussed three different ways of specifying rectangular regions! It's important to be clear
what we're specifying in each case.

In jit.window we typed in screen coordinates for the display area of the window. In the computer's operating system,
screen coordinates are specified in terms of the point at the upper-left corner of a pixel. The upper-left corner of the
entire screen is 0,0; the point two pixels to the right of that (the upper-left corner of the third pixel from the left) is
2,0; and the point 5 pixels down from that (the upper left corner of the sixth pixel down is 2,5. To describe a
rectangular area of the screen, we type in arguments for the left, top, right, and bottom limits of the rectangle's
coordinates.

In the dim attribute to jit.matrix, we provided dimension sizes for the object's matrix: the number of cells in each
dimension.

In the srcdimstart and srcdimend attributes, we're stating (inclusive) cell indices within the matrix. Remember that
cells are given index numbers that go from 0 to one less than the number of cells in that dimension. (Planes are
indexed similarly, by the way.) So for a 320x240 matrix, the indices for the cells in the first dimension go from 0 to 319,
and the indices for the cells in the second dimension go from 0 to 239. To set the source dimensions for jit.matrix, we
need to specify the range of cells we want to start at, using srcdimstart followed by a starting cell index for each of the
matrix's dimensions, and using srcdimend followed by the cell indices for the end of the range in each dimension.

These different ways of describing regions can be confusing, but if you think carefully about exactly what it is that
you're specifying, you'll be able to deduce the proper way to describe what you want.

We're using only an 80x60 pixel range of the incoming matrix as the source, but the destination matrix is 320x240. Once
again, this expansion of a smaller matrix into a larger one causes a pixelation effect. This time, though, the expansion occurs
inside jit.matrix (i.e. between its "source" region and its "destination" size), rather than between jit.matrix and jit.window
(as we did earlier when we reduced the actual dimensions of the jit.matrix). Therefore, if we want to smooth out the
pixelation by interpolating, we must do it in jit.matrix. There's no point in turning on interpolation in jit.window, since it's
already receiving a 320x240 matrix from jit.matrix.
If you want to verify this, turn on the toggle to send an interp 1 message into jit.window. It has absolutely no effect
because we're trying to interpolate a 320x240 matrix into a 320x240 display area, so no change occurs. Turn off that same
toggle to set the interp attribute of jit.window back to 0. Now use the other toggle to send an interp 1 message into
jit.matrix. This time we get the smoothing effect we desire.

Try entering new values into the number boxes to change the arguments of the srcdimstart and srcdimend attributes.
This lets you isolate any particular region of the picture as your "source" area. Of course, the dimensions you choose for your
source area will determine the distortion that the picture undergoes when it's expanded to fill a 320x240output matrix.

Flip the Image


You might assume that the arguments of the srcdimend attribute (the ending cell indices of the source region) should be
greater than the index numbers for the srcdimstart attribute. But that need not necessarily be so.

In the preset object, click on preset 3. Now the picture is has been flipped vertically.

The top and bottom have been flipped in the second dimension.

This example shows that if you specify an ending cell index in the vertical dimension that is less than the starting index,
jit.matrix will still relate those indices to the starting and ending points in the vertical dimension of the destination matrix ,
effectively reversing the up-down orientation of the values. (This statement assumes that you have not done the same sort of
flip to the orientation of the destination matrix!)

You could do the same sort of flip in the horizontal (first) dimension to flip the image horizontally. If you flip the source
region in both dimensions you get the same visual effect as if you had rotated the image 180.

In the preset object, click on preset 4.


In this example we've flipped the source region in both dimensions, reduced the size of the source area to 160x120, and
smoothed out the pixelation by turning on the interp attribute.

Resize the Output Matrix


Just as we specified the "source" region of the matrix, we can also specify a destination for that source. This still does not
change the size of the output matrix; that will still be 320x240, as determined by the dim attribute. However, this does
change the region into which the specified "source" region will be placed. The source region of the input matrix will be placed
in the destination region of the output matrix (with expansion/contraction as necessary). Cells of the output matrix that lie
outside the destination region will remain unchanged.

In the preset object, click on preset 5. The entire input matrix has been squeezed into an 80x60 rectangle in the center of
the output matrix.

The first thing to notice is that the usesrcdim attribute has been turned off, so that we're back to using the entire input
matrix as the source. (The srcdimstart and srcdimend attributes are now being ignored.) The usedstdim attribute has
been turned on, so the input will be placed in whatever part of the output matrix we specify. The dstdimstart and
dstdimend attributes have been set to specify the cells in the center of the matrix as the destination: dstdimstart 120 90
and dstdimend 199 149. We've turned the interp attribute off because we're contracting the image rather than expanding
it.

Notice also that we've turned on the toggle labeled Erase previous image. This sends the number 1 into the if $2 then
clear object. The if part of the statement is now true, so every time the object receives a message in its left inlet it will send
out the message clear. This clears the contents of the jit.matrix object immediately after displaying the image, to prepare
jit.matrix for the next matrix it will receive . That ensures that the values in all the cells outside the destination region will
be 0, so the unused region of the output matrix will be displayed as black.

Change some of the values in the number boxes that provide the destination dimensions, to move (and resize) the picture
within the Display window.
Now turn off the toggle labeled Erase previous image, to suppress the clear messages. Change the arguments of
dstdimstart and dstdimend some more, and notice what's different this time. The previous destination regions are still
being drawn in the Display window because those cells in the matrix have not been cleared, and they are left unchanged if
they're outside the new destination region. This gives the effect of leaving "trails" of the previous image behind. We can
potentially use these artifacts for their particular visual effect.

If the matrix is not cleared, old destination areas will be left behind if they're outside the new destination region. For
continuous changes, this leaves a "trail" of past images.

Moving the Image Data Around in the Matrix


By setting up an automated Max process that modifies the dstdimstart and dstdimend attributes, we can move the data
around in the matrix, making the image seem to move around in the display.

In the preset object, click on preset 6.


This starts an automated process inside the patcher move_around subpatch that provides a continuous stream of new
arguments for the dstdimstart and dstdimend attributes. The toggle above the patcher turns on this process, and the
number box gives a time, in milliseconds, for each move to a new destination.

Double-click on the patcher move_around object to see the contents of the subpatch. So far, we're only using the right
half of the subpatch.

The destination-moving process in the subpatch [move_around]

The "rate" value coming in the right inlet is a time interval for the metro object. The metro periodically bangs four random
objects which choose new left, top, right, and bottom cell indices at random. These destination points are sent, along with
the time value, to line objects. The line objects send out new values every 50 ms (the rate at which we're displaying the
image) to gradually move the destination region to these new random points. Outside the subpatch, those values are used as
arguments for the dstdimstart and dstdimend attributes of jit.matrix.
This subpatch contains a couple of tricks worth noting. The first trick is that we've made it so the arguments for dstdimend
can potentially exceed the 320x240 range of the matrix. For example, we use a random 640 object for the horizontal
dimension, then subtract 160 from the result to give us an ending cell index from -160 to 479. We do this to increase the
likelihood of a larger destination area so that we can see a larger view of the image as it moves around, and it also means
that the image will more frequently move all the way to the edge of the window. It's noteworthy that we can specify
destination boundaries that are beyond the limits of the actual cells in the matrix, and jit.matrix will place the image in that
area to the best of its ability (clipping it off when it exceeds the limits of the matrix dimensions). The second trick is a trivial
but useful detail: we use a sel 0 object to detect when the metro gets turned off, and we use that to trigger a stop message to
each of the line objects so that they don't continue sending out values after the user has turned off the process.
Close the [move_around] subpatch window.

Changing, Resizing, and Moving the Source Image


Now we'll automate changes to the source image, as well.

In the preset object, click on preset 7.


In much the same manner as we did for the destination area, we're now continually changing the source area of the image. In
effect, we're now seeing a constantly changing view of some retangular subset of the source matrix (using srcdimstart and
srcdimend) while also constantly resizing that view and moving it around in the window (using dstdimstart and
dstdimend). Because the source and destination rectangles are chosen randomly by the [move_around] subpatch, the
image sometimes gets flipped, too. We have turned on the interp attribute in the jit.matrix object to smooth out the
pixelation that would occur when the source image gets stretched.

To get a slightly clearer view of what's going on, try turning on the toggle marked Erase previous image.

One More Word About Dimensions


This tutorial has shown how to change the dimensions of a jit.matrix object, and how to specify source and destination
regions within that object. For ease of discussion and visualization, we've used a two-dimensional matrix, and specified
source and destination rectangles within the matrix. But we should point out that these ideas can also be employed with
matrices that have any number of dimensions. (The number of arguments for srcdimstart, srcdimend, dstdimstart, and
dstdimend should correspond to the number of dimensions in the jit.matrix object.) For example, if we have a three-
dimensional matrix, these arguments can be used to specify a hexahedron in the virtual 3D space of the matrix.

Note: In certain Jitter objects that deal exclusively with 2D matrices, such as jit.qt.movie, source and destination
regions will always be rectangular areas. So in those objects the source and destination areas are defined in single
attributes called srcrect and dstrect, which take four arguments to specify the bounding (left-top and right-bottom
corner) cells of the rectangles.

Hue Rotation
Just to add a little additional color variety, we've placed a jit.hue object between the two jit.matrix objects. (jit.hue is
described in detail in Tutorial 7.)

In the preset object, click on preset 8 to see jit.hue in action.

Modify the hue angle

This preset turns off usedstdim, but keeps usesrcdim on, and keeps interpolation on in jit.matrix to blur the expanded
image. The automated process in the patcher rotate subpatch continually rotates the hue angle of jit.hue.
Double-click on the patcher rotate object to see the contents of the subpatch.
The contents of the [rotate] subpatch

The value coming in the right inlet provides a time, in milliseconds, to complete a 360 hue rotation. When a 1 comes in the
left inlet, the number 360 is combined with that time value to instruct the line object to go from 0 to 360 in that amount of
time, sending out a new angle value once every 50 milliseconds. Note that the first typed-in argument of the line object
contains a decimal point. This instructs line to send out float values rather than ints, for greater precision (and because the
hue_angle message of jit.hue expects a float argument). When line reaches 360, its right outlet sends out a bang. We use
that bang to set the internal value of line back to 0, then we re-bang the pack object to start the next rotation. When a 0
comes in the left inlet, the sel 1 object passes it directly to line to stop line and reset the hue angle to 0.
Close the [rotate] subpatch window.

In the preset object, click on preset 9. This combines virtually all of the automation and image -manipulation techniques of
the patch. The changes of destination dimensions of jit.matrix are set to 200 ms this time, creating a more rapid rhythmic
effect.

Full Screen Display


When you've got your Max patch creating just the images that you want, and you want to display your results in a somewhat
more elegant way, you can instruct jit.window to fill your entire screen. jit.window has an attribute called fullscreen; when
fullscreen is on, the jit.window uses the entire screen as its display area. You can also use the hidemenubar message to
Max to hide the menu bar (see "Messages to Max" in the Topics section of the Max documentation for details).

There are a few things to remember about using the fullscreen capability of jit.window.
First of all, once you have filled your screen with an image (and especially if you have also hidden the menubar), you will no
longer be able to use your mouse to turn fullscreen off. So you will need to program into your Max patch some method of
returning the fullscreen attribute to 0.

Secondly, only one jit.window can fill any one screen at any one time. If you have more than one jit.window object vying for
access to the full screen, the jit.window object that has most recently had its fullscreen attribute set to 1 will fill the screen.
Also, even when a jit.window is fullscreen, its resolution is determined by its actual dimensions (that is, by the arguments of
its rect attribute). So if the rect attribute describes a 320x240 rectangle, that will be the resolution of your image, even
though your screen dimensions are much greater than that.

At the bottom of our patch, we've included the capability to turn the fullscreen attribute of jit.window on and off (and
hide/show the menu bar) with the space bar of your keyboard.

Using the space bar to switch the window to full screen display

Try toggling fullscreen on and off with the space bar.

For a more abstract visual effect, try importing the colorswatch.pict image into the jit.matrix at the top of the patch,then
try the different presets.

In this tutorial, we've used a still image as our source material so that you could easily see the effects being demonstrated,
but there's no reason that you couldn't use a video (from jit.qt.movie or some other video source) as your basic material.
(You might want to copy the contents of this patch to a new Patcher window and modify the top-left part of it to try that
out.)

Summary
There are several ways to isolate and reposition certain data in a matrix. The dim attribute of jit.matrix sets the actual
dimensions and size of the matrix. By turning on the usesrcdim and usedstdim attributes of jit.matrix, you can instruct it
to use a particular portion of its input and output matrices, which are referred to as the "source" and "destination" regions of
the matrix. You specify the cell boundaries of those regions with the srcdimstart and srcdimend attributes (to set starting
and ending cells as the boundaries of the source region) and the dstdimstart and dstdimend attributes (for the destination
region). These attributes do not change the actual size of the matrix, but they specify what part of the input matrix will be
passed out in what part of the output matrix (when usesrcdim and usedstdim are on).If the source and destination regions
are different in shape or size, jit.matrix will either expand or contract the source region to fit it in the destination region.
This results in either duplication or loss of data, but can provide interesting stretching or pixelation effects. The source and
destination regions can be altered dynamically with numbers provided by some other part of your Max patch, for interactive
or automated modification of the size, shape, and position of the image.

When the interp attribute is on, jit.matrix interpolates (provides intermediate values) between values when a dimension of
the destination region is greater than that of the source region. This smooths out pixelation effects, and blurs the changes
between values in adjacent cells.

The jit.window object displays whatever size matrix it receives, using whatever display rectangle has been specified for it in
its rect attribute. If the size of the incoming matrix differs from the size of the display area, the image will be expanded, or
contracted, or distorted by jit.window. This, too, can be used for stretching and pixelation effects. jit.window also has an
interp attribute which, when turned on, smooths out the pixelation caused by this expansion and stretching.

To fill the entire screen with an image, you can turn on jit.window's fullscreen attribute, and you can hide the menu bar
with a ;max hidemenubar message. (Just remember to leave yourself some way to get your Patcher window back in the
foreground.)

We've demonstrated the techniques of resizing, repositioning, flipping, and interpolating matrix data to create visual effects
such as stretching, distorting,blurring, and pixelation.

See Also
Name Description
jit.hue Rotate hue
jit.matrix The Jitter Matrix!
jit.qt.movie Play or edit a QuickTime movie
jit.window Display data in a window
line Generate timed ramp
pack Create a list
pak Output a list when any element changes
patcher Create a subpatch within a patch
preset Store and recall settings
random Generate a random number
Image Rotation
Tutorial 15: Image Rotation
Rotating and Zooming with jit.rota
Jitter provides an easy way to rotate an image, and/or zoom it in or out, with an object called jit.rota. Rotation and zoom
are common and useful video effects, and by combining them in different ways in jit.rota you can also achieve a variety of
kaleidoscopic effects. jit.rota takes a matrix of video data (or any other sort of image) in its inlet, and sends out a version
that has been zoomed, rotated, and otherwise distorted based on the settings of the object's attributes.

Basic Rotation
Open the tutorial patch 15jImageRotation in the Jitter Tutorial folder. The QuickTime video dishes.mov is read into the
jit.qt.movie object automatically by a bang from loadbang. To see the video, click on the Display toggle to start the
metro.

The video is a three-second left-to-right camera pan over a set of dishes. However, the loop attribute of the jit.qt.movie
object has been initialized to 2, so the movie loops back and forth, giving the illusion of a back-and-forth pan.

Note: Many attributes of Jitter objects use only the arguments 1 and 0 to mean "on" and "off", so it's reasonable to
assume that the loop attribute of jit.qt.movie is the same. While it's true that loop 0 turns looping off and loop 1
turns it on, loop 2 causes the video to play forward and then play backward when it reaches the loopend point, rather
than leaping to the loopstart point.

The theta attribute of jit.rota determines the angle of rotation around a central anchor point.
Drag on the Rotation Angle number box to rotate the video. Positive (or increasing) values cause counter-clockwise
rotation, and negative (or decreasing) values cause clockwise rotation. The angle of rotationa.k.a. the angle (theta)is
stated in radians. A value of 0or any multiple of 2 (i.e., 6.283185)is the normal upright positioning. A value of (i.e.
3.141593)or any odd multiple of is the fully upside-down position. Experiment until you understand the relationship
between the theta values and the behavior of jit.rota.

Technical Detail: jit.rota does a lot of internal calculation using trigonometry to determine how to rotate the image. If
you're not a trigonometry buff, you might not be used to thinking of angles in terms of radians. In everyday
conversation we more commonly use degrees, with a full rotation being 360. In trigonometry, it's more common to
use radians, where a full rotation equals 2 radians. That's because a circle with a radius of 1 has a circumference of
exactly 2, so you can refer to an angle by referencing the point where it would intersect the unit circle. (For example if
you started at a point on the unit circle and traveled a distance of exactly /2 around the circumference, you would end
up at a 90 anglei.e. an angle of /2 radiansfrom where you started, in reference to the circle's center.)

Also, in trigonometry we consider a positive change in angle to be a counter-clockwise rotation around the unit circle,
whereas in everyday life you might more commonly think of a clockwise motion as being intuitively "positive" or
"increasing" (like the passage of time).

So, to convert a clockwise rotation in degrees into the same rotation in radians, you would need to multiply the degree
angle by 2, then divide by 360.

Automated Rotation
Besides rotating the image by hand, you can also write an automated process in Max that will supply continually changing
rotation angles. In the previous chapter we wrote a subpatch called rotate that used the line object to increase the angle of
hue rotation continually from 0 to 360. In this chapter we do something similar, but this time we use the bang from the
metro that's displaying the movie to increase the angle of rotation. To keep it "user-friendly" we show the user degrees of
angle rotation rather than radians (we convert degrees to radians inside the subpatch), and we also display the rotation speed
as "rotations per second."

In the number box labeled Degrees per bang, enter the number 6. This will cause the rotation angle to increase by 6
degrees with each bang from the metro. Since the metro sends out a bang 20 times per second (once every 50 ms), we
know that we can calculate the number of rotations per second by the formula d*20/360that is, d/18where d is the
degrees of angle increase per bang. Now click on the toggle marked On/Off to begin the automated rotation.
Double click on the patcher rotate object to see the contents of the subpatch.

Automated rotation in the [rotate] subpatch

We convert what the user specifies as "degrees per bang" into an amount in radians, by multiplying the degrees by 2 and
dividing by 360. (See the Technical Detail sidebar above.) When a bang comes in the left inlet, if rotation is turned on then
the bang gets passed through and it causes an increase of angle rotation to be added into the accum object. Note that a
negative "degrees per bang" amount works fine, too, and causes a counter-clockwise rotation of the image. When the total
rotation angle exceeds 2 (or -2), we use a modulo operation to bring it back into range (resetting the value in the accum
object) before sending it to the outlet. When rotation gets turned off, we detect that fact with a sel 0 object, and reset the
theta angle to 0.

Close the subpatch window. Click on the On/Off toggle to stop the automated rotation.
Zoom In or Out
The other main feature of jit.rota is its zooming capability. The amount of zoom is determined by jit.rota's zoom_x and
zoom_y attributes. These permit you to zoom in or out in the horizontal and vertical dimensions independently; or you can
zoom both dimensions simultaneously by changing both attributes at once.

Drag on the number box labeled Zoom to zoom in and out. Values greater than 1 expand the image (zoom in), and values
less than 1 shrink the image (zoom out). You can change the zoom of the x and y dimensions independently by entering
values directly into those number boxes. (Negative zoom values flip the image as well as resize it.)
When we zoom in on the imagesay, with a zoom value of 2we still retain reasonably good image quality because we've
turned jit.rota's interp attribute on with an interp 1 message. If you turn interp off, you will get pixelation when you zoom
in. When you're zooming out, interp has no appreciable effect, so it's pretty much a waste of the computer's time. (See
Tutorial 14 for a discussion of pixelation and interpolation.) However, interpolation does improve the look of rotated images,
even when they've been shrunk by zooming out.

Beyond the Edge


Set the zoom of both dimensions to some small value, such as 0.25.

When the image does not fill the entire display area because of shrinking or rotation, jit.rota has to decide what to do with
the rest of the matrix that lies outside the image area. At present jit.rota is setting all the cell values outside the image area
to 0, making them all black. The way that jit.rota handles the cells that lie outside the image boundaries is determined by its
boundmode attribute. The different available boundmode settings are presented in the popup menu labeled Space outside
the image in the upper-right corner of the patch. We initialized the boundmode value to 1, which instructs jit.rota to clear
all the outlying cells. Here is the meaning of each of the boundmode settings:

0Ignore: Leave all outlying cells unchanged from their previous values.

1Clear: Set all outlying cell values to 0.

2Wrap: Begin the image again, as many times as necessary to fill the matrix.

3Clip: For all the outlying cells, continue to use the values of the boundary cells of the image.

4Fold: Repeat the image, flipped back in the opposite direction.


For special effects when the image is zoomed out, try setting the boundmode attribute to 2 (wrap) for a "Warhol"
duplicate image effect, or 4 (fold) for a kaleidoscope effect.

Now try turning the automated rotation back on, to combine rotation and zoom, and modify the different parameters
(Degrees per bang, Zoom, and Space outside the image).

When you have finished experimenting, turn off the automated rotation and return the zoom attributes (zoom_x and
zoom_y) to 1.

Some AdjustmentsAnchor Point and Offset


Up to now we've been using the center of the image as the center point of the rotation. However, you can actually choose any
point around which to rotate the image. The central anchor point of the rotation is set with the anchor_x and anchor_y
attributes. Right now those attributes are set to 160 and 120, but you can change them in the number boxes labeled Anchor
point.

Try different anchor points, and drag on the Rotation Angle number box to see the effect. Some anchor point settings you
might want to try are 0,0 or 40,30 or 160,120 or 320,240. You might want to set the boundmode attribute to 1 so that
you can see the effects of different rotations more clearly. Note that the anchor_x and anchor_y values are specified relative
to the upper-left corner of the matrix, but they may exceed the bounds of the matrix's dimensions.

In addition, you can move the image to a different location in the output matrix after zooming and rotation take place, using
the offset_x and offset_y attributes.

To see this most effectively, first click on the message box above the pvar object in the lower right corner of the patch.
This will set the rotation angle, boundary mode, zoom, and anchor points back to the settings we used at the outset of this
chapter. (We have given names to the relevant user interface objects so that we can communicate with them via pvar.) Now
set the Zoom number box to some value between 0 and 1, to zoom out on the image.

Use the Location offset number boxes to move the image around by changing the offset_x and offset_y values. Try this in
conjunction with boundmode 4, to see its utility in the "kaleidoscope" mode.

When you have finished, reset the Location offset values to 0.

Rotary Control
We've devised one more way for you to rotate the image.

Click in the jit.pwindow display object and, with the mouse button held down, drag in a small circular motion around the
center of the object.
jit.pwindow tracks your mouse movements and, as long the mouse button is down, it sends coordinate information (and
other mouse information) out its right outlet in the form of mouse messages. The first two arguments of the mouse
message are the x and y coordinates of the mouse, relative to the upper left corner of jit.pwindow. We use those coordinates
to calculate the angle of the mouse relative to the center of the jit.pwindow, and we send that angle to jit.rota as the
argument to the theta attribute.

You can use the mouse location in jit.pwindow as control information

Technical Detail: Do you really want to know how we did that calculation? If so, read on.

If we think of the center point of the jit.pwindow as the origin point 0,0, and we think of the current mouse location
relative to that as being a point along a circle around the origin, then we can describe a right triangle based on those
two points. By taking the arctangent of the mouse's coordinates y/x, we get the angle of the mouse relative to the center
of jit.pwindow.

So we take the incoming x and y coordinates, and the first thing we do is convert them so that they're relative to the
center of the jit.pwindow. We do that by subtracting 160 from the x dimension coordinate (so the x values will now go
from -160 to 160) and multiplying the y coordinate by 1 (so values will increase as we go up, instead of down) then
adding 119.5 to it. (If we added exactly 120, then every time we had a y coordinate of 120 from jit.pwindow we'd be
trying to divide by 0 in expr, which is an undefined mathematical operation.) Once we have converted the x and y
coordinates, we take the arctangent of y/x to get the angle in radians, then multiply that angle value by -1 to make
clockwise rotation of the mouse cause clockwise rotation of the image.

This method only works within a 180 span, because the arctangent function can't tell the difference between a mouse
location and its opposite point on the circle. (The calculation of y/x will be the same for both points.) So, every time the
y coordinate of the mouse goes into the bottom half of the jit.pwindow, we add an offset of - to the theta angle to
distinguish those locations from their counterparts on the opposite side. (That's the last part of the expression.)

Note that this expression only works relative to the point 160,120 in the jit.pwindow. If we wanted to make an
expression that works for the central point of any size jit.pwindow, we'd need to get the jit.pwindow's dimensions
with a getsize message, and use the size values as variables in our expression. As the math books say, "We'll leave
that as an exercise for the reader."

Summary
The jit.rota object provides an easy way to rotate an image with its theta attribute, specifying an angle of rotation, in
radians. It also provides an easy way to zoom in and out on an image with its zoom_x and zoom_y attributes. You can
change the central point of the rotation with the anchor_x and anchor_y attributes, and you can move the resulting image
in the output matrix with the offset_x and offset_y attributes. You can change the way that jit.rota treats the matrix cells
that lie outside of the resulting image with the boundmode attribute. Using all of these capabilities in combination, you can
get image-duplication and kaleidoscope effects in addition to simple zoom and rotation.

Zooming and rotation involve some rather intensive internal calculation by jit.rota, so these operations make substantial
demands on the computer's processor. If you're curious, the formulae for these calculations are in the jit.rota.help file. There
are additional attributes, not covered in this tutorial, that give you access to virtually every coefficient in the rotation
formula, presenting you even more possibilities for distorting and rotating the image. These, too, are shown in jit.rota.help.

To manage the control of so many attributes at once, you can devise automated Max processes to generate attribute values,
and/or interactive controls to change the values with gestures.

See Also
Name Description
accum Store, add to, and multiply a number
expr Evaluate a mathematical expression
if Conditional statement in if/then/else form
jit.pwindow Show data in a patcher
jit.qt.movie Play or edit a QuickTime movie
jit.rota Scale/rotate in 2D
split Look for a range of numbers
Using Named Jitter Matrices
Tutorial 16: Using Named Jitter Matrices
In this tutorial we'll learn how to use the name attribute of the jit.matrix object to write matrix data from multiple sources
into the same matrix. We'll also look at how to scale the size of matrices when they are copied into a new matrix, and how to
use the Max low-priority queue to de-prioritize Max events in favor of more time-consuming tasks .
Open the tutorial.

The tutorial patch is divided into five colored regions. The middle (light blue) region contains two jit.qt.movie objects. A
loadbang object reads two movies (rain.mov and traffic.mov) into the jit.qt.movie objects when the patch is opened:

Reading in the movies

Unlike the tutorial patches we've looked at before, the jit.qt.movie objects in this patch use send and receive objects to
communicate with the rest of the patch. The receive objects named m1 and m2 forward messages to the two jit.qt.movie
objects. The output matrices of the two objects are then sent (using send objects) to receive objects named movie1 and
movie2 elsewhere in the patch.

The yellow region at the top of the patch contains the metro object that drives the Jitter processes in the patch:

The metro object drives one of the two message boxes

Click the toggle box to start the metro. The three jit.pwindow objects in the patch will start to display an image.

Order of Importance
The metro object goes through a Ggate object and an object called jit.qball (about which we will have something to say
later) into a gate object. The bang messages sent by the metro are routed by the gate to one of two message boxes. Our
final output matrix (in the jit.pwindow at the bottom of the patch) will change depending on which message box gets a
bang.

Click the two message boxes attached to the left inlet of the gate (1 and 2). Notice how the jit.pwindow at the bottom
changes:
The final output matrix changes depending on the message ordering of the patch.

The two message boxes both send bang messages to the same three named receive objects (m1, m2, and output). The
difference between the two is the order in which they send the messages. The lefthand message box (driven by the metro
when the gate is set to 1) sends the first bang to the jit.qt.movie object (with the rain movie). Finally, the jit.matrix object
at the bottom of the patch receives a bang, causing our final matrix to be sent out. The righthand message box (driven by
the metro when the gate is set to 2) reverses the order of the two bang messages driving our jit.qt.movie objects (the left
jit.qt.movie outputs a matrix first, followed by the right jit.qt.movie object).

The order in which these messages occur only becomes relevant when we look into what happens between the two
jit.qt.movie objects and the final jit.pwindow object.

What's in a Name?
Once our jit.qt.movie objects receive their bang messages, they output a matrix to the send objects below them, which in
turn pass their matrices over to receive objects named movie1 and movie2. The receive objects (in two identical regions at
the right of the patch) are connected to jit.pwindow objects as well as two named jit.matrix objects:

The named jit.matrix object

Both of the jit.matrix objects at the right of the patch (as well as the jit.matrix object at the bottom of the patch above our
final jit.pwindow) have a name. The name attached to all three of these objects is composite. The result of this is that all
three of these jit.matrix objects share the same matrix data, which is contained in a Jitter matrix called composite.
Once we know that our two jit.qt.movie objects write data into the same Jitter matrix (via two separate jit.matrix objects
sharing the same name) we can understand why the ordering of the bang messages is important. If the left jit.qt.movie
sends out its matrix first, it writes data into the composite matrix, followed by the right jit.qt.movie, which writes data into
the same matrix. If the two matrices write to any cells in common (see below), the matrix that gets there last will overwrite
any data that was in those cells before.

Important Note: If you are ever unsure about the order in which things are happening in your Max patch, you can do a
Trace of the patch to see the way in which your patch executes. If you choose the Enable Debugging command from
the Debug menu, and then turn on the metro object, you can step through the patch with the Auto Step command to
see how it executes.

The Destination Dimension


The two jit.matrix objects on the right of the tutorial patch have their usedstdim attribute set to 1. This allows us to scale
the matrices sent by our jit.qt.movie objects so that they only write to a certain region of the composite Jitter matrix.
Play around with the number boxes labelled x origin, y origin, and scale connected to the two subpatchers labelled p
coords. Notice how you can move and resize the two images from the jit.qt.movie objects in the composite matrix.

Picture within a picture

The subpatches p coords contain identical helper patches to format the dstdimstart and dstdimend attributes for the
jit.matrix objects. These attributes specify the upper left and lower right coordinates, respectively, to use when copying data
into our composite Jitter matrix. The usedstdim attribute simply tells the jit.matrix object to use those attributes when
copying data. When usedstdim is set to 0, the incoming matrix is scaled to fill the entire matrix referred to by the jit.matrix
object.

Scaling the input matrices before the are written into our shared matrix

The three numbers that we send into the subpatches get formatted by the Max objects inside to generate a list that describes
the upper left and lower right areas of the output matrix which we want to fill with our input matrix. The message box
before the outlet uses $ substitution to replace the relevant arguments for the attributes with numbers from the list.

The last thing that happens after our two matrices have been written into the composite matrix is that a bang is sent to the
receive object named output:

The final result

The region at the bottom of the tutorial patch contains a third named jit.matrix object. The bang sent by the metro goes
through a trigger object that sends a bang to the jit.matrix (causing it to output its matrix to the jit.pwindow) followed
immediately by a clear message. The clear message erases (zeroes) all the cells in the Jitter matrix named composite. If we
didn't clear the matrix, changing the dstdimstart and dstdimend attributes of any of the jit.matrix objects could result in
cells left over from a previous output location of our movies.
Jumping the Queue
The jit.qball object at the top of the patch provides an invaluable service in the event that Max can't keep up with our
demands. The metro object (which is sending out bang messages every 50 milliseconds) is driving three separate operations
(writing the two matrices from the jit.qt.movie objects into our named Jitter matrix, as well as displaying the data and
clearing the matrix so we can start over). The jit.matrix object writes data into its internal Jitter matrix (in this case our
named composite matrix) in a way that allows it to be usurped by a subsequent message. It also allows other Max events
that are scheduled at a higher priority to happen while it works on a task. This makes it possible to display the matrix (or
write more data into it) before the previous operation has finished, causing flicker and other unexpected results. The jit.qball
object places messages input into the object at the back of Max's low priority queue where they too can be usurped by
another message. This way, if jit.qball gets a bang from the metro object before all the current Jitter tasks are complete, it
will wait until everything else in the low priority queue is finished before sending out the bang. Similarly, if another bang
comes along before that first bang has been sent (i.e. if it takes more than 50 milliseconds for the rest of the patch to do
everything), the first bang will be usurped (jettisoned) in favor of the second. This allows you to set a maximum hypothetical
rate of events in a Max patch without having to worry about events accumulating too rapidly for the objects in the patch to
keep up.

Click on the Ggate object labeled jit.qball bypass switch so that the output of the metro object bypasses the jit.qball
object. The composite image in the jit.pwindow at the bottom will start to flicker, indicating that messages are arriving out
of order.

Normally, sending a bang to a Jitter object will usurp an already pending event in that object (e.g. a bang that has already
arrived but hasn't been dealt with yet by the object). However, the jit.qball object gives us this kind of control over multiple
chains of Jitter objects, automatically usurping events ("dropframing") to guarantee that messages arrive in the right order.

Summary
By giving a single name to multiple jit.matrix objects, you can write into and read from a common Jitter matrix in different
parts of your patch. You can scale a Jitter matrix while copying it into the internal matrix of a jit.matrix object by using the
dstdimstart and dstdimend attributes and by setting the usedstdim attribute to 1. The jit.qball object allows you to de-
prioritize Max events by placing them in the low-priority queue where they can be usurped by subsequent events if there
isn't enough time for them to execute.

See Also
Name Description
jit.matrix The Jitter Matrix!
jit.pwindow Show data in a patcher
jit.qball Convert messages at scheduler time to low priority
jit.qt.movie Play or edit a QuickTime movie
Feedback Using Named Matrices
Tutorial 17: Feedback Using Named Matrices
This tutorial shows a simple example of using named jit.matrix objects in a feedback loop. We'll use a matrix of random
values to seed an iterative process (in this case, Conway's Game of Life).
Open the tutorial.

The tutorial patch generates an initial matrix of randomized values with the jit.noise object:

The jit.noise object

The jit.noise object generates a Jitter matrix full of random values. The dim, planecount, and type attributes of the object
determine its output matrix (in this instance, we want an 80 x 60 cell matrix of one-plane char data). Our random cell
values (which are initially in the range 0 -255) are then set to true (0) or false (255) by the jit.op object. The > operator to
jit.op takes the value from the number box (arriving at the right inlet of the object) and uses it as a comparison operator. If
a cell value is below that value the cell's value is set to 0. Otherwise the cell is set to 255. Sending a bang to jit.noise will
generate a new random matrix.

Try changing the number box attached to the jit.op object. Click the button attached to the jit.noise object to generate a
new matrix each time. Notice how higher comparison values yield fewer white (255) cells. The small jit.pwindow below the
jit.op object shows you the random matrix. The one-plane matrix data is correctly interpreted by the jit.pwindow object as
grayscale video.

Jitter Matrix Feedback


The quantized noise we've generated at the top of our patch goes from the jit.op object into a jit.matrix object with the
name of cellular:

Two named jit.matrix objects in a feedback loop

This jit.matrix object, which receives bang messages from a metro object at the top of the patch, is connected to an object
called jit.conway, the output of which is hooked up to another jit.matrix with the same name (cellular) as the first. The
result of this is that the output of the jit.conway object (whatever it does) is written into the same matrix that its input came
from, creating a feedback loop.

Start the metro object by clicking the toggle box. The jit.pwindow at the bottom of the patch will show you the output of
the jit.conway object.
If you want to start with a fresh random matrix, you can always copy a new matrix into the feedback loop by clicking the
button attached to thejit.noise object. The matrix from the jit.op object will go into our shared cellular matrix and will be
used in the feedback loop.

The Game of Life


The jit.conway object performs a very simple cellular automata algorithm called the 'Game of Life' on an input matrix.
Developed by John Conway at Princeton University, the algorithm simulates cycles of organic survival in an environment
with a finite food supply. The cells in the matrix are considered either alive (non-0) or dead (0). Each cell is compared with
the cells surrounding it in space. If a live cell has two or three live neightbors, it stays alive. If it has more or less than that
number, it dies (i.e. is set to 0). If a dead cell has exactly three live neighbors it becomes alive (i.e. is set to 255). It's that
simple.

Every time the jit.conway object receives an input matrix it performs one generation of the Game of Life on that matrix.
Therefore, it makes sense to use the object inside of a feedback loop, so we can see multiple generations of the algorithm
performed on the same initial set of data.

For example, the initial random matrix:

Some random matrix values

Generates the following matrices in the first four iterations through the jit.conway object:

The first four generations of the Game of Life performed on the dataset above

After seeding the feedback loop with a random matrix, you can turn on the metro object and watch the algorithm run! The
Game of Life is designed in such a way that the matrix will eventually stabilize to either a group of self-oscillating cell units
or an empty matrix (a dead world). In either case you can just bang in a new set of numbers and start all over again.

Summary
You can use the name attribute of the jit.matrix object to create feedback loops in your Jitter processing. By using two
jit.matrix objects with the same name at either end of an object chain, you create a patch where the output of the chain gets
written to the same Jitter matrix as the input comes from. The jit.noise object generates matrices of random numbers of any
type, dim, or planecount. The jit.conway object, which works best within such a feedback loop, performs simple cellular
automatation on an input matrix.

See Also
Name Description
jit.conway Play Conway's game of life
jit.matrix The Jitter Matrix!
jit.noise Generate white noise
jit.op Apply binary or unary operators
jit.pwindow Show data in a patcher
Iterative Processes and Matrix Re-Sampling
Tutorial 18: Iterative Processes and Matrix Re-Sampling
This tutorial demonstrates a more complicated example of when to use named jit.matrix objects, as well as how to use
jit.matrix objects to upsample and downsample an image.

Open the tutorial.

The upper left-hand corner of the patch contains a jit.qt.movie object that has a still image (the file fuzz_circle.jpg) loaded
into it when the patch opens.

Read the image

Start the metro object by clicking the toggle box above it. You should see an image appear in thejit.pwindow in the lower
right of the tutorial patch:

Our little comet

The fuzz_circle.jpg file contains an image of a white circle with a black background, which is being scaled in size to appear as
a small circle inside of our final matrix.

The real fuzz circle

Getting Drunk
The top part of the patch writes the image from the jit.qt.movie into the first jit.matrix object in the chain. A bang
generated by the bangbang object changes the dstdimstart and dstdimend attributes of the jit.matrix object with each
frame, randomly varying the coordinates using Max drunk objects. Note that our first jit.matrix object has its usedstdim
attribute set to 1, so that it will scale the input matrix:
The drunk part of the patch

This first jit.matrix, therefore, simply serves to scale the circle image to fit in a small (80 by 60) region of our output matrix.
Note that the message box that formats the coordinates for the scaled image also clears the matrix with every frame (with a
clear message), so that there are no artifacts from a previously written image. The Max drunk objects vary the placing of the
circle, causing it to jitter around (no pun intended).

Click somewhere in the jit.pwindow in the lower right corner of the patch. The circle will jump to the position you clicked,
and begin to move from there.

The result of a mouse click in the jit.pwindow is sent to the receive object with the name winclick. This message is then
stripped of its selector (mouse) and the first two elements (the x and y position of the mouse click) are extracted by the
unpack object. These coordinates are then used to set the new origin for the drunk objects.

The Feedback Network


Once our circle image has been scaled and placed appropriately by the jit.matrix object, our patch enters a feedback chain
that centers around a pair of jit.matrix objects sharing a matrix named blurry:

The feedback loop in our patch

This section of the patch contains four jit.matrix objects (not including the one at the top which scales down the circle
image). Two of the objects share a name (blurry) and are used simply to store and retreive previous matrices generated by
the rest of the patch. The topmost jit.matrix object sends its matrix to the rightmost inlet of the first jit.op object in the
patch. In addition, it sends a bang to the first namedjit.matrix object using a bangbang object, causing it to output its
stored matrix (called blurry). This matrix eventually ends up in the left inlet of the jit.op, where it is then displayed (by the
jit.pwindow) and multiplied by a scalar (the second jit.op object). It eventually overwrites the previous blurry matrix (by
going into the bottom named jit.matrix object). Without worrying about what the intermediate Jitter objects do, you can see
that the blurry matrix will hold some version of the previous 'frame' of our circle image:
A scaled-down and illustrated map of our patch

The new and old images are combined by the first jit.op object using the max operator. The max operator compares each
cell in the two matrices and retains the cell with the highest value. The second jit.op object (with the * operator) serves to
darken our image by multiplying it by a scalar (set by the number box on the right of the patch that is sent to the receive
object named fb):

The feedback amount sets how much the image is darkened before being stored in the blurry matrix.

Change the feedback amount of the patch by playing with the number box labeled Feedback on the right of the patch.
Notice how the trails after the circle increase or decrease when you move the circle by clicking in the jit.pwindow, depending
on how the feedback amount is set.

Downsampling and Upsampling


The final step in our image processing algorithm concerns the part of the patch in between the first named jit.matrix, which
sends out the matrix saved there during the previous frame by the jit.matrix at the bottom, and the first jit.op object, which
composites the previous matrix with the new one:

Using jit.matrix objects for resampling of an image

The two jit.matrix objects colored green in the tutorial patch are used to resample the blurry image matrix coming out of
the jit.matrix object above them. The first of the two jit.matrix objects has its dim attibute set to 4 x 4cells. This size can be
changed by setting the attribute with the number box at the top left with the caption Pixelation. This number gets sent to
the receive object named dim above the jit.matrix object.

Change the pixelation of the trails

Change the number box labeled Pixelation in the blue region of the tutorial patch. Notice how the circle trails change.
By downsampling the image matrix, the jit.matrix object copies the 320x 240 matrix from its input into a much smaller
matrix, jettisoning excess data. The result is a pixelation of the image that you can control with the dim of the matrix.

The second jit.matrix object upsamples the matrix back to a 320x 240 matrix size. This is so that when subsequent Jitter
objects process the matrix, they will have a full resolution image to work with and will output a full resolution matrix.

The jit.streak object adds a nice effect to the pixelated trails by randomly 'streaking' cells into their neighbors. The prob
attribute of jit.streak controls the likeliness that any given cell in the matrix will be copied onto a neighboring cell. Our
jit.streak object has a prob attribute of 0.5, so there's a 50% chance of this happening with any given cell.

Technical Detail: By default, jit.streak copies cells towards the left. Changing the direction attribute will alter this
behavior. There is also a scale attribute that determines the brightness of the 'streaked' cells as compared to their
original values. The help patch for jit.streak explains more about how the object works.

Our effects chain with intermediate jit.pwindow objects to show the processing

Summary
Pairs of named jit.matrix objects can be used effectively to store previous iterations of a Jitter process. These techniques can
be used to generate video delay effects by combining the previous matrix with the current one using matrix compositing
objects such as jit.op. You can also use jit.matrix objects to resample an image (using the dim attribute), both to perform
an algorithm more efficiently (the smaller the matrix, the faster it will be processed by subsequent images) and to create
pixelation effects. The jit.streak object performs random cell streaking on an input matrix by copying cells over to their
neighbors according to a probability factor (set by the prob attribute).

See Also
Name Description
drunk Output random numbers within a step range
jit.matrix The Jitter Matrix!
jit.op Apply binary or unary operators
jit.pwindow Show data in a patcher
jit.qt.movie Play or edit a QuickTime movie
jit.streak Probability lines
Recording QuickTime movies
Tutorial 19: Recording QuickTime movies
This tutorial shows how you can record a single matrix or a sequence of matrices to disk as a QuickTime movie. We'll
demonstrate the use of the jit.qt.record object for recording in real time and non-real time. Along the way, we'll also show
you how to adjust some of the settings of the output movie.

Like most Jitter objects, the jit.qt.record object operates according to an event-driven model rather than a time-driven one -
- frames sent to a record-enabled jit.qt.record object are appended to the movie in progress as "the next frame" based on
the timing characteristics of the output movie, without regard for the relative time between the arriving frames. This results
in very smooth movies with consistent timing between frames, but it requires some preparation before recording.

The jit.qt.record object also offers a time-driven (realtime) method of recording in addition to the default mode
described in this tutorial. Although the realtime mode might seem simpler to use, the recorded output won't be as
smooth because frames of the incoming movie will usually be dropped fairly regularly during recording. You can set the
time-driven mode for the jit.qt.record object by using the realtime message, but it is quite different from the realtime
operation described in this tutorial.

Your mileage may vary


Each and every matrix that arrives at a recording jit.qt.record object must be compressed before becoming part of your
output movie. The speed of this compression depends on several factors: the speed of your processor and your disk drive,
and -- most importantly -- the type of compression used (referred to as the codec, short for compression/decompression).
The examples in this tutorial will use the Photo-JPEG codec. It should yield fairly consistent results from machine to
machine without a lot of high CPU usage and disk access. On older or slower systems, it's possible that you'll notice some
timing inaccuracy with the first set of examples for this tutorial. If you do, don't worry; the second part of this tutorial will
show you how to achieve excellent results on even the most modest system by working in non-realtime mode.

On the clock
Open the tutorial.

The first example shows a very basic recording setup. Notice that the jit.qt.record object takes two arguments (320 and
240) that specify the width and height of any movies we record with this object.

A simple recording patch

Click the message box that says read countdown 15.mov to load a movie into the jit.qt.movie object, and start the
metro object by clicking on the toggle box connected to its inlet. You will see the movie's image appear in the jit.pwindow
object, since the jit.qt.record object passes any matrices it receives out its left outlet. (The jit.robcross object in this patch is
a simple edge detector that we're using to process the matrices passing through it).

Click the message box that says write 15. jpeg. to start writing the movie (we'll look at the contents of the message box
in more detail in a moment). A file Dialog Box will appear, prompting you for a file name. When you enter a valid name and
click the Save button, recording begins to the filename you've chosen (For the purposes of example, let's assume you've
named your movie myfilename.mov.). Click the stop message box to stop recording.
The jit.qt.record object sends a message out its right outlet after a write operation to confirm that the movie was successfully
written. Since we've connected that outlet to a print object in our patch , we can see the results by looking at the Max
Window. If everything went as expected, you should see print: write myfilename.mov 1 in the Max Window. If there was a
problem, the number after the filename will not be a 1.

Click the read message box attached to the jit.qt.movie object and read in the movie you just recorded. How does it look?
Let's examine the write message to the jit.qt.record object for a moment. The write message puts jit.qt.record into a
record-enabled mode. The actual recording doesn't begin until the object receives a matrix in its inlet. The write message can
take several optional arguments to specify a file name, frame rate, the codec type, the codec quality and the timescale for the
output movie. In this example we're only using two arguments (15. and jpeg) to specify the frame rate (15. indicates 15
frames per second) and the codec type (jpeg indicates Photo-JPEG) of the output movie. For a full description of all the
arguments for the write message, see the Object Reference entry for the jit.qt.record object.
Note that we have the metro object set to send a bang message every 66.67 milliseconds. This is done to match the input
movie's frame rate. If you change the metro object's rate and record a few more movies, you will see that a faster metro rate
causes the movie to be longer and slower, while a slower metro rate results in a shorter, faster movie. This happens because
of the event-driven model being used by jit.qt.record.
The second example patch is a little more complicated, but it has two important additions (and several minor ones).

Same idea, different patch

First, we're automatically detecting the frame rate of the original movie (using the getfps message), and using it to set both
the rate of the metro object driving jit.qt.record and the output movie's frame rate, as well. Let's look at that portion of the
patch in detail:

When a movie is successfully loaded into jit.qt.movie, the object sends the message read filename.mov 1 out its right
outlet (if the read operation is unsuccessful, the number will not be 1). We're using the route object to retrieve this message.
The unpack s 0 object breaks up the remaining elements of the message. We're not interested in the file name, only in the
success or failure of the read operation, so we've attached nothing to the left outlet of unpack, and attached a select object,
which tests for the integer 1, to the right outlet. If our read operation was successful, the select object will output a bang.
The bang is used to send the message getfps to jit.qt.movie, which will respond by sending the message fps [fps] out its
right outlet. The [fps] message element is a floating-point number representing the movie's frame rate. This value is sent
from the route object's middle outlet, and used to set the metro object's speed and the output movie's frame rate.
This patch includes a second improvement. Rather than locking the entire patch to the frame rate of the original movie,
we've added a jit.matrix object with thru turned off to "collect" the output of the patch, and we're using a second metro to
send it bang messages at the correct frame rate for jit.qt.record. This permits the rest of our patch to operate
independently, at as fast or slow a rate as we want, with only the very last part of the patch specifically timed to the recording
process.

Finally, we've added a neat crosshatching filter (the jit.hatch object) with its own editing control (the number box and the
grid $1 message box). You can use this to modify your movie while you're recording it and watch the effects on playback.
You can substitute any kind of Jitter object or patch you want at this point in the recording patch and modify what you
record in real time.

Off the clock


Both of the previous patches have a problem: under high processor loads, these patches will drop frames. In many cases, this
is not a problem, and the patches we've looked at are well suited to recording in any context, including live performance.

But how can we record a sequence in which every frame in an original movie has a corresponding frame in the output
movie? How do you render movies in Jitter so that, even under heavy processor or disk load, every processed frame is
captured?

There is a way. The jit.qt.movie object's framedump message offers a non-realtime playback mode that works perfectly
with jit.qt.record.
Scroll all the way down in the Patcher window to see the third example.

Non-realtime recording with framedump

On first inspection, the third example patch may not seem a lot more complicated than the previous one. But don't be fooled
-- this unassuming patch will bring even the speediest computer to its knees.

Click the message box countdown.mov to load a movie into the jit.qt.movie object, start the metro object by clicking on
the toggle box connected to its inlet and watch the jit.fpsgui object's framerate output display located at the bottom of the
patch. If you get more than 10 fps, you have a much nicer computer than we do.

While this patch runs slowly in real time, it does a great job of creating a QuickTime movie in non-realtime. Using the
jit.qt.movie object's framedump message and the jit.qt.record object, the patch will capture every frame of the original
movie, process it, and produce an output movie of identical length.

Here's how it works: the framedump message tells the jit.qt.movie object to stop playing its movie, and then sends each
frame out, one at a time. (N.B. You don't need to send a bang or outputmatrix message to the jit.qt.movie object for the
frames to be sent.) Because of the way the Max scheduler works, a new frame will not be sent until the previous frame has
been fully processed and recorded. Let's try it out.

Click on the toggle box connected to the inlet of the metro object to turn it off. (Sending a bang to jit.qt.movie during the
framedump operation will cause an extra frame to be sent, which is not what we want.) We've connected the button on the
top left corner of the patch to both the pack object that sends the write message, and the framedump message. Press the
button, enter a file name when the File Dialog appears, and wait for the movie to render. When the framedump is finished,
the jit.qt.movie object sends the message framedump done from its right outlet. The example patch uses that message to
trigger a stop message to jit.qt.record.
The example patch also takes advantage of the fact that the jit.qt.record object sends a matrix out its left outlet after
recording a frame. We're using that frame to trigger a bang message to a counter object that is driving the grid attribute of
the jit.hatch filter. This creates a repeatable sequence of processing changes that happen as the QuickTime movie is
captured.

Click on the "read" message box to open the movie you've just created. Turn on the metro to display the movie. Click on
the toggle box connected to the gate object to see your new movie. This switches the jit.qt.movie object's output directly to
the jit.pwindow, instead of through the processing objects.

Summary
The jit.qt.record object provides event-driven ways to record Jitter matrices as QuickTime movies. You can record the
output of a Jitter patch in real time as you manipulate your patch, or out of real time, in render-like operation. You can use
the jit.qt.movie object's framedump message to process an entire movie file without dropping any frames. This method lets
you record high quality movies regardless of the load being placed on your computer's processor.

See Also
Name Description
jit.fastblur Blur/sharpen using optimized algorithm
jit.hatch Perform crosshatch filtering
jit.matrix The Jitter Matrix!
jit.pwindow Show data in a patcher
jit.qt.movie Play or edit a QuickTime movie
jit.qt.record Record a QuickTime movie
jit.robcross Robert's Cross edge detection
jit.wake Feedback with convolution stage
Importing and Exporting Single Matrices
Tutorial 20: Importing and Exporting Single Matrices
This tutorial shows how you can export a single matrix to disk from Jitter. We'll demonstrate the variety of options available,
including QuickTime still picture formats, text and ASCII formats and Jitter's own .jxf file format.

In the previous Tutorial, we learned how to save a sequence of matrices as a QuickTime movieand we can save a single
matrix using the same techniques. Since the data that Jitter works with can describe much more than series of images, it
makes sense that there should be several additional options for exporting individual matrices.

Import and Export from the jit.matrix object


The jit.matrix object offers two types of single-matrix import/export: QuickTime movie and Jitter binary (.jxf). Both formats
permit import and export of a single matrix. We'll discuss both, starting with the movie format.

QuickTime export and import


The QuickTime movie format is identical to the format we learned about in the last tutorialRecording QuickTime Movies.
The only difference is that, in this case, an exported output movie will be exactly one frame long. We can also import a single
frame of a movie, regardless of the movie's length. The messages importmovie and exportmovie are used to import and
export a single matrix from the jit.matrix object. The exportmovie message conveniently uses the same format as the
jit.qt.record object's write message.

In fact, when you use the jit.matrix object's exportmovie message, the jit.matrix object is briefly creating an internal
instance of a jit.qt.record object, and sending a write message to it with the arguments you've specified for
exportmovie. Although that shouldn't change the way you think about it, it's pretty nifty.

Open the tutorial.

the jit.matrix objects importmovie and exportmovie messages

Click the message box that says read to load a movie into the jit.qt.movie object. Since we're only interested in a single
frame, there's no metro in the patch. You'll also notice that there is a new attribute set for the jit.qt.movie object
@autostart 0. Setting this attribute means that our movie will not begin playing automatically. We can choose a frame of
the loaded movie we want to export, using the number box connected to the message box containing the message frame
$1, bang.

Why are the colors all messed up? They're messed up because we're using the planemap attribute of jit.matrix to remap
the planes of the incoming movie from 0 1 2 3 (alpha, red, green, blue) to 0 3 2 1 (alpha, blue, red, green). We'll see why in a
few moments.

Click the message box exportmovie myframe.mov 30. jpeg to export the frame as a QuickTime movie. As with
jit.qt.record, we're specifying the frame rate and codec (30. and jpeg). We're also specifying a file name, myframe.mov.
The exportmovie message automatically closes the file after writing the frame to it.

To load the single frame we've just exported , we'll use the importmovie message. Since we want to be certain that we're
really importing the frame we just exported, we'll clear the jit.matrix object first. Click on the message box that says clear,
bang. This message clears the matrix and then outputs it to the jit.pwindow, which should now appear entirely black.
Now, click the message box that says importmovie, bang. A file Dialog Box should appear, and you should locate and
read myframe.mov. The movie should have been saved in the same folder as the Tutorial patch. If you can't find it there, use
the Finder's Find... command to locate the file on your disk drive. The frame you just exported should now be back in the
jit.pwindow. The importmovie message takes an optional first argument which specifies a file name.

You're probably wondering what that second importmovie message is for. If you try to import a multi-frame movie into
jit.matrix, the object assumes that you want the first frame, unless you specify a time value that you'd prefer. In this
example, we've asked for time value 600 whichis one second in from the beginning of a normal QuickTime movie
remember from Tutorial 4 that most QuickTime movies use a timescale of 600, which means they have 600 time values per
second.

Try reading another QuickTime movie by clicking on the message box importmovie 600, bang. The jit.pwindow should
now be showing a frame from one second into that movie. You'll notice that the colors in the frame are not switched around
this time. This is because we are importing an image matrix directly into the object. Since the jit.matrix object's planemap
attribute only affects matrices that arrive via its inlet, no plane remapping occurred.

Jitter binary export and import


Jitter offers its own binary format for single-matrix export, called .jxf. The Jitter binary format is simpler to use than the
QuickTime format, and .jxf stores your data without any of the data losses associated with the various codecs you need to
use with the QuickTime format. Additionally, the .jxf format supports matrices of all types, dimensions and planecounts,
whereas the QuickTime format is only capable of storing 4-plane char matrices (images).

using .jxf format with the jit.matrix object

The patch shown above uses the Jitter binary format, which is selected using the write and read messages. While it is very
similar to the previous example patch, there are some important differences:

The write message only takes a single argument that specifies the name of the output file. Since the .jxf format is always a
single matrix of uncompressed data, we don't need any other arguments.

The read message doesn't need a time argument (since a .jxf file will only have a single matrix in it). Like the importmovie
message, read will take an optional argument for the file name.

The read and write messages cause the jit.matrix object to send confirmation messages out the object's right outlet. We've
connected that outlet to a print object, so you can see those messages in the Max Window.

Both techniques described in this section are available to the jit.matrixset object as well, and function in similar ways.
Import and Export from the jit.qt.movie object
The jit.qt.movie object offers two export methods you can use to save movie frames as QuickTime still images, rather than
movies. The first method exports single frames as image files. The second method exports an entire movie as a sequence of
image files, called an Image Sequence.

You may find this way of working preferable if you're using images you generate with Jitter for page layout, or if you're using
the images in conjunction with other graphic processing software like Photoshop or GraphicConverter.

The jit.qt.movie object can export and import QuickTime movies in a number of non-movie formats. For the purposes
of this Tutorial, we're only going to cover still image export. For a more comprehensive listing of import and export
options available in jit.qt.movie, please consult the object's Object Reference entry and help file.

Exportimage
Let's start with the simpler of the two methods: the exportimage message to jit.qt.movie. Using exportimage, we can save
the current movie frame as an image file. This method allows you to save your image in one of several standard graphic
formats, including JPEG, PNG and TIFF.

the jit.qt.movie objects exportimage message

Click the message box read to read in a QuickTime movie. Use the number box to navigate to a frame you'd like to export
as a still image.

Click on the umenu object. The object contains a list of the still image file types available. Choosing one of these items will
send the exportimage message to jit.qt.movie (by way of the pak object), with your chosen file type as an argument. A file
Dialog Box will appear, where you can enter a file name for the image file you're about to create. The jit.qt.movie object will
automatically append the correct file name extension (.png, .jpg, .tif, etc.) to the filename when it exports the image, so you
don't need to add them. Click Save to continue.

That's it. To verify that your export was successful, look in the Max Window. The jit.qt.movie object sends the message
exportimage myfile 1 from its right outlet after a successful exportimage operation (myfile is the file name you chose). If
exportimage was unsuccessful, the number will not be 1. You can either reopen the file in Max, by reading it into
jit.qt.movie, or switch to the Finder and open it in your favorite image viewing application.

The exportimage message takes an optional int argument to call up the export Dialog Box. Click on the message box
exportimage 1 to see it. First, you'll be prompted for a file name. Then, before exporting the image file, the Dialog will
appear, where you have the option to change the file type, and set file type-specific options for the exportimage operation.

The full format of the exportimage message is exportimage [file name] [file type] [dialog flag]. All of the
arguments are optional. If you omit the file type and dialog flag, the exportimage operation will use the last file type
you specified. PNG is the default if there is no saved file type.

General Export from jit.qt.movie


We can also use jit.qt.movie to save an entire movie file as an Image Sequencea series of still images, one for each frame.
This process relies on a slightly more complicated export mechanism.

In QuickTime, every movie can potentially have a different set of available exportersfor example, you might want to export
the sound tracks in a QuickTime movies as CD audio or AIFF files. Or you may be able to export your Photo-JPEG video
tracks as a DV stream. Some movies might permit several image export formats, while others are limited to just a few.
Because of this potentially shifting landscape of options, we've attempted to make exporting in jit.qt.movie as flexible as
possible. And that added flexibility will require a little extra explanation.

generalized export from jit.qt.movie

Click the message box read garbage.mov, to read in that file. We're using this movie because it's only one second long.
You may use the number box to navigate around the movie, if you like.
Click on the message box getexporterlist. This causes jit.qt.movie to send a list of available exporter components from
its right outlet, preceded by the word exporterlist. Our patch breaks that list up and places the list into an umenu object for
easy access.

Click on the umenu to view the list. Our list contains entries like AIFF, BMP, FLC, HEURIS MPEG and several others. You
probably recognize several of the formats offered. Choose the Image Sequence item. This causes the message box
exporter $1 to send the Image Sequence exporter's index number (which is the same as its position in the umenu item list)
to jit.qt.movie.

Important Detail: Since each movie could potentially support different exporters, this index number might change
from movie to movie for the same exporter component.

Click on the message box export 1. A file Dialog Box will appear, prompting you for a file name. We'd suggest that you
create a new folder for saving the sequence, since the operation generates several files. Enter a valid file name and click Save.

You should now see a special Dialog Box appear, permitting you to adjust the options specific to the exporter you chose,
such as file type and frame rate, in the case of the Image Sequence exporter. (Notice that the same file type options are
available as with the exportimage operation.) If you leave the frame rate field empty, the export operation will use the
movie's native frame rate to generate the images.

Each exporter may have its own options. This Dialog Box will only appear when there is a 1 (which we call the options flag)
at the end of the export message to jit.qt.movie. The export message also accepts an optional file name before the options
flag.

You should only need to use the export 1 message once, whenever you start using a new exporter. While you're using
the same exporter, the jit.qt.movie object will remember the options after you've specified them the first time. Try
clicking the message box export now. No Dialog Box will appear for the exporter options, and the file will be exported
with the same options as before.

You should see a progress Dialog Box appear briefly. When it disappears, you can check in the Max Window to verify that
the operation was successfuljit.qt.movie will send the message export myfile 1 if it was. (The number will not be 1 if
there was a problem.) If you switch to the Finder and look in the folder where you chose to save the Image Sequence, you
should see several files, named sequentially. You've successfully exported your movie as an Image Sequence. Open a couple
of the files up and verify that they show different frames.
Returning to Max, click on the message box export fulldialog. The fulldialog argument is another flag to the export
message, telling jit.qt.movie to open the full QuickTime export dialog, which permits you to set file name, exporter and
exporter options all at once.

Technical Detail: When you use the fulldialog flag, jit.qt.movie won't know which exporter you chose while inside the
Dialog Box. In order for jit.qt.movie to remember what your current exporter is, you must use the exporter message.

The jit.textfile object


Had enough? Sorrythere's more, but let's take a little break from image data.

Jitter matrices can be used to manage all sorts of data, including text. The jit.textfile object provides a convenient interface
for importing and exporting text files to and from Jitter. Once you've imported a text file, you can edit it, or send it to other
objects for further processing or display as you would with any Jitter matrix. Or you might export a Jitter- generated text file,
and continue to work on it in your word processor. In this section, we're going to take a quick look at the jit.textfile object's
import and export abilities.

You may recall from the What Is A Matrix? chapter that one of Jitter's data types, char, is the size of a single character. With
the notable exception of certain complex character sets (such as Japanese), most languages use the char type for computer
representation. The correspondence between the numbers and letters has been standardized in the American Standard Code
for Information Interchange, usually referred to as ASCII.

One of the interesting things about the ASCII code is that the regular characters used in the English alphabet can be
represented in less than half of the space available to the char type (26 uppercase plus 26 lowercase plus 10 numerals is only
62 characters, compared to the 256 different values that chars can represent). Furthermore, all of these regular characters
fall in the first half of the char range (specifically, between 32 and 126). The following example patch will take advantage of
that fact.

String processing in Jitter with jit.textfile

This patch sends encoded text messages via Jitter matrices. Here's how to use it:

Let's begin by encoding a message. Choose an encode keya password that will be used for encoding (and later, decoding)
your message. Enter your encode key in the textedit object labeled encode key. Enter the message you want to encode in
the larger textedit object labeled code text, at the top of the patch. For the purposes of this example, you should limit your
message to regular English language charactersno accented characters, please.

Press the button labeled make code to encode your text. This causes the contents of the two textedit objects to be sent to
two jit.str.fromsymbol objects. These two objects convert the contents of their respective textedit objects from Max
symbols into matrices. The resulting two matrices are then added using the addition mode of the jit.op object, producing a
new encoded matrix that is then sent to the jit.textfile object,

It doesn't matter that the two pieces of text (and therefore the two matrices) are different sizes. Jitter automatically
scales the right-hand matrix of jit.op to the size of the left-hand matrix, stretching it or shrinking it as necessary. You
might modify the test patch and use a jit.print object to view the output of each object, and then compare it against the
output of jit.op, to see exactly what's happening.

Double-click on the jit.textfile object. This causes the object's text editor window to open, displaying the encoded message.
To verify that the encoding was successful, enter your encode key into the textedit object labeled decode key, and click on
the button labeled read code. Your original message will appear in the textedit object at the bottom of the patch. We'll
look at this process in a moment.

Click the message box that says write to save the message to disk so you can retrieve it later to send to your secret
message buddy (don't forget to give them the encode key!). A file Dialog Box will open, where you can enter a file name and
click Save to save your message to a text file. You can open this text file with any text editor application. The write message
takes an optional argument to specify a file name.

There's a secret message waiting for you, too. Click the message box read secret.txt. The read message reads a text file
from disk. In this case, we're using its optional file name argument. Without that argument, a file Dialog Box would open,
allowing you to locate a text file on your disk drive.

Double-click on the jit.textfile object again, and verify that there's a new encoded message in the editor window. Close the
editor window when you're ready. You can decode this message by entering the decode key Jitter in the textedit object
labeled decode key, and clicking on the button labeled read code. Did you get our message?
Like Max's text object, jit.textfile will output a single line in response to the line message. In Jitter, the line will be sent as
a string matrix. A string matrix is a matrix using the char data type with one dimension and one plane. The matrix is
composed of a sequence of characters ending with a zero (0). This is the format generated by jit.str.fromsymbol, and the
format expected by jit.str.tosymbol. We're using the line 0 message to output the first line of jit.textfile (our encoded text)
and send it to the jit.op object for decoding.
The decoder simply reverses the encoding processwe use the subtraction mode of the jit.op object to subtract the key
matrix from the encoded message matrix, leaving the original text. The decoded matrix, containing all the letters of the
decoded text, is then sent to the jit.str.tosymbol object, where it is converted back into the form of an ordinary Max
message, suitable for display in the textedit object.
If we wanted this patch to work properly with extended Roman characters, such as accented letters, we'd need to make a
couple of modifications. For extra credit, you might try to figure out a way to do that. Hint: the secret is in the op attribute to
jit.op.

Summary
Jitter offers several methods for importing and exporting single matrices from and to disk. The jit.matrix object (and the
jit.matrixset object, not demonstrated in this chapter) allow single matrices to be saved as single-frame QuickTime movies,
using the same parameters as the jit.qt.record object's write message. The jit.matrix and jit.matrixset objects also support
the Jitter binary (.jxf) format an uncompressed format specially suited to Jitter matrices. The jit.qt.movie object's
exportimage message lets you export a matrix as a single frame image in any of a number of image formats, and the export
message lets you store video frames as an Image Sequence.

In addition to images, Jitter matrices can be used to manage other kinds of data, such as text. The jit.textfile object provides
a convenient interface for importing and exporting text files to and from Jitter matrices. The jit.str.tosymbol and
jit.str.fromsymbol objects provide conversion between Max symbols and string matrices. These objects provide one of the
means by which data can be translated to and from Jitter's matrix data format.

See Also
Name Description
jit.matrix The Jitter Matrix!
jit.op Apply binary or unary operators
jit.pwindow Show data in a patcher
jit.qt.movie Play or edit a QuickTime movie
jit.qt.record Record a QuickTime movie
jit.str.fromsymbol Convert Max symbol to Jitter string matrix
jit.str.tosymbol Convert Jitter string matrix to Max symbol
jit.textfile Read and write a matrix as an ASCII text file
Working With Live Video and Audio Input
Tutorial 21: Working With Live Video and Audio Input
This tutorial demonstrates how to use Jitter in conjunction with a QuickTime-compatible image capture devicesuch as a
webcam, a DV camera, or a PCI video input cardto grab video sequences and use them as matrices, or record them directly
to disk. We can also use Jitter to record sound directly to disk as a QuickTime movie.
Open the tutorial.

The patch examples in this Tutorial assume that you have a QuickTime-compatible image capture device powered on
and attached to your computer.

A Note For Windows Users: The jit.dx.grab object offers many of the same capabilities of the jit.qt.grab object. The
main difference is that the object works natively with DirectX-compatible devices and doesn't require a QuickTime
VDIG. Please refer to the Reference and help patch for the jit.dx.grab object for more information

The Basics of Sequence Grabbing


When we capture video images from an input device, we are actually working with a sequence of images. In Tutorial 20, we
created a sequence of images using the export operation of the jit.qt.movie object. This time, we'll use the jit.qt.grab
object to grab a sequence of images.

The jit.qt.grab object provides an interface to one of QuickTime's componentsthe general mechanism used by QuickTime
to extend its functionality. Components can include software modules that provide interfaces for new video codecs, or an
interface between software and various kinds of hardware, or tasks like image capture and sound output. We've already used
a QuickTime component in Tutorial 20 when we used the export message, and we'll be looking at other QuickTime
component-based Jitter objects in the next several tutorials.

First grab in the Jitter Tutorial folder.

grab it like you want it

Notice that the jit.qt.grab object takes two arguments (320 and 240) that specify the width and height of the matrix output
by the object. They also represent the dimensions of the internal buffer into which any captured data will be placed. The
matrix will always be a 4-plane char matrix).

Click the message box that says getvdevlist. This message causes the jit.qt.grab object to search for available video
capture devices. The jit.qt.grab object will then send the names of any devices it finds out the right outlet in the form of a
list preceded by the symbol vdevlist. In our patch, we're using iter to break the list up, and placing the device names in an
umenu. Our list only has one item, DV Video, but yours may include different items.

Click on the umenu and select the device you'd like to use. This causes the message box that says vdevice $1 to send the
index of the selected video capture device (which is the same as its position in the umenu) to jit.qt.grab. If you don't
explicitly choose a vdevice, jit.qt.grab defaults to the first selection in the list (equivalent to sending a vdevice 0 message)
when it opens the component connection.

Click on the message box that says open. The open message tells jit.qt.grab to open a connection to the sequence
grabber componentto create a component instancefor the video capture device you've selected. Until you send the open
message, jit.qt.grab will simply output its last matrix when you send it a bang or outputmatrix messageno sequence
grabbing will occur.

Click on the toggle attached to the metro object, to start sending bangs to jit.qt.grab. You should now see your captured
video signal in the jit.pwindow.

If you don't see your video signal, check the Max Window and see if jit.qt.grab reported any errors. It may be possible
that your device is in use by another application, or that it has gone to sleep (our video camera sleeps after about 3
minutes of non-use, for example). If your device supports multiple inputs, read on.

If you have multiple devices connected to your computer, you can use the vdevice attribute to switch between them, even
after sending the open message to jit.qt.grab.
To close the component connection, click on the message box that says close. Leave this patch open; we'll return to it in a
moment.

Switching between inputs


The video capture device you're using may support several different inputs. For instance, a CapSure Card supports s-video
and composite inputs, and an ATI Rage 128 Pro supports s-video, composite and tuner inputs. FireWire DV generally
supports a single input. In this section, we'll learn how to list those inputs and switch between them.

Re-open the jit.qt.grab object's component connection by clicking on the message box that says open.
Click on the message box that says getinputlist. This causes jit.qt.grab to send a list of available inputs for your chosen
device out the right outlet preceded by the symbol inputlist. The patch breaks this list up using the iter object and sends it to
the umenu on the right of the patch.
Click on the rightmost umenu to see a list of inputs available to your device. Our DV camera reports that it has one input:
YUV component (DV). Our CapSure card reports composite and s-video inputs, as shown in the screen shot:

setting device inputs

To change your input, select an item from the umenu. This causes the message box that says input $1 to send the index
of the selected input (which is the same as its position in the umenu) to jit.qt.grab, which will switch to your selection. If
you don't explicitly choose an input, jit.qt.grab defaults to the first selection in the list (equivalent to sending an input 0
message) when it opens the component connection.

You should now see your captured video signal (from your chosen input) in the jit.pwindow.
When you're done, click the message box that says close to close the component connection.
Some video capture devices don't work properly in the jit.qt.grab object's default mode (vmode 0, or sequence
grabber mode). If you find that jit.qt.grab is acting erratically, try sending it the message vmode 1 (vdig mode). This
enables a method of video capture that is more reliable on certain capture devices.

Grabbing for quality


For webcams, the normal operating mode of jit.qt.grab provides speed and good quality. For other higher resolution
capture devices such as analog video-capture boards or DV cameras, we'd like to be able to adjust the quality of the sequence
grabber to get the most out of them.

high quality mode, with source and destination rects

Double-click on the p device_input subpatcher. The Patcher window that opens contains everything you need to set your
vdevice and input settings. Once you've done this, close the subpatch window.

Click the message box that says open to start the component connection. Click on the toggle attached to the metro
object. You should now see your captured video signal (from your chosen input) in the jit.pwindow.
To enable high quality mode, we need to send the message vmode 2 to jit.qt.grab. Enter the numeral 2 in the number
box attached to the message box that says vmode $1. If your capture device supports a high quality mode, you'll probably
see the image in the jit.pwindow change slightly.

If your device does not support high quality mode (vmode 2), you may see no change, or some undesirable result, like
distorted image proportions or noise. Should this occur, return to sequence grabber or vdig mode (vmode 0 orvmode
1).

To compare the different quality modes and settings, let's zoom in on a detail of the captured signal. Click on the toggle
attached to the message box that says usesrcrect $1. Sending the message usesrcrect 1 causes jit.qt.grab to capture only
the portion of the input signal specified by the source rectangle attribute, srcrect. By default, the srcrect attribute is set to
the full frame of the input signal.

Change the values of the number boxes attached to the paksrcrect 0 0 320 240 object. This will generate a message to
set the srcrect attribute. The srcrect message arguments refer to the left x, top y, right x and bottom y coordinates of the
input frame, respectively. You should see the image changing to reveal only the portion of the input frame you specify. For
best results, choose two numbers that have the same 4:3 aspect ratio as the input frame.

Let's do some comparisons. First, switch the vmode setting back to 0 or 1, depending on what you were using before
(reminder: vmode 1 (vdig mode) is only necessary and supported on specific capture devices). Compare the image quality to
vmode 2 (high quality mode). On our system, using a DV camera, the image becomes noticeably crisper, and aliased edges
are tightened up.
Click on the umenu object. The object contains a list of available quality settings for vmode 2 (the settings have no effect
in sequence grabber and vdig modes). Choosing an item from the umenu will cause the item's index number to be sent to
jit.qt.grab, via the message box that says codecquality $1. Select some different quality settings, and observe the changes
both in terms of image quality and frame rate (displayed on the jit.fpsgui object). The default setting for codecquality is
max (equivalent to sending a codecquality max or codecquality 4 message to jit.qt.grab).

You should experiment with your hardware to determine the best settings for your system. For example, using the
vmode 2 in conjunction with the codecquality min and codecquality low modes actually looks worse than vmode 0
on our system. While vmode 2 offers control over the capture quality, it will not necessarily improve the image quality
over the jit.qt.grab object's default capture mode.

You can also specify the portion of the output matrix the captured frame will occupya destination rectanglewith the
dstrect attribute. To enable the destination rectangle, click on the toggle attached to the message box that says usedstrect
$1. By default, the destination rectangle is set to the dimensions of the jit.qt.grab object's output matrix.
Change the values of the number boxes attached to the pakdstrect 0 0 320 240 object. As with the srcrect message, the
dstrect message arguments refer to the left x, top y, right x and bottom y coordinates of the output matrix. You should see
the image changing to occupy only the portion of the output matrix you specify. Notice that the pak object is connected to a t
l clear object, which causes a clear message to be sent to jit.qt.grab before sending the dstrect message. You could modify
the patch to see what happens if you don't send the clear message.

When you're done, click the message box that says close to close the component connection.

Grabbing to disk
You can save grabbed sequences directly to disk as a QuickTime movie, if you prefer. When you do this, jit.qt.grab writes
straight to the hard disk without sending out any matrix output. With only a few minor differences, this process is similar to
the one described in Tutorial 19. But this time, we'll be recording audio, too.

You should quit or disable any applications or settings that interrupt processing on your machine while recording to
disk, such as Internet applications or AppleTalk.

Grabbing video to disk

grabbing to disk

We've encapsulated the vmode, srcrect and dstrect settings we just looked at in the
p mode_rect subpatch. You can access them by double-clicking on the object if you'd like to change them. Note,
however, that the vmode attribute does not affect the grab to disk operation.

Double-click on the p device_input patcher. The Patcher window that opens contains everything you need to set your
vdevice and input settings. Once you've done this, close the subpatch window.

Click the open message box to start the component connection. Click on the toggle attached to the metro object. You
should now see the captured video signal from your chosen input in the jit.pwindow.
The jit.qt.grab object, by default, has its write_video attribute set to on (1). To reflect this, we've used loadbang to turn
on the toggle attached to the message box that says write_video $1. If you wanted to disable writing video and only write
audio, you would send a write_video 0 message and a write_audio 1 message to jit.qt.grab. For now, leave the toggle
connected to the message box that says write_audio $1 turned off (by default, the write_audio attribute is set to off (0)).
Click on the write grabfile.mov 15. jpeg normalmessagebox. You've probably noticed that this message looks like the
write message that we send to jit.qt.record object to start recording. Except for the lack of a timescale argument, the write
message to jit.qt.grab is formatted identicallygrabfile.mov is the file name, 15. refers to the output movie's frame rate,
jpeg specifies the Photo-JPEG codec, and normal specifies normal codec quality. All of the arguments are optional; if we
omit the file name, a file Dialog Box will appear. The remaining settings, if omitted, will retain their previous values. If there
are no previous values, the default values for the capture device will be used.

Technical detail: There is an important difference in the formatting of the write message to jit.qt.grab if you plan to
record separate video and audio (split) files. For more information, consult the Object Reference entry and help file for
the jit.qt.grab object.

Recording begins immediately after you send the write message. While we are recording, the jit.qt.grab object doesn't
output any matrices. We can tell because the jit.fpsgui object's display isn't changing. You can use the write_preview
attribute to switch matrix output on and off while recording. The write_preview attribute is off (set to 0) by default. Click on
the toggle attached to the message box that says write_preview $1 to enable matrix output while recording. Your
recordings will be smoother if you leave write_preview off.

Click the message box that says stop to stop the grab to disk operation, but leave the patch open.
The jit.qt.grab object sends a message out its right outlet after a write operation to confirm that the movie was successfully
recorded. Since we've connected that outlet to a print object in our patch, we can see the results by looking at the Max
Window. If everything went as expected, you should see print: write grabfile.mov 1 in the Max Window.

We can also record sound to disk using the technique just described. There are two ways to choose the sound device for
jit.qt.grab.

1. Use the snddevice and sndinput messages to set sound device and sound device input. This method is very similar to the
method we used to list the video devices and inputs, except that we use the getsnddevlist and getsndinputlist messages
instead of the getvdevlist and getinputlist messages. 2. Use the QuickTime Sound Settings Dialog Box to adjust all of the
device and input settings at once.
We're going to use the Sound Settings Dialog Box for this tutorial, but you might find it instructive to try making an altered
copy of the example patch for the message-based method. You can use the p device_input subpatcher as a model.

There is a Video Settings Dialog Box available for changing video device and input settings, as well. You can access it
by sending the settings message to jit.qt.grab.

Click the message box that says snd_settings. The Sound Settings Dialog Box will appear. Using the pop-up menus and
other controls, adjust the sound input settings to your preference. Close the Dialog Box by clicking OK.

Click on the toggle attached to the message box that says write_audio $1 to enable audio for the grab to disk operation.
Click the write grabfile+snd.mov 15. jpeg normalmessagebox. The recording will begin immediately as before, but
sound will also be recorded to the movie.

Click the message box that says stop to end the recording. Locate the movie on your hard drive, and open it in QuickTime
Player (or Max, if you prefer) to verify that sound was recorded with the movie.

Click the close message box to close the component connection.

If you investigate the Sound and Video Settings Dialog Boxes, you will notice that both offer numerous options for
controlling the input settings of each devicebrightness, saturation, gain, etc. All of these parameters may be modified
directly from Max/Jitter, although it's beyond the scope of this Tutorial to describe their operation. Please refer to the
Object Reference entry and help file for jit.qt.grab for more information.

Summary
The jit.qt.grab object allows you to grab images from any QuickTime-compatible video input device. The object offers both
Max-based and Dialog Box interfaces for listing devices and inputs, switching between them, and controlling image quality.
The srcrect and dstrect attributes can be used to crop and position a captured image within a Jitter matrix. The jit.qt.grab
object also provides a mechanism for recording video and sound directly to disk as a QuickTime movie.

See Also
Name Description
jit.pwindow Show data in a patcher
jit.qt.grab Digitize video from an external source
jit.qt.grab Digitize video from an external source
jit.qt.movie Play or edit a QuickTime movie
Working With Video Output Components
Tutorial 22: Working With Video Output Components
This tutorial demonstrates how to use Jitter in conjunction with a QuickTime-compatible video output devicesuch as a DV
camerato send matrices and video sequences directly to hardware, bypassing your computers analog video output. Well
explore the jit.qt.videoout object, and return to the jit.qt.movie object to explore its video output capabilities.

The patch examples in this tutorial assume that you have a DV camera attached to your computers FireWire port,
powered on and in VTR mode. However, the techniques described will work with any device that has a QuickTime
video output component.

End of the Line


You can place the jit.qt.videoout as the final object in a Jitter patch and send processed Jitter matrices directly to a video
output device. You'll find that this process is very similar in operation to the jit.qt.grab object that we used in the previous
tutorial.

The jit.qt.grab and jit.qt.videoout objects both require that you create a component connection before they can do their
work. In the case of the jit.qt.videoout object, that means a connection to a video output device. And, as in the previous
tutorial, we'll need to specify the settings we want to use by creating a listing of all our available devices and output modes
and choose the settings we want before we use the jit.qt.videoout object. Since we're already familiar with that procedure
from working with the jit.qt.grab object in the last tutorial, using the jit.qt.videoout object will be easy.
Open the tutorial.

jit.qt.videoout in action

Click the read dozer.mov message box to read an example movie.


Take a moment and look at the patch. By now, you should be familiar with the processes we're using to transform the movie:
we separate out a single plane of a matrix using the jit.unpack object, and sent it to the jit.op object. You'll notice that the
jit.op and the jit.rota objects are using named matrices to communicate between the jit.rota objects output matrix and the
jit.op objects right input matrix without using any patch cords. Yepit's the cool Jitter feedback loop in action.
Turn on the toggle attached to the metro object to start the patch. Youll notice that jit.qt.videoout appears to have no
effect. Until we send it an open message, the object simply passes any matrix received via its inlet directly to its outlet. Dont
click the open message box just yetwe still have some setup work to do.
Click the message box that says getvoclist. Sending a getvoclist message to the jit.qt.videoout object causes it to send
out its right outlet a list of messages preceded by the symbol voclist. The items in this list refer to each available video
output component voc, for short. This list of available video outputs is routed through an iter object and from there into
the umenu object on the left, from which we can easily make our selection. On our system, the list contains a single item:
FireWire.

If the video output component is registered with the MacOS, it will appear in the voclist and can be opened even if the
hardware isn't available. If there is no hardware available, the jit.qt.videoout object will report a 200 error in the
Max window when you send matrices to it.

Select the FireWire output component from the umenu. This causes the items index number (which is the same as its
position in the umenu) to be sent to the jit.qt.videoout object, via the voc $1 message. If you don't select anything, the
first item in the list will be used as the default component. This is equivalent to sending the message voc 0 to the
jit.qt.videoout object.

Click on the message box that says getvocmodes to retrieve a list of available modes for the output component you chose.
The resulting list, preceded by the symbol vocmodes, is routed through iter and into the righthand umenu object. Our list
contains two items: Apple FireWire NTSC and Apple FireWire PAL.

Select the output mode youd like to use from the umenu. Your selection will depend on your FireWire hardwareour
camera is NTSC, so were using Apple FireWire NTSC mode. This causes the items index number (which is the same as its
position in the umenu), to be sent to the jit.qt.videoout object, via the vocmode $1 message. If you don't select anything,
the first item in the list will be used as the default mode. This is equivalent to sending the message vocmode 0 to the
jit.qt.videoout object.

Now were ready to start sending data to our output device. Click the open message box to start the component
connection. After a few moments, you should see the same image on your devices display as you see in the jit.pwindow in
the patch.

If you are getting errors in the Max window, and not seeing any video on your hardware device, check to make sure
that your device hasnt gone to sleep.

We have control over other aspects of the output, too. While the specific codec we use is hardware-specific (Apple FireWire
always uses the Apple DV codec for output, for example), we do have control over the codec quality of our output. Try
selecting different values in the umenu object connected to the codecquality $1 message and compare the results on your
output device. You should be able to improve speed at the expense of a small loss in image quality by using the Minimum
Quality (codecquality 0) or Low Quality (codecquality 1) settings. The default is Normal Quality (codecquality 2).

Just Passing Through


If you want to send a movie directly from your disk drive to an output device and you don't need to process any of your data
using Jitter, you can use the jit.qt.movie object. You would typically want to do this only when the movie on your disk is
already in the proper format for the video output component you're usingfor example, if you're using a FireWire output
device, the file should be already be compressed with the Apple DV codec at the standard image resolution and frame rate).
using jit.qt.movie with output components

While using jit.qt.movie with output components doesn't look very different from using the jit.qt.videoout object, there is
one important difference:

The jit.qt.movie object doesnt use the open or close messages. You send the jit.qt.movie object a voc message with an
argument of 0 or greater to open a component connection, and close the connection and return the jit.qt.movie to normal
operation by sending the message voc 1. The argument to the voc message specifies the output component, just as with
jit.qt.videoout.

Other than that, the two objects access video output components identically.

Click the message box that says read to load a DV-encoded QuickTime movie from your disk drive. These usually have the
file extension .dv at the end of their file name. Because these movies tend to be large, weve chosen to not include one with
the tutorial package. If your computer came with Apple iMovie, there are sample DV movies in the iMovie Tutorial folder.

Click on the toggle object attached to the metro. Your movie will be shown in the jit.pwindow. You may notice that the
display is skipping frames; that's because DV movies contain a lot of data. Dont worrythe playback will improve when we
switch to the video output component.

Technical note: Playback improves when we switch to the video output component because the movie is no longer
being decompressed in software before it's displayedit's passing directly to the hardware where it is processed (as
necessary) there.

Use the getvoclist and getvocmodes message boxes and the umenu objects to select your preferred device and output
mode as we did in the previous chapter. When you set the output device (via the voc $1 message box), the movie will stop
playing in the jit.pwindow, and should begin playing on the display of your output device. If your DV movie includes sound,
the sound will play on the output device, as well. If your movie is correctly encoded for your output device, playback will be
smooth.

Click the message box that says voc 1 to disconnect from the output component. Playback will return to normal mode,
and the movie should display in the jit.pwindow object again.

Important: You may have noticed that the jit.qt.movie object that weve created has dimensions of 320x240, even
though DV movies are generally 720x480. When we switch to the output component, the movie is sent to your selected
output device at the movies native size, without regard for the dimensions of the jit.qt.movie objects output matrix.

Summary
The jit.qt.videoout object provides a way to send processed Jitter data directly to a device supported by QuickTime video
output componentssuch as a DV cameraover FireWire. If you dont require Jitter processing and would like to send a
properly encoded QuickTime movie from your disk drive to a supported output device, use the voc message to the
jit.qt.movie object.

See Also
Name Description
jit.op Apply binary or unary operators
jit.pwindow Show data in a patcher
jit.qt.grab Digitize video from an external source
jit.qt.movie Play or edit a QuickTime movie
jit.qt.videoout Output video to QuickTime video output component
jit.rota Scale/rotate in 2D
jit.unpack Make multiple single plane matrices out of a multiplane matrix
Controlling Your FireWire Camera
Tutorial 23: Controlling Your FireWire Camera
This Tutorial describes how to use Jitter to control the transport of a FireWire-based DV camera or deck using the jit.avc
object. This object provides a simple interface for communicating between Jitter and your DV device, and lets you control
and automate your FireWire DV device using the Max interface.

AV/C (an abbreviation for Audio Video Control) is the official name for the protocol that communicates between a computer
and an external device such as a DV camera. The exact specification used is called the AV/C Tape Recorder / Player Subunit.
You can find a copy of the entire specification online at http://1394ta.org.
The specification breaks the different types of transport controls you can use into three main groups:

1. The WIND group is used to move the media forward and backward, without playing it. WIND group commands include
stop, fast forward and rewind. 2. The PLAY group contains commands used to play media while moving forward or backward
at various speeds. Examples include play, pause, slow forward and slow reverse. 3. The RECORD group is used to insert data
on media.
These three groups are fully implemented in the jit.avc object. Additionally, the object supports a custom message, which
lets you send any command to your hardware, even those not directly supported by the jit.avc object.

The patch examples in this Tutorial assume that you have a DV camera or deck attached to your computers FireWire
port and powered on.

Plug and Play


The jit.avc objects hardware connection has to be explicitly opened and closed, as is the case for the jit.qt.grab and
jit.qt.videoout objects we've used in the previous tutorials. Using the jit.avc object is a little simpler, though -- it
communicates only with a single type of device.

Basics
Open the tutorialand double-click on the p example_1 subpatch to open it.

jit.avc and friends

Click the getdevice message box. This causes the jit.avc object to look for a compatible device attached to your computer.
If it finds one, the object sends the devices name from its outlet, preceded by the symbol device. With our Sony DV camera
attached, jit.avc sends the message device Sony DV.
In the patch, were using the route and prepend objects to set the contents of the blank message box to the name of the
located device. If jit.avc cannot find any compatible devices, an error message will be posted to the Max Window.

If you receive an error message, double-check your cable connections between your camera/deck and computer, and
make sure that the device is powered on.

Click the message box that says open. This causes jit.avc to open a connection to the device it found.
Technical note: We don't need to do any configuration prior to sending the open message to the jit.avc object. Unlike
objects like jit.qt.grab and jit.qt.videoout, which can switch between multiple input or output devices, jit.avc
communicates with a single device -- the DV component -- which supports a single piece of hardware (this is a MacOS
limitation).

PLAY and WIND groups (VTR mode)

This portion of the tutorial assumes that you have a DV cassette (with data already recorded on it) loaded in your
device, and that you are in VTR mode.

Use the play, stop, pause, rewind and ff message boxes (one at a time) and observe the behavior of your FireWire
device. It should be responding as if youd pressed those buttons on the unit itself.

Click on the umenu object to view a partial list of PLAY group messages. These messages consist of the word play followed
by an additional symbol describing the specific type of PLAY group operation. Double-click on the p avc_play_commands
subpatch to see brief descriptions of the messages weve placed in the umenu. A full list of supported messages can be found
in the Object Reference entry for jit.avc. Use the umenu to send a few of these messages to jit.avc to check their effect.
To check the current tape time, click the gettime message box. This causes the jit.avc object to send the current time
from its outlet as a list of four integers preceded by the symbol time. Were using route and unpack objects to display those
integers in the number boxes at the bottom of the patch. The numbers represent hours, minutes, seconds and frames,
respectively.

Click the message box that says close to turn off the connection between jit.avc and your DV device.

Avez-vous le temps?
The following patch uses the gettime message to do something useful -- it causes an attached DV device to play the first
minute of a loaded tape, and then rewinds and starts over. You might use a patch like this to automate a video installation,
for example.
Open the tutorialand double-click on the p example_2 subpatch to open it.

automating DV transport with jit.avc

Make sure that you have at least 1 minute of recorded material on your loaded DV cassette. Otherwise, the patch wont
work properly. Modifying the patch to perform error checking would probably be an instructive exercise for the motivated
reader.

Click on the message box that says open to open the connection between the jit.avc object and your device.
Click on the toggle attached to the metro object. This causes two things to happen: the trigger object causes a rewind
message to be sent to your device, and the metro is turned on, sending a gettime message to jit.avc every 100ms.
Were using the route object to send jit.avc objects response message (time [hour] [minute] [second] [frame]) to the
unpack object at the top of the patch. The individual time values are unpacked, multiplied and added to determine the total
number of frames that the current time represents.

Actually, our frame count is a little inaccurate. DV time has 29.97 frames per second, not 30. For simplicity, weve
rounded up. For the purposes of this exercise, the math is close enough.

Next, we test the frame count against the numbers 0 and 18122115 using the select object. Why? When a DV device cant
find time code (which is the case when its fully rewound and stopped), it reports the current time as either 0 0 0 0 or 165
165 165 165, depending on the device model. Since (0 * 10800) + (0 * 1800) + (0 * 30) + 0 = 0, and (165 * 10800) + (165
* 1800) + (165 + 30) + 165 = 1812215, we can use these numbers to determine if the tape has been fully rewound. If our
frame count does equal 0 or 1812215, then we send a bang to the play message box to start playback.

The jit.avc object also offers an advanced message called gettransport that reports the exact state of the devices
transport using hexadecimal numbers, which we might have used in preference to the method above. For our purposes,
though, this is fine, and a little bit cleaner. For more information on gettransport, refer to the Object Reference entry
and help file for jit.avc.

If our frame count does not equal 0 or 1812215, then we are either rewinding or playing. Now, we want to make sure that
we stop playing after approximately one minute, or 1800 frames (60 seconds * 30 frames). We test the frame count against
1800 with the > 1800 object and, if it sends out a 1, the sel 1 object will bang the rewind message box and start the
process all over again -- that's all there is to it.

When youre ready, turn off the toggle. This will both disable the metro and send a final rewind message to your DV
device, just for neatness. Click on the message box that says close to close the connection between jit.avc and your device.

Some FireWire DV devices support an additional message, time, which causes the device to wind to the specified
location on a loaded tape (the location is described by four integers, in the same format as noted above). DV cameras
do not support this message, generally speaking. Please refer to the help file for jit.avc for an example of building an
auto-wind function in Max.

RECORD group
If your DV device is a camera, it likely has two modes of operation: VTR mode and Camera mode. VTR mode is used for tape
playback and non-camera (line-level) recording. Camera mode is used for recording directly from the camera portion of the
unit. In VTR mode, all of the PLAY and WIND group commands are available, plus the RECORD group. In Camera mode,
only the RECORD group commands are available (since you cant rewind while recording!). You can use either mode for this
portion of the tutorial.

The RECORD group provides two primary messages: record and recpause. The record message starts recording, while the
recpause message places the unit into record pause mode.

time-lapse with jit.avc

This simple little patch is all thats necessary to set up time-lapse recording with jit.avc. It records 1 second of material every
30 seconds. Lets go through it:
Open the tutorialand double-click on the p example_3 subpatch to open it.

Click the message box that says open to start the connection between jit.avc and your DV device.
Before we turn it on, lets examine the patch to see whats going to happen. Every second, the metro object will send a
bang to the counter. When the counter hits 0, the sel 0 object will output a bang, first to the record message, and then to
the delay object. After the specified delay (weve chosen 1000 ms.), the recpause message will be sent to jit.avc. Weve
supplied some number boxes so that you can change the counter and delay values.
Make sure that your DV device is receiving input (either from its built-in camera, or from a line-level source). Then, turn
on the toggle attached to the metro, and watch your DV device for a few minutes -- time-lapse videography was never so
easy!

When youre ready, turn off the toggle and click the message box that says close to close the connection between jit.avc
and your DV device.

Summary
The jit.avc object provides a way to control and automate your FireWire DV device, such as a DV camera or deck, using the
Max interface. It offers complete control over the WIND, PLAY and RECORD group commands.

See Also
Name Description
jit.avc Control a FireWire VTR
QuickTime Effects
Tutorial 24: QuickTime Effects
This tutorial describes the basic operation of the jit.qt.effect objectJitters interface to Apples QuickTime Effects
architecture. Well learn how to set up and configure the object, discuss the difference and use of tweenable and non-
tweenable parameters and apply a few effects to Jitter matrices. Well also learn how to create QuickTime Effects tracks
inside of movies.

QuickTime contains a large number of built-in effects, including transitions (wipes and fades), filters and standalone
(render) effects, collected under the general system known as QuickTime Effects. While QuickTime Effects are slow
compared to many of Jitters transitions and filters, there are some unique effects available that Jitter does not include. The
other difference between using QuickTime Effects and Jitter filters is that QuickTime Effects can be embedded as tracks
inside a QuickTime movie, in a similar way as audio or video tracks.

The QuickTime Effects architecture uses a single interface to support a wide variety of different effects, each of which may
require different numbers of parameters and parameter typesQuickTime Effects use the same interface to describe effects
which don't use any input sources at all (such as the Fire or Cloud effects), effects which require a single input source (such
as Blur or Gain) and effects that require two inputs (such as the Chromakey effect). So it should come as no surprise that the
jit.qt.effect object is one of the most complex objects in the Jitter package. But don't worrywe'll be taking it one step at a
time in this tutorial.

The Dialog Box Interface


The quickest and easiest way to access QuickTime Effects and to become acquainted with them is to use QuickTimes
standard Dialog Interface. The following patch will let you do just that.

Open the tutorial patch 24jQTEffects in the Jitter Tutorial folder and look at the section labeled A. QuickTime Dialog.

exploding QuickTime Effects

By clicking on both of the message box objects that say read, load QuickTime movies into the two jit.qt.movie objects.
Turn on the toggle attached to the metro object to start the patch. You will see your movies in the two smaller
jit.pwindow objects. On the larger jit.pwindow object, you should see the left-hand movie. Since we havent actually selected
a QuickTime effect, the jit.qt.effect object is just passing the matrix received in its left inlet through its outlet.
Click on the dialogmessagebox. This causes the jit.qt.effect object to display the standard QuickTime Effects Dialog Box.
You can select any available effect, and set any of the parameters for it. Here's an example of what the Dialog box looks like
under QuickTimewe've selected the Explode effect:
the QuickTime Effects Standard Dialog Box interface

All available QuickTime Effects are shown in the scrollable window on the left. Your list may look slightly different from
this exampleespecially if you've added extra effects to your system. As you select different items from the list, the preview
window on the bottom-left of the patch changes to show you an example of what the effect does. The adjustable parameters
for the effect are shown on the right part of the window.

Go ahead and try a few different effects, and experiment with different parameters. Choose an effect, set the parameters,
and click on the OK button to see your changes in the patch. To try another effect, just click on the dialog message box
again and choose another effect. Note that some of the effects use both matrix inputs to jit.qt.effect, some only use one, and
some dont use the incoming matrix at all, except for timing purposes.

Youll notice that a number of effects offer two values for each parameter. For instance, in the Explode effects parameter
panel shown above, all three parameters have two values. These are known as tweenable parameters, because the effect will
interpolate between the two values entered. If you look at the jit.qt.effect object in our patch, youll notice that it has a
typed-in value of 60 for the steps attribute, indicating that any tweened parameters should interpolate over 60 steps (60
incoming matrices). Well discuss tweened parameters in more detail later on in this tutorial.

When youve had your fill of the QuickTime Effects Dialog Box, click on the toggle to turn off the patch.

To the Max
Every effect and option that you saw in the QuickTime Effects Dialog Box is available when using Jitter, too. Here's where
things become a little bit complicated, and here's where we can help you out. While you were experimenting with the last
patch, you probably noticed that each effect had a different number of parameters, each with completely different parameter
types. For example, let's compare the Blur and Cloud effects. The Blur filter effect has one parameter in the form of an
enumerated list of values (the menu),while the Cloud render effect has three parameterstwo of which specify RGB colors,
and the third of which is a floating-point number representing the degree of rotation. How will you know how many
QuickTime Effects parameters you need to control, and what kind of data you need to send for each one?

We've created a patch we hope you'll use if you want to use QuickTime Effects from with Jitter. Our patch handles all the
QuickTime Effects information by listing all the variables on the fly, as you make selections in Jitter. We've created an
interface in the Max patch that interprets this information in a clear way that you can use and adapt for your own purposes.
You should feel free to use our patchat least until you're comfortable enough to make something similar for yourself. We
promise it will save you a lot of hassle and frustration.

In the jitter-examples folder installed with Jitter, youll find a whole set of QuickTime Effects helper patches, in the
folder jit.qtfx.helpers. Each of these patches isolates and documents the functionality of a single QuickTime Effect
and weve made helper patches for all of them. You can use these helper patches as though they were normal Jitter
objects, and ease your entry into the rich, but complex, world of QuickTime Effects.

Listing and loading effects


To generate a list of available effects using jit.qt.effect, we use the geteffectlist message. This causes a series of messages to
be sent out the objects right outlet, one message for each available effect. Each of these messages is in the format effectlist
[index] [name] [code], where index is an index number (starting at 0), name is the plain English name for the effect, and
code is a 4-letter code used to describe the effect.

Open the tutorial patch 24jQTEffects in the Jitter Tutorial folder and look at the section labeled B. QuickTime Effects Max
Interface.

Dont worry about the jit.qt.movie objects for now. Lets start by looking at the other parts of the patch first.
Click on the message box that says geteffectlist. Were using a route object to separate out messages beginning with the
symbol effectlist, formatting the messages with sprintf, and then appending them to the umenu.
Click on the umenu to see the list of available effects. It should contain the same items as the list that appeared on the left
side of the QuickTime Effects Dialog Box.

To load an effect for use in jit.qt.effect, we use the loadeffect message. The loadeffect message takes a single argument,
which can be either the index number or the 4-letter code of the desired effect. In this example, were using the effects index
number (which is the same as the items position in the umenu) to load effects into jit.qt.effect via the loadeffect $1
message.

Now that we've loaded our effect, it's time to list and specify the parameters for our effect.

Parameter types
Lets take a moment and look over the various parameter types used by QuickTime Effects. When the jit.qt.effect object
reports available parameters, it describes the type of each parameter and any limitations placed on the values. Youll need
this information to set the parameters properly.

The types are:

long: (long integer) an integer value

fixed: (fixed-point) floating-point value, usually between 0. and 1.0.

double: (double-precision floating point) floating-point value

rgb: (RGB color) 3 integers between 0 and 255, describing an RGB color

bool: (Boolean) an integer value, 0 or 1

enum: (enumerated list) a list of integer indices, in which each index is associated with a specific value (the indices are not
necessarily consecutive)

text: (text) This type is not currently supported from Max (you can use effects with text parameters from the Dialog Box)

imag: (image) This type is not currently supported from Max (you can use effects with image parameters from the Dialog
Box)

Listing parameters
To generate a list of available parameters for your selected effect, we use the getparamlist message. This causes a series of
messages to be sent out the jit.qt.effect objects right outlet, one message for each available parameter, plus a "header
message".

The header message is sent first. It is in the format paramhead [name] [code] [params] [sources], where name is the
plain English name for the effect, code is the 4-letter code, params is the number of parameters the effect has, and sources
is the number of input sources used by the effect.

Although some QuickTime Effects report the ability to use 3 sources, the jit.qt.effect object only supports up to 2-
source effects at present.

After the header message comes the series of parameter messages, in the format paramlist [index] [name] [code] [tween]
[type] [variable]. The index argument is the index number of the parameter (starting at 0), name is the plain English name
of the parameter, code is the 4-letter code for the parameter, tween is an integer describing the parameters tweenability (0
= always tween, 1 = never tween, 2 = optionally tween), type is the type of parameter (from the list above), and variable is
zero or more additional arguments which indicate permitted values, depending on the parameter type. They are:

long: [min (optional int)] [max (optional int)]

fixed: [min (optional float)] [max (optional float)]

double: [min (optional float)] [max (optional float)]

rgb: rgb_range (which is just a reminder that RGB values are from 0 - 255)

bool: none

enum: [index (int)] [value (int /symbol)] (these repeat in pairs until all enumerated values are described)

text: [max characters (optional int)] [max lines (optional int)]

imag: none

In practice
In our patch, when you select an effect from the umenu, a bang is automatically sent to the getparamlist message box.
The subpatcher p interpret contains an algorithm that automatically takes the information weve just described and formats
it for readability (If youd like to see how it works, double-click on the patcher object).

Take a look at the portion of the patch shown above. The three outlets from the p interpret patcher are attached to the
inlets of the three objects belowthe message box, umenu and textedit object. The message box contains the formatted
paramhead message. The umenu contains the formatted paramlist messages. The textedit object displays the additional
parameter data. Above, you see the information reported for the Blur effect. We see that its called blur, has a 4-letter code
of blur, takes only one parameter and one source. Parameter 0, the first parameter, represents the amount of blurring, and
has a 4-letter code of ksiz. This parameter is an enumerated list, and cannot be tweened. In the textedit object, we display
the correspondence between the indices and their actual values.

Choose a few other effects from the left-hand umenu, and see how the information displays change. Choose different
parameters from the right-hand umenu to get a feel for how the different parameters are described.

Making changes to parameters


Load some movies into the two jit.qt.movie objects by clicking on the read message box objects and turn on the toggle
attached to the metro to start the patch.
In the left-hand umenu, choose the transition effect called radial (in our umenu, its at index 24).

Looking at the parameter display, we see that radial has seven parameters and takes 2 sources. In the jit.pwindow, you
should see your left-hand movie playing.

The effects first parameter is called percentage. Its a fixed-point parameter, and, by consulting the textedit object, we
see that it takes a minimum value of 0, and a maximum value of 1.
In the example patch, find the display pictured in the screen shot above. Its located toward the upper right of the patch.
This is our parameter editor. The value in the blue number box represents the parameter number. Well use the yellow
number boxes to set values for the chosen parameter. Each time you change one of the yellow number boxes, the pak object
sends a param message to jit.qt.effect to set the parameter values.

Weve set up the patch so that when you change the blue number box, the parameter information display automatically
changes to display the parameter youve chosen. Behind the scenes, were using another message to jit.qt.effect called
getparam to retrieve the current values of the parameter.

For now, lets just edit the first parameter. Make sure the blue number box is set to 0. Now, adjust the first yellow
number box to values between 0 and 1. You should see the image in the jit.pwindow change as you do. The right-hand
screen shot, above, shows an example.

Change the parameter number to 1. From the information display, we see that parameter 1 is an enumerated list that
controls the wipe type. You can scroll down in the textedit object to see the full list of types. Try entering different indices in
the leftmost yellow number box to try them out. You can always switch back to parameter 0 to see the effect at different
percentage values.

Lets skip to parameters 4 and 5 (parameters 2 and 3 control horizontal and vertical repeat valuesfeel free to try them
out). Change to parameter 4 (border width, which takes a fixed-point number between 0 and 20) and set the parameter
value so that you see a border appear at the edge of the wipe. Now, change to parameter 5. This parameter sets the RGB
color of the border. Using all three yellow number boxes, set the parameter to 0 255 0. The border should appear bright
green, as pictured below.

Finally, change to parameter 6, (soft edges). Parameter 6 is a Boolean value (the equivalent of a check box in the Dialog
Box). If you set this parameter to 1 (on), the border will be drawn anti-aliased.

Youve now successfully negotiated jit.qt.effect and worked with every major parameter type.

Tweening
Like any other Jitter object, we use messages to control jit.qt.effect parameters using messages. Additionally, we can take
advantage of QuickTime Effects built-in support automatic interpolation between parameter values, or tweening. As we saw
in the first part of this tutorial, using tweened parameters is fairly straightforward. Now, were going to control them from
Max.

Youll recall that tweened parameters change from an initial value to a target value over a specified number of steps. Setting
these values from a patch differs only slightly from the method we just used. Instead of setting parameters using the param
message, we use a pair of messages, param_a and param_b, which represent the initial and target values, respectively.
Locate the portion of the patch shown in the screen shot, above.

Select the cloud render effect from the left-hand umenu. The parameter information display should indicate that cloud
has 3 parameters and takes no sources. If you quickly browse through the parameters, youll see that they are all marked
tween-optional, which means that we can tween them all if we like.

Lets set our initial values. Click on the blue umenu, and change the selection to param_a. This sets the first item in the
pak object, so that any parameter changes are now sent to the jit.qt.effect object as a param_a message.

The cloud effects first parameter, parameter 0, sets the RGB color of the cloud. Lets go for red. Using the yellow number
box objects, set this parameters value to 255 0 0.

Parameter 1 sets the RGB color of the background. Anyone for black? Set this parameter to 0 0 0.

Parameter 2 sets the clouds rotation. Well set up a full rotation for this example. Change this parameter to 0.

Click on the blue umenu again, and select param_b. Well set target values now.
Set the cloud color to blue (0 0 255), the background color to yellow (255 255 0) and the rotation to 360.

To actually see our tweened parameters, change the number box connected to the message box that says steps $1. Look
at that sky change!

Saving and Loading Parameter Files


QuickTime Effects supports a special file type that we use to save and retrieve effect parameters, called .qfx. We can use .qfx
files to back up parameter configurations that wed like to recall later, or to move a parameter set from one patch to another
(or from one application to another.qfx files use a standard file type that any program that utilizes QuickTime Effects
should know how to read). In Jitter, we also use .qfx files to create QuickTime Effects tracks in the jit.qt.movie object.
Locate the message boxes shown in the screen shot below in the lower right of the patch. Since were confident that youll
want to hold on to the settings we just entered for the cloud effect, let's save them to disk.

Click on the qfx_writemessagebox. A File Dialog box will appear. Enter a filename and click on the Save button to write
your parameter file to disk. The qfx_write message also accepts an optional filename as an argument, if youd like to bypass
the File Dialog box.

We use the qfx_read message to retrieve a .qfx file. Click on the message box that says qfx_read luv.qfx. Make sure you
have two movies running in the patch, and that your steps attribute is set to a value greater than 0. Its a little present from
us to you, because we love you so much.

If you are using the QuickTime Effects Dialog Box interface to set your effect parameters, you can access the
functionality of the qfx_read and qfx_write messages with the Load and Save buttons at the bottom left of the Dialog
Box.

Using QuickTime effects in QuickTime movies


QuickTime Effects can be used as special tracks inside of movies. A QuickTime Effects track uses existing video tracks as
sources (if applicable) and renders the effect in real time, while the movie plays.

The jit.qt.movie object lets you add effect tracks to an existing movie by using .qfx files to describe the effect and its
parameters.

Open the tutorial patch 24jQTEffects in the Jitter Tutorial folder and look at the section labeled C. QuickTime Effects
Track.

Turn on the toggle attached to the metro object to start the patch.

Click on the read track1.mov message box to read in an example movie.

To determine the number of tracks this movie contains, click the message box that says gettrackinfo. This causes one or
more messages to be sent out the jit.qt.movie objects right outlet, beginning with the symbol trackinfo, followed by several
arguments. The format of the message is trackinfo [track index] [track name] [track type] [track enabled] [track layer].

Lets take a moment to look at this message. It reads trackinfo 1 unnamed video video 1 0. Since there is only one
message, we know there is one track in track1.mov, at index 1. It is an unnamed video track. Its enabled, and at layer 0.

QuickTime layers are numbered from 32768 to 32767. Tracks at lower layers are displayed in front of tracks at higher
layers. If two tracks are at the same layer, the track with the higher track index is displayed in front. When you create a
new track, QuickTime assigns it a layer of 0.

Click on the message box that says copy track2.mov track 1 track 1. This message finds the movie track2.mov, and
copies its first track (which we happen to know is a video track) to a new track in our current movie (the 1 tells
jit.qt.movie to create a new track). Because the new track has the same layer as the existing track (0, in this case), it is
displayed in front.

If we wanted to know, without a doubt, what the track layout of track2.mov is, we could send the message
gettrackinfo track2.mov to jit.qt.movie. Most track query commandsmessages beginning with gettrackaccept a
remote source (a file on disk, a URL or data on the clipboard) as an initial argument.

Click on the gettrackinfo message box again. You should see two messages printed in the Max Window, indicating that
we now have two tracks in our movie:

print: trackinfo 1 unnamed video video 1 0


print: trackinfo 2 unnamed video video 1 0

Lets insert luv.qfx as an effect track in this movie. Take a look at the addfxtrack dialog 0 0 1 2 message:

This message causes jit.qt.movie to present a File Dialog Box, in which you can choose a .qfx file to import as an effect track
(if we replaced the reserved symbol dialog with a the name of a file, the object would load the file specified). The message
format is addfxtrack [filename] [offset] [duration] [source track A] [source track B]. The offset argument refers to the
starting position of the effect in the movie. The duration argument specifies the length of the effect (in QuickTime time
values). The source track A and source track B arguments specify the source tracks, by track index.

A duration argument of 0 causes jit.qt.movie to calculate a maximum duration for the effect. For a 0-source effect,
this value is the length of the movie (minus any offset). For a 1-source effect, its the length of the source track (minus
any offset). For a 2-source effect, the value is the length of the shortest of the two source tracks (minus any offset).

Click the message box that says addfxtrack dialog 0 0 1 2. Find luv.qfx and click the Open button in the File Dialog
Box.

You should immediately see the luv.qfx effect applied to the two movie tracks as the movie plays.

Click the gettrackinfo message box one last time. You should see the following in your Max window:
print: trackinfo 1 unnamed video video 1 0
print: trackinfo 2 unnamed video video 1 0
print: trackinfo 3 ___effect_src2 video 1 0
print: trackinfo 4 ___effect_src1 video 1 0
print: trackinfo 5 ___effect_track video 1 32768

Apparently, our movie has acquired some new tracks, hasn't it? Applying an effect track to a movie will create between one
and three new tracksone track for the effect itself (named ___effect_track), and one track for each of the source tracks
(named ___effect_src1 and ___effect_src2).

You shouldn't change the names of these tracks the jit.qt.movie object relies on these track names for the
deletefxtrack message, as we'll see.

We use the deletefxtrack message to remove effects tracks from a movie. Click on the message box that says
deletefxtrack. This will remove any tracks with the reserved names discussed above.

Summary
The jit.qt.effect object provides an interface to Apples QuickTime Effects architecture. The object permits control over
QuickTime Effects using a standard Dialog Box, or with Max messages. The jit.qt.effect object permits control over
tweenable parameters, and offers import and export with the .qxf file format. The jit.qt.movie object can use .qxf files to
generate effect tracks for QuickTime movies.

See Also
Name Description
jit.pwindow Show data in a patcher
jit.qt.effect QuickTime Effects for Jitter matrices
jit.qt.movie Play or edit a QuickTime movie
Tracking the Position of a Color in a Movie
Tutorial 25: Tracking the Position of a Color in a Movie
Color Tracking
There are many ways to analyze the contents of a matrix. In this tutorial chapter we demonstrate one very simple way to look
at the color content of an image. We'll consider the problem of how to find a particular color (or range of colors) in an
image, and then how to track that color as its position changes from one video frame to the next. This is useful for obtaining
information about the movement of a particular object in a video or for tracking a physical gesture. In a more general sense,
this technique is useful for finding the location of a particular numerical value (or range of values) in any matrix of data.

jit.findbounds
The object that we'll use to find a particular color in an image is called jit.findbounds. Since we're tracking color in a video,
we'll be analyzingas you might expecta 4-plane 2-dimensional matrix of char data, but you can use jit.findbounds for
matrices of any data type and any number of planes.

Here's how jit.findbounds works. You specify a minimum value and a maximum value you want to look for in each plane,
using jit.findbounds's min and max attributes. When jit.findbounds receives a matrix, it looks through the entire matrix
for values that fall within the range you specified for each plane. It sends out the cell indices that describe the region where it
found the designated values. In effect, it sends out the indices of the bounding region within which the values appear. In the
case of a 2D matrix, the bounding region will be a rectangle, so jit.findbounds will send out the indices for the left-top and
bottom-right cells of the region in which it found the specified values.
Open the tutorial.

In this example we use the jit.qt.movie object to play a movie (actually an animation) of a red ball moving around. This is
obviously a simpler situation than you will find in most videos, but it gives us a clear setting in which to see how
jit.findbounds works. Notice that we've used typed-in arguments to initialize the min and max attributes of
jit.findbounds.

Minimum and maximum values specified for each of the four planes

There are four arguments for these attributesone value for each of the four planes of the matrix that jit.findbounds will
be receiving. The min attribute sets the minimum acceptable value for each plane, and the max attribute sets the maximum
acceptable value. These arguments cause jit.findbounds to look for any value from 0 to 1 in the alpha plane, any value from
0.75 to 1 in the red plane, and any value from 0 to 0.1 in the green and blue planes. Since the data in the matrix will be of
type char, we must specify the values we want to look for in terms of a decimal number from 0 to 1. (See Tutorials 5 and 6
for a discussion of how char values are used to represent colors.) We want to track the location of a red ball, so we ask
jit.findbounds to look for cells that contain very high values in the red plane and very low values in the green and blue
planes. (We'll accept any value in the alpha plane.)

Click on the toggle to start the metro. As the red ball moves around, jit.findbounds reports the cell indices of the ball's
bounding rectangle. Stop the metro, and examine the numbers that came out of jit.findbounds. You'll see something like
this:

jit.findbounds reports the region where the specified color appears

The jit.findbounds object will report the region where it finds the desired values in all planes of the same cell. In this
picture, the jit.findbounds object found the values we asked for somewhere in columns 120 through 159 and somewhere in
rows 50 through 89 inclusive. This makes sense, since the red ball is exactly 40 pixels in diameter. Those cell indices
describe the 40x40 square region of cells where the ball is located in this particular frame of the video.
Note that the output of jit.findbounds from its first two outlets is in the form of two lists. The first outlet reports the
starting cell where the values were found in each dimension and the second outlet reports the ending cell of the region in
each dimension. (Since it's a 2D matrix, there are only two values in each list, and we use the unpack objects to view them
individually.)

If we wanted to know a single point that describes the location of the ball in the video frame, we could take the center point
of that rectangular region reported by jit.findbounds and call that the "location" of the ball. That's what we do with the expr
objects. For each dimension, we take the difference between the starting cell and the ending cell, divide that in half to find
the center between the two, and then add that to the starting cell index to get our single "location" point.

Calculating the center point of the rectangle

Notice that for the vertical dimension we actually subtract the vertical location coordinate from 239. That's because the cell
indices go from top to bottom, but we would like to think of the "height" of the object going from bottom to top. (That's also
how the slider object behaves, so since we're going to display the vertical coordinate with the slider, we need to express the
coordinate as increasing from bottom-to-top.)

We send the results of our "location" calculation to a pair of slider objects to demonstrate that we are successfully tracking
the center of the ball, and we show the coordinates in the number boxes. We also scale the coordinates into the range 0 to 1,
to show how easily the horizontal and vertical location of the ball could potentially be used to modify some activity or
attribute elsewhere in a Max patch. For example, we could use the vertical location to control the volume of a video or an
MSP sound, or we could use the horizontal coordinate to affect the rotation of an image.

Scale the location coordinates into the range 0-1, for use elsewhere in the patch.

Tracking a Color in a Complex Image


Well, that all worked quite nicely for the simple example of a plain red ball on a plain white background. But tracking a
single object in a "real life" video is a good deal tougher. We'll show some of the problems you might encounter, and some
tricks for dealing with them.

Make sure the redball movie is stopped. Now double-click on the patcherbballtracking object to see A More Detailed
Example. Click on the toggle labeled Start/Stop in the upper-left corner of the [bballtracking] subpatch to start the video.
This movie has objects with distinct colors: a red shirt, green pants, and a yellow-and-blue ball. Potentially it could be useful
for color tracking. However, there are a few factors that make tracking this ball a bit harder than in the previous example.

First of all, the top few scan lines of the video (the top few rows of the matrix) contain some garbage that we really don't
want to analyze. This garbage is an unfortunate artifact of the imperfect digitization of this particular video. Such
imperfections are common, and can complicate the analysis process. Secondly, the image is not highly saturated with color,
so the different colors are not as distinct as we might like. Thirdly, the ball actually leaves the frame entirely at the end of the
four-second clip. (When jit.findbounds can't find any instance of the values being sought, it reports starting and ending cell
indices of -1.) Fourthly, if we want to track the color yellow to find the location of the ball in the frame, we need to recognize
that the ball is not all one shade of yellow. Because of the texture of the ball and the lighting, it actually shows up as a range
of yellows, so we'll need to identify that range carefully to jit.findbounds.
Let's try to solve some of these problems. As we demonstrated in Tutorial 14, some Jitter objects allow us to designate a
"source" rectangle of an image that we want to view that's different from the full matrix. In Tutorial 14 we demonstrated the
srcdimstart, srcdimend, and usesrcrect attributes of jit.matrix, and we mentioned that jit.qt.movie has comparable
attributes called srcrect and usesrcrect. Let's use those attributes of jit.qt.movie to crop the video image, getting rid of
some parts we don't want to see.

Click on the message box labeled Crop Source Image. This sends to jit.qt.movie the cell indices of a new source rectangle
that we want to view, and tells jit.qt.movie to use that source rectangle instead of the full matrix. Notice that by starting at
row 4 (that is, starting with the fifth row of the matrix), we crop out the garbage at the top of the image. We also chop 20
pixels off of the left side of the source image, so that the first bounce of the ball occurs exactly in the lower-left corner. Now
we've focused on the part of the video we want to analyze.

Next we'll deal with our other problems. Click on the small preset object labeled Setup in the lower-right corner of the
window. This sets all the user interface objects to just the settings we desire.

This sets the loop attribute of jit.qt.movie to 2 for back-and-forth playback, and it sets a loop endpoint at time 2160 (just
at the moment when the 54th frame would occur) so that the movie now plays back and forth from frame 0 to frame 53 and
back. The movie now plays just up to the moment of the first bounce of the ball on the pavement, then reverses direction.

We have also sent some values to the jit.brcosa object (discussed in detail in Tutorial 7) to set its brightness, contrast, and
saturation attributes just the way we want them. This doesn't exactly result in the best-looking image, but it does make the
different colors more distinctive, and compresses them into a smaller range of values, making them easier for jit.findbounds
to track.

And we've turned on the usesrcdim attribute of the jit.matrix object (in the center of the patch) so that it is now using the
output of jit.findbounds to determine its source rectangle. You can see the tracked region displayed in the jit.pwindow
labeled Show Tracked Region.

Using the output of jit.findbounds to set the srcdimstart and srcdimend attributes of jit.matrix

The basic yellow of the ball has nearly equal amounts of red and green in it, so we set the min and max attributes of
jit.findbounds to look for cells containing high values in the red and green planes and a low value in the blue plane. You
can see that with careful settings of jit.brcosa and careful settings of the min and max attributes of jit.findbounds, we've
managed to get very reliable tracking of the yellow part of the ball.

Note: One fairly important detail that we haven't really discussed here is how to set the min and max attributes of
jit.findbounds most effectively to track a particular color in a video. A certain amount of trial-and-error adjustment is
needed, but you can get some pretty specific information about the color of a particular pixel by using the suckah
object demonstrated in Tutorial 10. You can place the suckah object over the jit.pwindow of the video you want to
analyze, click on the color you want to track, and use the output of suckah to get the RGB information of that cell.
(The values from suckah are in the range 0-255, but you can divide them by 255.0 to bring them into the 0-1 range.)

Using the Location of an Object


So, at least in this particular situation, we've managed to overcome the difficulties of tracking a single object in a video. But
now that we've accomplished that, what are we going to do with the information we've derived? We'll show a couple of ways
to use object location to control sound: by playing MIDI notes or by playing MSP tones. Neither example is very
sophisticated musically, but they should serve to demonstrate the basic issue of mapping location information to sound
information.

We'll send the location data to two subpatches located in the part of the patch marked Use Tracking Info. We use a pack
object to pack all of the output of jit.findbounds together into a single 4-item list, and then we use a gate object to route
that information to the patcher playnotes subpatch (to play MIDI notes) or the patcher playtones subpatch (to play MSP
tones) or neither (to produce no sound).
Send the location information to one of two subpatches

Note: In order for any of the tutorial examples involving MIDI or MSP to work, you'll need to have your equipment
configured properly. The MIDI examples assume that you have OMS installed and that you have a multi-timbral
synthesizer keyboard connected to Max's virtual MIDI port a. The MSP examples assume that you have MSP installed
and that you have the Driver set to the proper output device in the Audio Status window.

For more information on how to configure your equipment, consult the "Setup" section of the Max Getting Started
manual, the "Introduction" section of the Max Tutorials and Topics manual, and the "Audio I/O" section of the MSP
manual.

Playing Notes
In the umenu labeled Use Tracking Info, choose the menu item 1 = Play MIDI Notes. Double-click on the patcher
playnotes object to see the contents of the [playnotes] subpatch. If you are not hearing any notes being played (and you've
verified that the movie is still playing), try double-clicking on the noteout a object and choosing a different MIDI
synthesizer in the device dialog box.

The contents of the [playnotes] subpatch

In the [playnotes] subpatch we use the same sort of mapping formulae as we used in the first example to calculate the
location coordinates of the ball and place the information in a usable range. We calculate the horizontal location and divide
by 16 to get numbers that will potentially range from 0 to 19. We use the change object to ignore duplicate numbers (i.e.
repeated notes), and then we look up the note we want to play in the table.

Note: The basketball player's motion has no relationship to any particular musical scale, so taking the raw location data
as MIDI key numbers would result in an atonal improvisation. (Not that there's anything wrong with that!) If we want
to impart a tonal implication to the pitch choices, we can use the numbers generated by the horizontal motion of the
ball as index numbers to look up notes of the scale in a lookup table. If you want to see (or even alter) the contents of
the table, just double-click on the table object to open its graphic editing window.

We use the vertical location of the ballwhich we've mapped into the range 0-119to determine the velocity values. The
makenote object assigns the duration (200ms) to the notes and takes care of providing the MIDI note-off messages. The
underlying pulse of the music (20 pulses per second) is determined by the speed of the metro that's playing the movie, but
because the change object suppresses repeated notes, not every pulse gets iterated as a MIDI note.
Close the [playnotes] subpatch window. Click on the message box labeled Crop and Flip Source Image. This sends a new
source rectangle to jit.qt.movie to flip the image horizontally, which reverses the high-low musical effect of the [playnotes]
subpatch.

Playing Tones
In the umenu labeled Use Tracking Info, choose the menu item 2 = Play MSP Tones. Double-click on the patcher
playtones object to see the contents of the [playtones] subpatch.

Use location of a color as frequency control information for MSP oscillators

Here we're using the horizontal and vertical location coordinates of the basketball as frequency values for MSP oscillators.
The equations we use to calculate those values are somewhat arbitrary, but they've been devised so as to map both
coordinates into similar frequency ranges. The horizontal coordinate is used to control the oscillator in the left audio
channel, and the vertical coordinate controls the frequency of the oscillator in the right channel.

We use the presence of incoming messages to turn MSP audio on (and fade the sound up), and if the messages are absent for
more than 200 ms, we fade the sound down and turn the audio off.

First message starts and fades in audio; lack of message for 201ms fades out and turns off audio.

Close the [playtones] subpatch window. Flip the video image horizontally by clicking on the message boxes labeled Crop
Source Image and Crop and Flip Source Image to hear the difference in the effect on the MSP oscillators.

Deriving More Information


In this tutorial we've shown a pretty straightforward implementation in which we use the location coordinates of a color
region directly to control parameters of sound synthesis or MIDI performance. With a little additional Max programming, we
could potentially derive further information about the motion of an object.

For example, by comparing an object's location in one video frame with its location in the preceding frame, we could use the
Pythagorean theorem to calculate the distance the object traveled from one frame to the next, and thus calculate its velocity.
We could also calculate the slope of its movement (), and thus (with the arctangent trig function) figure out its angle of
movement. By comparing one velocity value to the previous one, we can calculate acceleration, and so on. By comparing an
object's apparent size from one frame to the next, we can even make some crude guesses about its movement toward or away
from the camera in the "z axis" (depth).

Summary
The jit.findbounds object detects values within a certain range in each plane of a matrix, and it reports the region in the
matrix where it finds values within the specified range of each plane. This is useful for finding the location of any range of
numerical data in any type of matrix. In particular, it can be used to find the location of a particular color in a 4-plane
matrix, and thus can be used to track the movement of an object in a video.

Cropping the video image with the srcrect attribute of jit.qt.movie helps to focus on the desired part of the source image.
The jit.brcosa object is useful for adjusting the color values in the source video, making it easier to isolate and detect a
specific color or range of colors.

We can use the output of jit.findbounds to track the location of an object, and from that we can calculate other information
about the object's motion such as its velocity, direction, etc. We can use the derived information to control parameters of a
MIDI performance, MSP synthesis, or other Jitter objects.

See Also
Name Description
jit.brcosa Adjust image brightness/contrast/saturation
jit.findbounds Locate bounding dimensions for a value range
jit.matrix The Jitter Matrix!
jit.pwindow Show data in a patcher
jit.qt.movie Play or edit a QuickTime movie
MIDI Control of Video
Tutorial 26: MIDI Control of Video
The MIDIVideo Relationship
When Max was first developed it was mainly for the interactive control of musical instruments via MIDI. As computer
processor speeds increased, it became practical to use Max for processing audio signals directly with MSP, and to process
large matrices of data such as video images with Jitter. The great power of Max is that it gives you access to all of the digital
information in each of these domains MIDI, audio, and videoand helps you program interesting correlations between
them. This tutorial will focus on using incoming MIDI data to control aspects of video playback in Jitter.

The two main benefits of using MIDI for controlling video are 1) the advantage of using a physical interfacea slider, wheel,
etc.rather than a mouse dragging an onscreen control, and b) the potential to make interesting relationships between
music and video in realtime performance. There are many available MIDI controllers that provide useful physical interfaces
for video: banks of multiple sliders on fader boxes or digital mixers, jog wheels, etc. Even most synthesizer keyboards have
buttons, sliders, wheels, and foot pedals in addition to the obvious piano-like keys. For this tutorial we'll limit ourselves to
the controls that are commonly available on most MIDI keyboards.

This tutorial makes the same assumptions about your MIDI setup as are made in the Max Tutorial and the MSP Tutorial,
namely: a) that you have OMS installed, have used the OMS Setup application to describe your setup to OMS, and have used
Max's Midi Setup... command in the File menu to assign Max's virtual ports to devices in your OMS Setup, b) that you have
a 61-key MIDI synthesizer keyboard with a modulation wheel and a pitchbend wheel, and c) that the keyboard is connected
to your MIDI interface and is assigned to Max's virtual port a.

In this tutorial patch we'll play a movie, we'll use the notes from the MIDI keyboard to move around in the movie, and we'll
use various types of MIDI messages to apply effects to the video and modify it in real time.

Mapping MIDI Data for Use as Video Control Parameters


The data in MIDI channel messages (notes, pitchbend, aftertouch, etc.) is in the range 0 to 127. For the most part, the
attributes of Jitter objects expect arguments in the range 0 to 1especially when handling 4-plane 2D matrices of char data,
as with video. So one of the first tasks we need to do is map the MIDI data into the appropriate range for controlling
parameters of the Jitter objects. In the tutorial patch we show some examples of how to do this.
Open the tutorial.

In the yellow portion of the patch we have various MIDI input objects, for gathering the data generated by a keyboard
controller attached to port a: ctlin a 1 for the modulation wheel, ctlin a 7 for the volume pedal, bendin a for the pitchbend
wheel, and notein a for the keyboard. The most straightforward controls for our use are continuous controllers like the mod
wheel and the volume pedal. It's a simple matter to map their values into the 0 to 1 range, just by dividing by 127.

Map MIDI control data into a more useful 0-to-1 range

Even though both controllers have a range from 0 to 127, the mod wheel's "normal" resting position is at 0 (modulation off),
while the volume pedal's usual resting position is at some non-zero position such as 100 or 127 (volume on). Thus, they
might be useful to us in slightly different ways for controlling video effects.

The pitchbend wheel uses still another normal position. It's resting position is at 64, and it springs back to that position
when released by the user. So we want it to give us a value of 0.5 when at rest. The problem is that 64 is not exactly half way
between 0 and 127; if we simply divide by 127, a bend value of 64 will give us a result of about 0.504. So we have to treat the
"downward bend" and "upward bend" values differently, as shown in the following example.
There are 64 pitchbend values below the central value, and 63 above the center.

For the pitch information from the keyboard, the problem is a bit more complicated. First of all, most keyboards do not have
keys for all pitches 0 to 127; the normal 5-octave keyboard sends out MIDI key numbers 36 to 96. But even more
importantly, we're usually concerned not only with pitch "height" (where it lies in the 0 to 127 range), but also the musical
significance of the pitch class (C, C#, D, etc.). In our patch, we use both ways of viewing pitch. We map the key range 36 to
96 into the 0-to-1 parameter range, and we derive the pitch class with a % 12 object. (All Cs will be 0, all C#s will be 1, etc.)

Using the note-on key value to derive pitch height and pitch class

In the above example we use a couple of other handy objects to thin out the incoming note data. The poly 1 1 object allows
only one note-on message to go through at a time; it turns off the preceding note (sends it out with a velocity of 0) before
passing the new note through. That's because we only want to try to track one key number at a time. If the user plays with
legato technique (plays a note before releasing the previous one) or plays several notes in a chord "simultaneously" (i.e.,
nearly simultaneously; nothing is really simultaneous in MIDI) it might be hard to tell which note our patch is actually
tracking. The poly 1 1 object ensures that all notes except the most recently played one will be turned off in our patch, even
if the notes are still being held down on the actual MIDI keyboard. The stripnote object suppresses note-off messages, so
only the note-on key numbers will get through. We don't want to track the pitches as the notes are being turned off, we only
want the get the key number when the note is first played.

Note: We've set up the patch so that you don't really need a MIDI keyboard to try it out. You can play (silent) pseudo-
notes by clicking on the keys of the kslider object, and you can generate other values by dragging on the number boxes
labeled Mod., Vol., Bend, Key, and Vel. Needless to say, the mouse will be a bit less gratifying than a MIDI keyboard as
a physical interface, but you can at least test the patch and try out the things that are explained in this chapter.

Try out your MIDI keyboard (and wheels) to verify that MIDI messages are getting into Max OK. If not, double-click on the
MIDI input objects to select the proper input device.

Using send and receive


The workings of this patch may be a bit difficult to follow because we make liberal use of the send and receive objects. We
do this mainly to avoid what would otherwise be a ludicrous mess of patch cords. It's particularly appropriate here because
we'll be sending so many messages into and out of the jit.qt.movie object from/to so many other places in the patch. So we
use receive and send objects for the input and output of the jit.qt.movie object, and all other objects in the patch can now
communicate with it remotely.
We can communicate with jit.qt.movie no matter where it's located.

Just in case you're not familiar with the use of a semicolon (;) in a message box, we'll take a moment to point out that you
can put a semicolon, the name of a receive object, and a message in a message box, and when that message box is
triggered it will function exactly as if you had sent that message into a send object. See the following example.

A semicolon in a message box is like using a send object.

So, let's trace what happens when we send a read message to jit.qt.movie.
Click on the red message box that says ; movieA read blading.mov; movieA vol 0.

This opens the movie blading.mov. When jit.qt.movie has completed the movie-opening operation, it sends a read message
out its right outlet. If it opened the file successfully, the full message will be read blading.mov 1. (If it was unsuccessful, the
last argument will not be 1.) This message gets sent to the receive Arightoutlet object in the purple region in the bottom-
left corner of the patch. We use the route objects to detect all the messages we expect to get out of that outlet and route the
messages to the proper places elsewhere in the patch. The arguments of the read message get sent to the r read object in the
green region in the bottom-right corner of the patch. With the zl ecils 1 and sel 1 objects we check to see if the last
argument of the message was a 1. If so, that means that the read was successful, so we then go ahead and get the movie's
attributes.

If the movie was read in successfully, get its framecount , fps , rate , and dim attributes.

The remainder of the read message will be the name of the movie file, so we put that into a message box to show the user
what file is now playing. If the read was unsuccessful, the sel 1object will trigger the message failed to read movie instead.
(The delay object is there to ensure that the failure message gets put into the message box after the filename.

Using MIDI Notes to Trigger Video Clips


We have chosen to use the pitch class of the note played on the MIDI keyboard to decide where to go in the video. (There
are, of course, many ways you could choose to use MIDI to navigate through a movie or select different video segments. This
just happens to be the method we've picked for this tutorial. In a later tutorial chapter we demonstrate how to switch from
one video to another.) So, we take the total number of frames in the movie (the framecount attribute of jit.qt.movie) and
divide that by 12. We then use each note's pitch class (key % 12) to leap to a certain twelfth of the movie.
The movie blading.mov is a 12-second long video consisting of twelve 1-second edits. So in this case each different pitch
class takes us to a different scene of this short movie. (Of course, that's all very neat and convenient since we planned it that
way. But by using the movie's actual framecount, we've made it so our patch will successfully divide a movie of any length
into twelfths.)

The pitch class (5) of F above middle C takes us to frame 75, 5/12 into the movie.

The note-on velocity will turn on the toggle that starts the metro that bangs the jit.qt.movie object, and the note-off
velocity will stop the metro.
Click on the toggle labeled Show/Hide Display Window make the Display window visible. Play some notes on your MIDI
keyboard (or click on the kslider) to leap to different points in the movie.
The jit.qt.movie object's matrices go to a send Aleftoutlet object, and eventually get to the jit.pwindow via a receive
display object. Where do the jit_matrix messages go between send Aleftoutlet and receive display? They actually go into
a subpatch for video effects processing. But before we examine that subpatch, we'll discuss how we intend to control those
effects.

Routing Control Information


Earlier in this chapter we saw the various ways that the incoming MIDI data gets mapped into the 0-to-1 range for use in
controlling Jitter attributes. If you look in the yellow region of the patch, you can see that that control information goes to
five send objects: s pitch, s vel, s bend, s mod, and s vol. These are five different sources of MIDI control , and we will use
them to control up to eight different video effects linked in a series. The effects link is something like this:

movie -> rate control -> volume control -> brightness control -> saturation control -> edgedetection -> zoomin control -
> pixelation -> zoomout control -> display window

For maximum versatility, we'd like to be able to control any of those effects with any of our MIDI sources. To accomplish
that, we use a combination of objects designed for just such a purpose: matrixctrl and router. The router object takes
messages in its various inlets and routes those messages internally to any of its outlets that you specify. The matrixctrl
object (designed for controlling the MSP matrix~ object and the Max router object, not for controlling Jitter matrices per
se) provides a user-interface for specifying those routings. Take a look at the matrixctrl object in the blue region of the
patch.

Route fifth input (VOL) to second output (Volume)


matrixctrl shows input sources on vertical grid lines and output destinations on horizontal grid lines. So, if we want to route
the messages from the fifth source inlet of a router object to the second destination outlet, we need to click on the grid point
where those meet. In this example, we're asking to route the vol data to control the volume effect. Clicking at that point on
the matrixctrl grid sends a message to a router object that tells it to make this sourcedestination connection internally.
(Clicking again erases the red dot and breaks the connection in router.) In our program the router object is inside the
patcher effects subpatch, but if they were in the same patch, their connection would look like the following example.

router is the"patchbay" for Max messages, and matrixctrl is its user interface

Routing Around (Bypassing) Parts of the Patch


If we aren't using some of the video effects at a certain time (for example, maybe we don't want any zooming or pixelation),
we'll want to bypass those particular effects. In the effects subpatch we'll use Ggate and gate objects to bypass some of the
effects. To give the user easy control over which effects to use and which to bypass, we've set up checkboxes in the main
patch, using the radiogroup object. When the user clicks on one of the checkboxes, radiogroup sends the on/off status of
all of the checkboxes out its outlet, and we can use that information to switch the routing of the Ggates in the subpatch.

Zoom In, Pixelate, and Zoom Out effects are completely bypassed.

Double-click on the patcher effects object to see the contents of the effects subpatch.
The output of radiogroup is used to switch gate and Ggate objects in the subpatch.

In the subpatch, the receive Aleftoutlet object receives jit_matrix messages from the jit.qt.movie in the main patch. In the
example above, the Ggate object routes the jit_matrix message around the p brightness subpatchbypassing that effect
and the next Ggate object routes the message through the p saturation subpatch. Thus, the Ggate objects serve as
Insert/Bypass switches for each effect, and the checkboxes in the radiogroup provide the user interface for those switches.
At the end of this chain of effects, the matrix is finally passed to a send display object, which sends the matrix to the
Display window.

So, in the main patch we have two separate controls for the user to set up the routing of control data and effects. With the
matrixctrl object, MIDI data from a source (or more than one source) can be routed to any (or many) of the effects. With
the radiogroup checkboxes, the user can elect to insert effects or bypass one or more effect entirely.
Close the [effects] subpatch window. Use the checkboxes to select which video effects you want to insert, and use the
matrixctrl to assign MIDI sources to the control of those effects. Play around with different combinations to see what types
of control are most intuitive (and work in the context of a keyboard performance) for each effect.

User Control of Video Effects


Each video effect in this tutorial patch is pretty simple, so we won't describe each one in detail. We'll just point out a few
traits that might be instructive as you decide how you want to apply realtime user control of video effects.

Double-click on the patcher effects object once again to open the effects subpatch window. Double-click on the p
brightness object to see a typical one of these video effect subpatches.

The 0 to 1 data is scaled to the range 0 to 2 for controlling the brightness.

The jit_matrix message comes in the left inlet and the control data (in the range 0 to 1) comes in the right inlet. The control
data is scaled to an appropriate range, and is used to alter an attribute in a Jitter object, and the processed matrix is passed
on out to the next effect in the chain. The p saturation and p zoomin subpatches work pretty similarly. The p zoomout
subpatch is also similar, but uses a slightly more involved mathematical expression, shown in the following example.
The 0 to 1 data is remapped as an exponential curve from 1 to 0.125.

In the above example the incoming control data (0 to 1) is used to calculate the exponent of a power of 2. When the control
data is 0, the expression will be 2 0=1. When the control data is 1, the expression will be 2 -3=0.125. Thus, the actual control
value is flipped to have reverse meaning and to describe an exponential curve instead of a linear change.

In the p edges subpatch, the object that's really creating the effect is a Sobel edge detection object called jit.sobel. What
we're controlling is the mix between the original input image and the edge-detector's output. So we're really just controlling
the xfade parameter of a jit.xfade object (described in detail in Tutorial 8).
The p pixelate subpatch reduces the dimensions of the image matrix (a process known as downsampling), so that some of
the data must be discarded and the image will be pixelated when it's displayed in the 320x240 Display window. (This
method of pixelation is detailed in Tutorial 14.) We got the dimensions of the original image by retrieving the dim attribute
of jit.qt.movie (back when we first read in the movie), so we use our control data to scale those dimensions by some factor
from 0 to 0.0625, and we use those new dimensions to set the dim attribute of a jit.matrix object, as shown in the following
example.

Downsampling an image causes it to be pixelated when it's upsampled to its original dimensions.

The p rate and p volume subpatches are a bit different because we're not actually processing a matrix in those subpatches,
we're just changing an attribute of jit.qt.movie in the main patch. The following example shows the contents of the p rate
subpatch.

Send the result to any rrate object, and also use it so set the rate attribute of jit.qt.movie

Summary
The physical interface afforded by MIDI controllers gives you a good way to control video in real time in Jitter, and
particularly to make correlations between music and video. Each type of controllerkeyboard, pitchbend wheel, modulation
wheel, volume pedal, etc.implies a different type of control mapping. All the data of MIDI channel messages falls in the
range 0 to 127, but the way you map that data to control Jitter attributes varies depending on the effect you're trying to
produce. In this patch, as a starting point we mapped all the pertinent MIDI data into the range 0 to 1, then we scaled that
range as necessary for each video effect.

Because Jitter objects receive so many different messages, it's often necessary to use a message box to construct the desired
message. If you find yourself directing many different messages to the same place(s) from different parts of the patch, you
might consider using the message box's remote message-sending capabilitya semicolon plus the name of a receive object
to reduce the patchcord spaghetti in your patches.

If you need to send Max messages from many different sources to many different destinations, and you need the ability to
reconfigure the routing of source messages to the desired destinations, the router object functions well as a configurable
"patch bay" for Max messages. The matrixctrl object provides a readymade user interface for configuring the internal
sourcedestination patching within a router. in this patch, we used a matrixctrl and router to allow the user to direct any of
five types of MIDI control data to any of eight different video effects. We used a radiogroup object to create a bank of
checkboxes that act as Insert/Bypass switches for the video effects.

See Also
Name Description
bendin Output MIDI pitch bend values
ctlin Output received MIDI control values
jit.matrix The Jitter Matrix!
jit.pwindow Show data in a patcher
jit.qt.movie Play or edit a QuickTime movie
jit.rota Scale/rotate in 2D
jit.scalebias Multiply and add
jit.sobel Sobel and Prewitt gradient edge detector
jit.xfade Crossfade between 2 matrices
matrixctrl Matrix switch control
notein Receive MIDI note messages
radiogroup Radio button/check box user interface
router Route messages to multiple locations
stripnote Filter out note-off messages
zl Process lists in many ways
Using MSP Audio in a Jitter Matrix
Tutorial 27: Using MSP Audio in a Jitter Matrix
This tutorial shows how to copy an MSP audio signal into a Jitter matrix using an object called jit.poke~. Along the way,
we'll investigate how to use the soundtrack from a QuickTime movie in the MSP signal network using the sound output
component attribute of the jit.qt.movie object and a new MSP object called spigot~.
This tutorial assumes familiarity with routing MSP signals using send~ and receive~. It also uses a simple delay network
using tapin~/tapout~ objects. Tutorial 4 and Tutorial 27 in the MSP manual cover these topics.
Open the tutorial.

The jit.qt.movie object at the top left of the tutorial patch reads a QuickTime movie called rca.mov upon opening.

Our jit.qt.movie object

Start the metro object at the top of the patch by clicking the toggle box. You will see an image in the lefthand jit.pwindow
object below the jit.qt.movie object. You won't see anything in the other jit.pwindow objects yet, nor will you hear any
sound.

Our jit.qt.movie object has two attributes set in its object box in addition to its dim attribute (320 by 240 cells). The loop
attribute with a value of 2 tells the jit.qt.movie object to loop the movie as a palindrome. Once the playback of the movie
reaches the end, it will play backwards to the beginning of the file, rather than looping around to the beginning and playing
forward (the default behavior, when the loop attribute is set to 1). If you watch the movie, you'll see that the arm
manipulating the oscillator control moves up and then down again in an endless loop. The movie actually only contains
footage of the arm moving upward, but the loop attribute we've used reverses the playback in the second half of the loop.

The Sound Output Component


The second attribute we've set in our jit.qt.movie object sets the Sound Output Component (soc) for that instance of the
jit.qt.movie object. The name specified as an argument to the soc attribute (in this case gliss) specifies a new sound output
component that MSP can use to acquire the soundtrack of the movie loaded into the jit.qt.movie object. By default, the soc
attribute is set to none, which routes the movie's audio output directly to the Sound Manager. A named soc attribute routes
the audio to a spigot~ object with the same name as the component, allowing you to access the audio signal in MSP:

The spigot~ object

The spigot~ object in the upper-right hand corner of the tutorial patch has an argument (gliss) which matches the soc
attribute of our jit.qt.movie object. If a movie file loaded into that jit.qt.movie object has a soundtrack (which the rca.mov
file conveniently does), the audio from the movie is sent out as MSP signals from the spigot~. Note that the spigot~ object
has two outlets, which correspond to the left and right audio channels of the movie soundtrack. Our rca.mov file has a
monaural soundtrack, so we only need to use one of the outlets in our patch.
Important: The soc attribute of the jit.qt.movie object allows you to create a separate sound output component for
each jit.qt.movie object in your patch. You can use as many spigot~ objects as you like, each with a unique name, to
grab the audio from multiple QuickTime movies. It's important to note, however, that you can only have one spigot~
object per sound output component, and each jit.qt.movie object must have a unique soc attribute (unless, of course,
the soc is set to nonethe Sound Manager can take the sound from as many movies as you wish). Once you have
multiple movie audio tracks as MSP signals you can mix them as you please.

Start the dac~ object at the bottom of the patch by clicking the toggle box attached to it. You will see images appear in the
remaining jit.pwindow objects and will see a signal level appear in the meter~ object attached to the spigot~. If you turn up
the gain~ slider attached to the dac~, you should begin to hear sound out of whatever device you currently have selected as
your MSP audio driver. For more information on how to setup your computer's audio system with MSP, consult the Audio
I/O Chapter in the MSP manual.

Receiving the audio signal from the spigot~

The soundtrack from the rca.mov file is sent as an MSP signal from the spigot~ object into a two-tap delay line (generated
by the tapin~ and tapout~ objects in the patch). The dry audio signal is sent to a send~ object with the name red attached
to it; the two delay taps are sent to send~ objects named green and blue, respectively. The three audio signals are output by
named receive~ objects and summed into the gain~ object at the bottom of the patch, allowing you to hear all of them at
once.

Adjust the delay times using the number box objects labeled Delay times (green/blue) attached to the tapout~ objects.
You can adjust the delays up to a maximum length of 1000 milliseconds (the maximum delay time allocated by our tapin~
object).

Poke~ing Around
The righthand jit.pwindow object at the top of the tutorial patch shows the output of a jit.matrix named scope, which also
gets bang messages from the metro object at the top of the patch:

The output of the scopejit.matrix

The scope Jitter matrix is generated by three jit.poke~ objects at the right of the tutorial patch, which write MSP audio
signals into cells in the matrix. These cells, when displayed in the jit.pwindow object, portray an oscilloscope view of the
movie soundtrack, with the dry and two delayed signals appearing as the colors red, green, and blue, respectively.
The three jit.poke~ objects, writing into the scope matrix

The three similar regions at the right of the screen use the jit.poke~ object to write MSP signal data into our scope matrix.
The jit.poke~ object takes three arguments: the name of the Jitter matrix to write into, the number of dim inlets to use, and
the plane of the destination matrix to write numbers to. All three jit.poke~ objects in our patch write into the matrix scope.
Since scope is a 2-dimensional matrix, we need 2 inlets to specify where to write the data (one inlet for the column and one
inlet for the row). The three objects differ in that they each write to a different plane of the scope matrix.

The first inlet of the jit.poke~ object provides the value to write into the matrix cell specified by the other two inlets, which
take signals to specify the cell location. We use a sig~ object with a value of 1 to write a constant value into our current
position in the scope matrix. The value of 1 gets interpreted as 255 when writing into a matrix containing char data (which
is what we're doing in this case).

The other two inlets in our jit.poke~ objects determine where in the output matrix they should write data (this set of
coordinates defines the write pointer for the objectyou could think of this as the location of the record head, only with two
dimensions instead of one). The rightmost inlet receives the audio signal from our named receive~ objects and sets the
vertical (dim 1) coordinate of the write pointer to correspond to the amplitude of the signal. The *~ and +~ objects in the
patch scale the output of the audio signal from between -1 and 1 (the typical range for an audio signal) to between 0 and
239 (the range of the vertical dimension of our output matrix).

Sync or Swim
The middle inlet to our jit.poke~ object receives a sync signal that specifies where along the horizontal axis of the matrix we
write the current amplitude from the audio signal. This signal is unrelated to the audio data coming from the movieyou
could think of it as the horizontal refresh rate of the virtual oscilloscope we've made in this patch. The sync signal is
generated by a phasor~ object in the middle of the tutorial patch:

Generating the horizontal sync signal for our jit.poke~ objects

Our phasor~ object generates a repeating ramp signal from 0 to (nearly) 1. The *~ below it rescales this signal to generate
values appropriate to the width of our matrix (0 to 319). This signal is then passed to a send~ object with the name h_sync,
which forwards the signal to receive~ objects connected to the middle inlets of our jit.poke~ objects. The frequency of the
phasor~ (specified by the number box connected to its first inlet) determines the rate at which our jit.poke~ objects scan
from the left to right through the matrix.

Try changing the frequency of the phasor~ by changing the number box labeled Horizontal scan rate (Hz). Notice how at
higher frequencies you can see the waveform generated by the movie audio in more detail. If you set the rate to a negative
value, the matrix will be written backwards (i.e. from right to left).

The dry audio signal and the two delayed outputs are visualized as the three visible planes of our scope matrix (1, 2, and 3,
or red, green, and blue). When the cells written by the jit.poke~ objects overlap, different color combinations will appear
in the output matrix.

Now that we understand how the matrix is being written, we need to look into how the matrix clears itself every time a
horizontal scan is completed. The relevant parts of the patch are shown below:

Detect when the horizontal sync resets and clear the matrix

The change~ object outputs a value of 1 when the ramp generated by the phasor~ object is on the increase. When the
phasor~ snaps back to 0 at the end of the ramp, change~ will briefly output a value of -1. The ==~ operator, which
outputs a 1 when the change~ object does, will output a 0 at that point. When the phasor~ begins to ramp again, the ==~
object will output a 1, triggering a bang from the edge~ object (which detects a zero to non-zero transition in the last signal
vector). The bang is then sent to a receive object named reset, which triggers a clear message to the jit.matrix object. As a
result, our scope matrix is cleared every time the phasor~ restarts its ramp.

Putting it all Together


Our two Jitter matrices (the image from the jit.qt.movie object and the oscilloscope drawn by our jit.poke~ objects) are
composited into a final matrix by the jit.op object:

Compositing the two matrices using jit.op

The op attribute we've specified initially for our jit.op object is *. As a result, our composite is made from the multiplication
of the two matrices. Since most of the cells in our scope matrix are 0 (black), you only see the movie image appear in those
cells and planes where the jit.poke~ objects have traced the waveform.
Change the op attribute of the jit.op object by clicking on some of the message boxes attached to the prepend object to
the right of the jit.pwindow showing the scope matrix. Notice how the different arithmetic operators change the
compositing operation of the two matrices.

Summary
The soc attribute of the jit.qt.movie object lets you define a named Sound Output Component. The spigot~ object lets you
access the soundtrack of a QuickTime movie as an MSP signal by giving it an argument that matches the soc attribute of the
jit.qt.movie object playing the movie.

You can use the jit.poke~ object to write data from MSP signals into a named Jitter matrix. The jit.poke~ object takes
arguments in the form of the name of the matrix to write to, the number of inlets with which to specify cell coordinates, and
the plane to write to in the matrix. The first inlet of jit.poke~ takes the value to be written into the matrix. Subsequent inlets
take MSP signals that specify the cell location in the matrix in which data should be written.

See Also
Name Description
change~ Report signal direction
dac~ Audio output and on/off
edge~ Detect logical signal transitions
jit.matrix The Jitter Matrix!
jit.op Apply binary or unary operators
jit.poke~ Write an audio signal into a matrix
jit.pwindow Show data in a patcher
jit.qt.movie Play or edit a QuickTime movie
phasor~ Generate sawtooth signals
spigot~ Route QT audio into MSP
tapin~ Input to a delay line
tapout~ Output from a delay line
Audio Control of Video
Tutorial 28: Audio Control of Video
Audio as a Control Source
This tutorial demonstrates how to track the amplitude of an MSP audio signal, how to use the tracked amplitude to detect
discrete events in the sound, and how to apply that information to trigger images and control video effects.
Open the tutorial.

In the upper-right corner of the patch we've made it easy for you to try out either of two video sources: the audio input of the
computer or a pre-recorded soundfile.

The popup menu lets you select one of two audio sources: adc~ or sfplay~

We've used a loadbang object (in the upper-middle part of the patch) to open an AIFF soundfile talk.aiff and a QuickTime
movie dishes.mov, and to initialize the settings of the user interface objects with a preset. So, in the above example, the
umenu has already selected the sfplay~ object as the sound source, the soundfile has already been opened by the open
talk.aiff message, the rate of sfplay~ has been set to 1, and the output volume has been set to 0.5. The left channel of the
sound source (the left outlet of the left selector~ object) is connected to another part of the patch, which will track the
sound's amplitude.

Tracking Peak Amplitude of an Audio Signal


To track the sound's amplitude for use as control data in Max, we could use the snapshot~ object to obtain the
instantaneous amplitude of the sound, or the avg~ object to obtain the average magnitude of the signal since the last time it
was checked, or the peakamp~ object to obtain the peak magnitude of the signal since the last time it was checked. We've
elected to track the peak amplitude of the signal with peakamp~. Every time it receives a bang, peakamp~ reports the
absolute value of the peak amplitude of the signal it has received in its left inlet. Alternatively, you can set it to report the
peak amplitude automatically at regular intervals, by sending a non-zero time interval (in milliseconds) in its right inlet, as
shown in the following example.

A non-zero number in the right inlet is a reporting time interval in milliseconds

Every 10 milliseconds, peakamp~ will send out the peak signal amplitude it has received since the previous report. We've
given ourselves the option of turning off peakamp~'s timer and using the metro that's controlling the video display rate to
bang peakamp~, but the built-in timing capability of peakamp~ allows us to set the audio tracking time independently of
the video display rate.
Using Decibels
We actually perceive the intensity of a sound not so much as a linear function of its amplitude, but really more as a function
of its relative level in decibels. This means that more than half the sound pressure level we're capable of hearing from MSP
resides in the bottom 1% of its linear amplitude, in the range between 0 and 0.01! For that reason, it's often more
appropriate to deal with sound levels on the logarithmic decibel scale, rather than as a straight amplitude value. So we
convert the amplitude into decibels, using the p AtodB subpatch (which is identical to the AtodB subpatch used in the MSP
Tutorial 4).

The contents of the [AtodB] subpatch

The [AtodB] subpatch takes the peak amplitude reported by peakamp~ and converts it to decibels, with an amplitude of 1
being 0 dB and all lesser amplitudes having a negative decibel value .

Convert amplitude to a decibel value, relative to a reference amplitude of 1

Technical Detail: The formula for conversion of amplitude into decibels is:

where A0 is a reference amplitude and A is the amplitude being measured.

The decibel scale is discussed in the "Digital Audio" and "Tutorial 4" sections of the MSP manual.

Focusing on a Range of Amplitudes


In many recordings and live audio situations, there's quite a bit of low-level sound that we don't really consider to be part of
what we're trying to analyze. The sound we really care about may only occupy a certain portion of the decibel range that MSP
can cover. (In some recordings the music is compressed into an extremely small range to achieve a particular effect. Even in
many uncompressed recordings, the most important sounds may all be in a small dynamic range.) The level of the soft
unwanted sound is termed the noise floor. It would be nice if we could analyze only those sounds that are above the noise
floor.

The patcher dBexpander subpatch lets us control the dB level of the tracked amplitude and set a noise floor threshold
beneath which we want to ignore the signal. The subpatch takes the levels we do want to use, and expands them to fill the
full range of the decibel scale from 0 dB down to 120 dB. In the following example, we have specified a noise floor
threshold of 36 dB. The amplitude of the MSP signal at this moment is 0.251189, which is a level of 12dB. The subpatch
expands that level (originally 12 in the range from 0 down to 36) so that it occupies a comparable position in the range
from 0 down to 120. The resulting level is 40 dB, which is sent out the right outlet of the subpatch. The level relative to
the noise floor is sent out the left outlet expressed on a scale from 0 to 1, which is a useful control range in Jitter. In this
example, the input level of 12 dB is 24 dB greater than the noise floor; that is, it's 2/ 3 of the way to the maximum in the
specified 36 dB range.
Convert linear amplitude in the region above -36dB into full range

You can apply this value as control data for Jitter. Turn on the toggle labeled Use Display Framerate. This will
temporarily turn off the internal timer of peakamp~ and will use the bangs from the metro instead. Turn on the toggle
labeled Audio On/Off to start MSP audio processing. Click on the message box containing the number 1 above the sfplay~
object to start the playback of the sound file. Turn on the toggle labeled Display Movie to start the video playback. The peak
amplitude of the audio is reported at the same rate as the movie matrix is displayedevery 25 milliseconds. The tracked
decibel level40 values per secondis displayed in the green and black multislider labeled expanded level. The level,
mapped into the range 0 to 1, is used to change the val attribute of the jit.op object, affecting the displayed video. You can
scale the range of that value up or down with the number box labeled Effect Strength. Values in the range 0.5 to 1.5 have the
most effect on the image.

Audio Event Detection


In the preceding section we tracked the amplitude envelope of the sound and used the peak amplitude to get a new control
value for every frame of the video. We can also analyze the sound on a different structural level, tracking the rhythm of
individual events in the sound: notes in a piece of music, words in spoken text, etc. To do that, we'll need to detect when the
amplitude increases past a particular threshold, signifying the attack of the sound, and when the sound has gone below the
threshold for a sufficient time for the event to be considered over. We do this inside the patcher detectevent subpatch. In
the main patch, we provide three parameters for the [detectevent] subpatch: the Note-on Threshold (the level above which
the sound must rise to designate an "event" or "note"), the Min. Note Duration (a time the subpatch will wait before looking
for a level that goes back below the threshold), and the Min. Off Time (the amount of time that the level must remain below
the threshold for the note to be considered ended). In the following example a "note" event will be reported when the level
exceeds 30 dB, and the note will only be considered off when the level stays below 30 dB for at least 25 milliseconds.
Since the subpatch will wait at least 50 ms before it even begins looking for a note-off level, the total duration of each note
will be at least 75 milliseconds.

When the level exceeds the threshold and reaches a local maximum, an audio event is reported.

To see the contents of the subpatch, double-click on the patcher detectevent object.
Event-detection based on amplitude exceeding a threshold

The comments in the subpatch explain the procedure pretty succinctly. When a new level comes in the left inlet, two
conditions must be satisfied: the level must be greater than the threshold and there must not already be a note on. If both
those conditions are met, then we keep watching the amplitude until it stops increasing, at which point we consider the note
to be fully on so we send the number 1 out the right outlet and send the peak level out the left outlet. We wait the "minimum
note time", then open the gate to begin looking for indications (from the > object) that the level has gone below the
threshold. Once such a level has been detected, we wait the "minimum off time" before deciding that the note is off. If
another level above the threshold comes before the minimum off time has elapsed, the delay object is stopped and a new
note-off level must detected. When the note is truly off, a 0 is sent out the right outlet, the fact that the note has been turned
off is noted (in the == 0 object), and the gate is closed again. It's now ready for the next time that the threshold is passed.
Close the [detectevent] subpatch window. For this event-detector to work well on fast-changing sounds, the peak amplitude
should usually be tracked at a fairly rapid rate. Turn off the Use Display Rate toggle so that the peakamp~ object will use
its internal timer at an interval of every 10 ms.

In the main patch you can see three demonstrations of ways to use the output of the [detectevent] subpatch. In the bottom
right corner of the patch we use the 1 from the right outlet of patcher detectevent to trigger another subpatch, patcher
flashbulbs, which places random colored dots in a display window. We take the value out of the left outlet of patcher
detectevent and expand its range just the way we did for the original audio level, so that the value signifying the "note
amplitude" can cover the full available range. We use that to trigger MIDI notes, and also to choose different pictures to
display. Let's look at each of those procedures briefly.

Using Audio Event Information


The simplest use of an audio event is just to trigger something else when an event occurs. Whenever an audio event is
detected, we trigger the patcher flashbulbs subpatch. That subpatch generates a 16x12 matrix of random colors, then uses
scaling to turn most of the colors to black, leaving only a few remaining cells with color. When that matrix goes out to the
main patch, those cells are upsampled with interpolation in the jit.pwindow and look like flashes of colored light.
Subsequent level values from peakamp~ are used in the [flashbulbs] subpatch to bang a bline object, causing the colors to
fade away after 20 bangs.
The [flashbulbs] subpatch

In the patcher pickpicture subpatch, we simply divide the event amplitudes up into five equal ranges, and use those values
to trigger the display of one of five different pictures.

In the following example, you can see the use of audio information to trigger MIDI notes.

Peak level determines pitch and velocity of a MIDI note

We use the expanded decibel value coming out of the right outlet of the patcher expander to derive MIDI pitch and velocity
values. We first put the values in the range 0 to 120, then use those values as MIDI velocities and also map them into the
range 96 to 36 for use as MIDI key numbers. (Note that we invert the range so as to assign louder events to lower MIDI
notes rather than higher ones, in order to give them more musical weight.) The note durations may set by the Min. Note
Duration number box, or they may be set independently by entering a duration in the number box just above makenote's
duration inlet.

You can experiment further with this patch in a number of ways: by changing the rate of the audio file with the Rate
number box, by opening different soundfiles and movies, by choosing Sound Input from the umenu to use live sound input,
and by changing the various tracking parameters such as Reporting Interval, Noise Floor Threshold, Note-On Threshold,
and Min. Note Duration.

Summary
We've demonstrated how to track the peak amplitude of a sound with peakamp~, how to convert linear amplitude to
decibels, and how to detect audio events by checking to see if the amplitude level has exceeded a certain threshold. We used
the information we derived about the amplitude and the and peak events to trigger images algorithmically, select from
preloaded images, play MIDI notes, and alter video effects.

See Also
Name Description
expr Evaluate a mathematical expression
jit.brcosa Adjust image brightness/contrast/saturation
jit.noise Generate white noise
jit.op Apply binary or unary operators
jit.pwindow Show data in a patcher
jit.scalebias Multiply and add
peak Output larger numbers
sfplay~ Play audio file from disk
Using the Alpha Channel
Tutorial 29: Using the Alpha Channel
In this tutorial we'll look at how to composite two images using the alpha channel of a 4-plane char Jitter matrix as a
transparency mask. We'll explore this concept as a way to superimpose subtitles generated by the jit.lcd object over a movie
image.
Open the tutorial.

The upper-lefthand region of the tutorial patch contains a jit.qt.movie object that reads the file ozone.mov when the patch
opens. The metro object outputs a new matrix from the jit.qt.movie object every 33 milliseconds and polls the time
attribute of the object (the current playback position of the movie, in QuickTime time units) by using a trigger object:

Play back the movie, getting the current time position with each new matrix

Start viewing the movie by clicking the toggle box attached to the metro. The jit.qt.movie object will start to output
matrices as well as the current playback position within the movie. You should see the movie (with subtitles!) appear in the
jit.pwindow at the bottom of the patch.

Nice kitty

First, we'll look at how the subtitles are being generated. Then we'll investigate how we composite them with the image from
the movie using the alpha channel.

The jit.lcd object


The subtitles in our patch are generated by sending messages to the jit.lcd object (at the top of the patch). The arguments to
jit.lcd specify the planecount, type, and dim of the matrix generated by the object (jit.lcd only supports 4-plane char
matrices). Thejit.lcd object takes messages in the form of QuickDraw commands, and draws them into an output matrix
when it receives a bang. We initialize our jit.lcd object by giving it commands to set its font and textface for drawing text
and its foreground (frgb) and background (brgb) color (in lists of RGB values). We then clear the jit.lcd object's internal
image and send out an empty matrix with a bang:
An initialized jit.lcd object

Note: The jit.lcd object has the same complete set of QuickDraw commands and functions that are available in the Max
lcd object. Though we'll be using it in this patch for the purpose of generating text images, jit.lcd can be used to
generate all manner of 2-dimensional vector graphics as well. Tutorial 43 in the Max Tutorials and Topics manual
demonstrates some of the features of the lcd object, all of which can be applied just as easily to jit.lcd.

The jit.lcd object outputs its matrix into a jit.rgb2luma object, which converts the 4-plane image output by jit.lcd into a 1-
plane grayscale image. The jit.rgb2luma object generates a matrix containing the luminosity value of each cell in the input
matrix. This 1-plane matrix is then sent to a send object with the name alphamask and to a jit.pwindow object so we can
view it. Note that the jit.pwindow object has its border attribute set to 1. As a result, we can see a 1-pixel black border
around the white image inside.

Our jit.lcd object also receives messages from elsewhere in the patch (via the receive object named lcd attached to it). The
subtitles are generated automatically by looking for certain times in the movie playback:

Parsing the time values from the jit.qt.movie object

The jit.qt.movie object outputs its current playback position with every tick of the metro object, thanks to the t gettime b
we have between the two. The time attribute is sent out the right outlet of the jit.qt.movie object, where we can use a route
object to strip it of its message selector (time). We divide the value by 100 so that we can search for a specific time more
accurately. Since the metro only queries the time every 33 milliseconds, it's entirely possible that we'll completely skip over
a specific time -- dividing the time value by 100 makes it easier to find the point in the movie we want.

The time values are sent through a gate object where you can disable the subtitles if you so choose:

Control the flow of the time values with a gate object

Click the toggle box attached to the gate. The subtitles should disappear. You can resume the subtitles by clicking the
toggle box again.

The subtitles are finally generated when the time values 21 and 40 make it past the gate object. The select object sends out
a bang when those values arrive. This triggers commands from the message boxes to jit.lcd:
Performing the subtitling based on the time values

The clear message to jit.lcd erases the drawing canvas, filling all the pixels with white (our chosen background color). The
moveto message moves the cursor of the jit.lcd object to a specific coordinate from which it will draw subsequent
commands. The write message draws text into the matrix using the currently selected font and textface. Once we've written
in our subtitles, we send the object a bang to make it output a new matrix. With every subtitle, we also send a bang to a
delay object, which clears and resends the matrix 1000 milliseconds later, erasing the title.

Make Your Own Titles


The region of the tutorial patch to the right (with the magenta background) lets you use the textedit object to generate your
own subtitles. The number box labelled Offset determines the horizontal offset for the text. The trigger object allows you to
send all the necessary QuickDraw commands to the jit.lcd object in the correct order.

Make your own subtitles

Turn off the automatic subtitling with the toggle box above the gate. Type some text into the textedit box and hit the
return key. The text will appear superimposed over the image.

The new subtitle over the image

Now that we understand how the titles are generated, lets take a look at how they get composited over the movie.
The Alpha Channel
The alpha channel of an ARGB image defines its transparency when it is composited with a second image. If a pixel has an
alpha channel of 0 it is considered completely transparent when composited onto another image. If a pixel's alpha channel is
set to 255 it is considered completely opaque, and will show at full opacity when composited. Intermediate values will cause
the pixel to fade smoothly between the first and second image. In 4-plane char Jitter matrices, data stored in plane 0 of the
matrix is considered to be the alpha channel.

Technical Detail: Color systems and software environments differ on whether the alpha channel describes the
transparency or the opacity of an image. In QuickTime movies (and hence in Jitter) an alpha value of 255 means that
the pixel is fully opaque. You may encounter programs where the opposite is true (i.e. an alpha value of 255 denotes
full transparency). The mode attribute of the jit.alphablend object lets you treat the alpha channel in either way. The
default mode of 0 treats increasing alpha values as more opaque, while setting the mode attribute to 1 causes the
object to treat increasing alpha values as more transparent.

The jit.alphablend object uses the values stored in the alpha channel (plane 0) of the matrix arriving in the left inlet to
perform a crossfade (on a cell-by-cell basis) between the matrices arriving in its two inlets. Our patch replaces plane 0 of the
jit.qt.movie object's output matrix with the output of the jit.lcd object. We then use this new alpha channel with the
jit.alphablend object to crossfade between the movie and an inverted copy of itself:

Inserting a new alpha channel with the jit.pack object

We use the jit.unpack and jit.pack objects to strip the original alpha channel from our QuickTime movie. The 1-plane
matrix containing the subtitle arrives at the jit.pack object from the receive object above it. Notice how the trigger object is
used to force jit.pack to output new matrices even when no new matrix has arrived from the receive (jit.pack, like the Max
pack object, will only output a matrix when it has received a new matrix or a bang in its leftmost inlet). The jit.op object
creates a negative of the original matrix from the QuickTime movie (by subtracting the matrix values from 255 using the !-
operator). The jit.alphablend object then uses our new alpha channel -- white values in the subtitle matrix cause the original
image to be retained, while black values bring in the inverted image from the righthand matrix.

Different techniques are often used for subtitling. The technique of superimposing white text over an image (sometimes with
a black border around it) is far more common than the technique used here of filling an alpha mask with an inverted image.
However, doing our subtitling this way gives us a perfect excuse to use the jit.alphablend object, and may give you more
legible subtitles in situations where the background image has areas of high contrast.

The image below shows the compositing process with jit.pwindow objects showing intermediate steps:
The compositing process, showing intermediate steps

Summary
The jit.lcd object offers a complete set of QuickDraw commands to draw text and 2-dimensional graphics into a Jitter
matrix. The jit.rgb2luma object converts a 4-plane ARGB matrix to a 1-plane grayscale matrix containing luminance data.
You can replace the alpha channel (plane 0) of an image with a 1-plane matrix using the jit.pack object. The jit.alphablend
object crossfades two images on a cell-by-cell basis based on the alpha channel of the lefthand matrix.

See Also
Name Description
gate Pass input to an outlet
jit.alphablend Blend two images with an alpha channel image
jit.lcd QuickDraw wrapper
jit.op Apply binary or unary operators
jit.pack Make a multiplane matrix out of single plane matrices
jit.pwindow Show data in a patcher
jit.qt.movie Play or edit a QuickTime movie
jit.rgb2luma Converts RGB to monochrome (luminance)
jit.unpack Make multiple single plane matrices out of a multiplane matrix
text Format messages as a text file
Drawing 3D text
Tutorial 30: Drawing 3D text
This tutorial shows you how to draw and position 3D text in a jit.window object using the jit.gl.text3d and jit.gl.render
objects. Along the way, we will cover the basics of drawing OpenGL graphics using the jit.gl.render object.
The jit.gl.text3d object is one of the many Jitter OpenGL drawing objects that work in conjunction with the jit.gl.render
object. OpenGL is a cross-platform standard for drawing 2D and 3D graphics, designed to describe images so that they can
be drawn by graphics coprocessors. These coprocessors, also known Graphics Processor Units or GPUs, speed up drawing
operations enormously, allowing complex scenes made of textured polygons to be animated in real time. OpenGL graphics
can help you create faster visual displays or interfaces without bogging down your computers CPU.
Open the tutorial.

In the lower left of the patch, there is a jit.window object named hello. This window will be the destination for our OpenGL
drawing.
Click on the toggle labeled Start Rendering.
The toggle starts the qmetro object,which sends bang messages to a trigger object. For each bang received at its inlet, the
trigger object sends the message erase out its right outlet, and then a bang message out its left outlet. These messages are
sent to the jit.gl.renderhello object.

Creating a Drawing Context


All OpenGL graphics in Jitter are drawn with the aid of jit.gl.render objects. Each jit.gl.render object must refer to a
named destination for drawing. You can specify this destination using an initial argument to jit.gl.render. So in this case,
jit.gl.renderhello creates a jit.gl.render object that will draw to the destination window that we have named hello.

Its important to note that hello is not the name of the jit.gl.render objectonly its destination.

We refer to this combination of a jit.gl.render object and a named destination as a drawing context. A drawing context is
required for OpenGL rendering. The objects on the left side of this patch are sufficient to build a valid drawing context, and
so when you click on the toggle, the message jit.gl.render: building GL on window hello appears in the Max window.
This tells you that the context is being created.

A jit.gl.render object and a named destination create a drawing context

GL Objects in the Context


Click on the message box reading Hello\, Jitter!.

Technical Detail: The qmetro object is needed in this patch because, unlike most previous tutorial patches, there are no
jit.matrix objects present. In complex patches, the drawing or matrix calculations being repeatedly triggered by a
metro object may not complete before the next bang is scheduled to arrive. In this example, this situation would occur
if the text took more than 40 milliseconds to render. Normally, the Max scheduler would place this bang on its queue
a list of pending messages. Max is not normally allowed to drop messages from the queue. So in this patch, if each
bang generated a sequence of events that take longer than 40 milliseconds, and no dropping of messages was allowed,
the queue would eventually overflow, or run out of space to store additional pending messages. Then the scheduler
would stop, and so would your show! This is probably not what you had in mind. The qmetro object (which is really
just a combination of a metro object and the jit.qball objectsee Tutorial 16) helps you avoid this situation by
dropping any bang messages that are still pending during a calculation. If a bang is scheduled to occur while the rest
of the patch is rendering, it will be placed in a queue. If that bang still hasn't been passed to the rest of the patch by the
time the next bang occurs, the first bang will be usurped by the second, which will be placed next in the queue. And so
on.

Lets say the output of a metro object set to output a bang every 10 milliseconds is sent to a jit.qt.movieobject,
followed by some effects that take 100 milliseconds per frame to draw. So the jit.qt.movie object will receive 10 bang
messages during the time the effects are being calculated. The jit.qt.movie object knows in this case that the
processing is not yet complete, and instead of sending out ten jit_matrix messages next time it has a chance, it drops
all but one. While the jit.qt.movie and jit.matrix objects have this capability built in, the jit.gl.render object does not.
This is because the jit.gl.render object will often need matching groups of messages in order to draw a frame properly.
In this example, the erase message is needed to clear the screen, and the bang message draws the text. If an erase
message was dropped to avoid overflowing the queue, multiple bang messages might be processed in a row, and
multiple copies of the text would be drawn at once, which is not what we want to do. As patches get more complex,
different kinds of visual artifacts might result. So, the qmetro object is provided to let the designer of the patch decide
what messages to drop from the queue. In this example, as in most cases, simply substituting qmetro objects for
metro objects insures that the drawing will always look correct, and the queue will never overflow.

Common 3D Attributes
All Jitter OpenGL objects (which all begin with "jit.gl") share a common set of attributes that allow them to be positioned in
3D space, colored, and otherwise modifiedthe GL group. Drawing 3D graphics can be a fairly complex task. The ob3d
group simplifies this by insuring that the messages you learn to draw one 3D object will work with all of them, whenever
possible. These common attributes are fully documented in the GL group section of the Jitter Object Reference. To
introduce the 3D group here, we will demonstrate the position, rotation, scale and axes attributes by manipulating the
jit.gl.text3d object.

We can add a set of spatial axes to the jit.gl.text3d object to make our spatial manipulations easier to see and understand
it's both easier to see how the text object is oriented, and also to see additional information about exactly where the objects
origin is.

Click on the toggle connected to the message box reading axes $1 in order to see the 3d objects axes.

The 3D text at the origin

The x axis, drawn in in red, points to the right. Zero is at the center of the screen, and increasing x values move in the
direction of the right of the screen. The y axis, drawn in green, points upwards, and the z axis, drawn in blue, points out of
the screen towards you (since it is pointed directly toward you, you will only see a small blue dot). These axes represent the
objects local coordinate system as it moves through the world. When a GL group object is first created, its local coordinate
system is not rotated, translated, or scaledit has the same coordinate system as the rest of the 3D world, by default

The text Hello, Jitter! is displayed in the jit.window object's display area, but it starts at the center of the screen, so the
final part is cut off. Lets move the text to the left.

Set the number box labeled x in the Common 3D attributes section of the patch to the value 1.
The Number box sends a floating-point value to the pak object, which sends the message position followed by three
numbers to the jit.gl.text3d object. As you change the value in the number box, you can see the text slide to the left until all
of it is visible on the screen.

Changing the position attribute

We have just changed the position attribute of the jit.gl.text3d object. The position message can be followed by three
number arguments that set the position of the object in three dimensions. If fewer than three numbers follow the position
message, the axes are filled in the order [x, y, z], and the position of the object on the unspecified axes is set to 0. For
example, sending the message position 5. will set the position of a GL group object to the location [5, 0, 0].

The operation of changing an objects position is called translation.

Now, lets rotate the text.

Set the number boxes labeled x, y and z directly above the pakrotation object in the Common 3D attributes section of the
patch to the value 1. This sets the axis of rotation.

Drag the number box labeled angle to the value 320. You will see the text rotate around the axis into the position shown in
this screenshot.

The 3D text after translation and rotation

Sending the message rotate followed by from one to four numbers sets the rotation attribute of an GL group object. The first
number is an amount of rotation in degrees, counterclockwise around the objects axis of rotation. The other three numbers
specify this axis of rotation as an [x, y, z] vector. As with the position attribute, some values following the rotation attribute
can be dropped and default values will be understood. If the rotation message is followed by only one number, that number
is understood to mean the angle in degrees, and the axis of rotation is [0, 0, 1]. This rotates the object around the z axis, or in
other words, in the x-y plane of the screen. If two or more numbers accompany the rotation message, the first one always
specifies the rotation angle, and following ones specify the vector of rotation in the order in which they appear.

Set the number box labeled x directly above the pakscale object to 0.5. This scales the 3D text by half along its local x
axis.
The 3D text after translation, rotation and scaling

Note that the red axis scales along with the object. The dots along the line are now twice as close together as they were
before the scale operation. The axes are always drawn in the GL groups local coordinate system, which in this case has been
translated, rotated, and scaled with respect to the world coordinate system in the jit.gl.render object.
It's important to consider the order of operations when performing geometry transforms. You can set the rotate, position
and scale attributes of an object independently in any order you wish. But each time it is drawn, the object is transformed in
the following order:

1. Scaling 2. Rotation 3. Translation


Keeping this order is essential so that the attributes behave predictably. If rotation occurred before scaling, for example, a
scale 0.5 message would scale the object not just in its x coordinate, but in some combination of x, y and z depending on
the rotation of the object.

The following example shows the difference that performing operations in different orders makes.
The order of operations makes all the difference

Summary
Creating a draw context is the first step to using OpenGL graphics in Jitter. A draw context consists of a named destination,
such as a window, and a jit.gl.render object drawing to that destination.
A variety of Jitter objects exist which draw OpenGL graphics in cooperation with jit.gl.render; their names all start with
jit.gl. The jit.gl.text3d object is one example. All the Jitter OpenGL objects share a common set of attributes for moving
them in 3D space. This group of objects is referred to as the GL group.

See Also
Name Description
jit.gl.model Read and draw various 3D model formats
jit.gl.plato Generate platonic solids
jit.gl.render Render Jitter OpenGL objects
jit.gl.text3d Render vector text
jit.window Display data in a window
qmetro Queue-based metronome
Rendering Destinations
Tutorial 31: Rendering Destinations
In the previous tutorial, we saw how to draw OpenGL graphics into a jit.window using the jit.gl.render object. Now we will
look at the other kinds of destinations into which a jit.gl.render object can draw, what to use them for, and how to switch
between destinations.
Open the tutorial and look at the left side of the patch.

In the upper left of the patch is a jit.gl.render object with an argument of inky, along with other objects.
Click on the toggle in the upper left of the patch labeled Start Rendering.
You should see a red ball appear in the jit.window object. The jit.gl.gridshape object is drawing the ball. Its first argument,
inky, specifies the drawing context currently being drawn by the jit.gl.render object to the jit.window. The other arguments
set the color and scale attributes of the ball.

Draw a red ball in the window named inky

Drawing and Swapping Buffers


Clicking the toggle starts the qmetro object, which sends bang messages to the object t b b erase. This object first sends
an erase message followed by a bang message to the jit.gl.render object, and then a bang message that is used elsewhere
in the patch.

When the jit.gl.render object receives the bang message, it draws all of the GL group objects which share its destination,
then copies its offscreen buffer, if any, to the screen. An offscreen buffer is an area of memory not visible on the screen, the
same size as the drawing destination. By default, all drawing contexts have an offscreen buffer. Drawing is done into the
buffer, which must then be copied to the screen in order to be seen.

The offscreen buffer makes flicker-free drawing and animation possible, as we see here. Even though the buffer is being
erased before the red ball is drawn each time, we never see the buffer in its erased state. To see what drawing looks like
without the offscreen buffer, click on the message box doublebuffer 0 in the upper right of the patch . You will probably
see the image start to flicker. This happens because the erase message now causes the window itself to be erased, not the
offscreen buffer. The window remains blank for a short but indeterminate period of time before the red ball is drawn, so you
can see the area under the ball flickering between red and the dark gray of the erased window. Click the message box
doublebuffer 1 to remake the offscreen buffer and stop the flickering.

Setting Fullscreen Mode


The pfullscreen subpatch contains a key object, a select object, a toggle, a message box and an outlet object that sends
the results of the subpatch to the jit.window object. This is standard Max stuff, so we wont go over it in too much detail
the result is that the escape key toggles between sending the messages fullscreen 0 and fullscreen 1 to the jit.window
object. (See the "Full Screen Display" section of Tutorial 14.)
Press the 'esc' key to change the jit.window object to fullscreen mode and back.

The escape key seems to be a common way to toggle fullscreen mode, so weve used this setup in many of the example
patches. Its important to note, however, that this is just a conventiontheres nothing built into Jitter that forces you
to use one key or another for this purpose.

You can use the fsmenubar message in conjunction with the fullscreen message to hide the menubar in addition to
covering the screen.
Setting a jit.pwindow Destination
The jit.gl.render object can draw to three different kinds of destinations. The right side of the tutorial patch contains an
object example of each destination: a jit.window, a jit.pwindow, and a jit.matrix. Right now we are rendering to the
jit.window object. To change the destination to the jit.pwindow object, we need to first name the jit.pwindow object and
then set the destinations of the jit.gl.render object and the jit.gl.gridshape object.
Click on the message box name blinky above the topmost of the jit.pwindow objects.

This names the jit.pwindow object, which allows it to be used as a rendering destination. To switch the drawing to this
destination, we need to send messages to both the jit.gl.render object and the jit.gl.gridshape object, telling them about
the new destination.
Click on the message box blinky in the Switch Destinations section of the patch.
The symbol drawto is prepended to the message blinky, and the result is sent to the sdest object. Two objects receive this
message jit.gl.gridshape and tl b erase. The trigger object sends a sequence of messages to the jit.gl.render object,
which tell it to: 1. Erase its current destinations draw buffer 2. Swap that buffer to the screen, visibly clearing the old
destination, and 3. Switch future drawing to the new destination. The result is that the red ball is displayed on the
jit.pwindow object at the right of the patch.

Viewing our rendered output in a jit.pwindow object

Setting a jit.matrix Destination


In addition to drawing to jit.window objects and jit.pwindow objects, we can draw to jit.matrix objects. We introduced
offscreen buffers in the discussion of jit.window destinations, above. When a 2D jit.matrix object is a rendering destination,
the jit.matrix data is used as the offscreen buffer. This puts an image of an OpenGL scene into the same format as video
data, so that any of Jitters video-processing effects can be applied to the image.

The jit.matrix object must meet a few criteria in order for OpenGL graphics to be drawn into it:
It has to have four planes of char data.

It has to have two dimensions.

It has to be bigger than eight pixels in both width and height.

We have such a matrix in the bottom right corner of the tutorial patch. It is 160 pixels wide by 90 pixels highthe same
dimensions as the jit.pwindow object below it.
Click on the message box clyde in the Switch Destinations section of the patch to draw into the jit.matrix object.

You should see a cyan ball on a light gray background. This is because the red ball image generated by OpenGL is processed
through the jit.op object, which subtracts each color component from 255, inverting the image.
Rasterizing the output into a jit.matrix

Theres one more important detail about drawing to jit.matrix objects. Note that underneath the qmetro object theres a
trigger object t b b erase. The leftmost (and therefore last) bang message from this object is sent to the jit.matrix object
into which we are drawing. This is necessary to see the image in the jit.pwindow. When the jit.gl.render object receives a
bang message, it finishes constructing the drawing in the offscreen buffer belonging to the jit.matrix object. But to send the
resultant matrix out for viewing or further processing, its necessary to send a bang message to the jit.matrix object.

Hardware vs. Software Rendering: One of the great advantages about using OpenGL for rendering graphics is that most
of the work can be done by the graphics accelerator hardware in your computer, freeing the CPU up for other work
such as generating audio. When drawing into jit.window objects or jit.pwindow objects, the hardware renderer can be
used. Unfortunately, due to limitations of the current system software (Mac OS 9) the hardware renderer cannot draw
directly into jit.matrix objects. This is not a limitation inherent in OpenGL, and may change in the future. Now,
however, this means that drawing directly into Jitter matrices is significantly slower than drawing to jit.window or
jit.pwindow objects, especially for complex scenes or those involving textures.

Multiple Renderers and Drawing Order


To move an OpenGL scene to a different destination, the jit.gl.render object as well as any GL group objects involved in
drawing the scene must receive the drawto message. Why not just send a message to the renderer, telling it to move the
entire scene? The reason is that each GL group object can have an independent destination, as well as each renderer. Objects
in the GL group can be moved between multiple renderers. To see an example of why this might be useful, please look at the
right-hand portion of the patch for this tutorial.

At the right are three jit.pwindow objects named A, B and C. The message box objects above them are not strictly
necessary, because once a jit.pwindow object has been named, its name is stored with it in the patch. But they are useful
here as labels and as a reminder of what messages to send to name the objects.

There are also three jit.gl.render objects in the patch. Each of them is pointed at a different destination.
Click the togglelabeledStart Rendering.

This repeatedly sends the erase message followed by a bang message to each of the three renderers. You should see a yellow
circle within a blue circle in the topmost drawing destination. This simple OpenGL scene is created by the two
jit.gl.gridshape objects in the bottom left of the patch. We can move each of these objects to any of the three drawing
destinations present.

Rendering to jit.pwindow A

Click the topmost message boxreadingBin theSwitch Destinations section of the tutorial patch. This changes the
destination of the blue circle to the draw context named "B"it now appears on the center jit.pwindow.
Click the lower message boxreadingBin theSwitch Destinationssection of the tutorial patch. This changes the
destination of the yellow circle to the draw context named "B". The two objects are reunited.
Each time a jit.gl.render object receives a bang message, it draws all of the GL group objects that have been added to its
context. It draws the objects in the order in which they were added to the context. In this case, the yellow circle was added to
the draw context named "B" after the blue circle, so it appears on top. To change this order, we can send the message drawto
B to the jit.gl.gridshape object drawing the blue circle again. This will remove it from its present place in the list of objects
for the context named B, and add it again at the end of the list.

Click the upper message boxreadingBin theSwitch Destinationssection of the tutorial patch again. The blue circle
should now obscure the yellow circle.

The blue circle obscures the yellow one

Summary
We have introduced a flexible system for creating multiple OpenGL renderers and drawing destinations, and for moving
objects in the GL group between them using drawto messages.

Three Jitter objects can function as drawing destinations: jit.window, jit.pwindow, and jit.matrix. Each kind of destination
has different uses. A jit.window object can be moved to different monitors and quickly enlarged to cover the screen. A
jit.pwindow object keeps its location in the patch. A jit.matrix object may be used as an offscreen buffer for rendering. The
output of the jit.matrix object is a rasterized image of the 3D scene, to which further video processing may be applied.

See Also
Name Description
jit.gl.gridshape Generate simple geometric shapes as a grid
jit.gl.render Render Jitter OpenGL objects
jit.matrix The Jitter Matrix!
jit.pwindow Show data in a patcher
jit.window Display data in a window
qmetro Queue-based metronome
Camera View
Tutorial 32: Camera View
This tutorial shows you how to set up the camera view and how to position and rotate GL objects using jit.gl.handle. It will
cover the group of components which together make up the camera view: the camera's position, the point at which the
camera is looking, the "up" vector, the type of projection, the lens angle, and the clipping planes.
Open the tutorial.

In the lower left of the patch, there is a jit.window object named mister. This window will be the destination for our
OpenGL drawing. You will notice that the jit.window object has an attribute argument @depthbuffer 1 to specify the
creation of a depth buffer. A depth buffer allows the OpenGL renderer to determine which drawing command is visible at a
given pixel based on the proximity of the geometry to the camera. Without depth buffering, OpenGL uses what is often
referred to as the "Painter's Algorithm"--i.e. the visible results of drawing commands correspond to sequence in which they
are performed.

Click on the toggle object labeled Start Rendering.


We now see large gray circle and some yellow lines. These are being drawn by two instances of the jit.gl.gridshape object.
The jit.gl.gridshape object can draw a variety of 3D shapes, including spheres, tori, cylinders, cubes, planes, and circles. The
grey circle we see drawn in the window is actually a sphere and is being drawn by section of the patch labeled Grey Shape.
The yellow lines are actually a plane and are being drawn by the section of the patch labeled Yellow Plane. The yellow plane
is being rendered with poly_mode 1 1, which means that the shape is being drawn with outlined polygons rather than filled
polygons for both the front and back faces of the plane. If you switch off the toggle object connected to the message box
poly_mode $1 $1, you can see the plane rendered with filled polygons.

The mister drawing context

In the Grey Shape section of the patch, click on the message box scale 0.3 0.3 0.3 and then click on the message box
containing shape torus. You should now see what looks like a grey doughnut.

Click on the toggle object connected to the message box lighting_enable $1 and then click on the toggle object
connected to the message box smooth_shading $1. We are now staring at a lit, smoothly shaded, 3D gray torus.

By default, Jitter's GL objects have lighting and smooth shading disabled, so it is necessary to turn these on. Lighting
will be covered in detail in Tutorial 36.
Rendered shapes with smooth shading and lighting enabled

In the Camera View section of the patch, click on the toggle object labeledjit.gl.render axes.
You should see a red line from the center of the window to the right of the window, a green line from the center of the
window to the top of the window. These are the x and y axes, respectively. They help us to determine the origin of our scene.
Since the default camera position is at [0.,0.,2.], and the default lookat position is [0.,0.,0.], the camera is looking directly at
the origin of our scene along the z axis. Hence, we do not see the blue line which represents the z axis along which the
camera is looking.

View the axes

Under the camera position label, set the x value to be 1. Now the camera is at the position [1.,0.,2.], it is still looking at the
position [0.,0.,0.], and the blue line of the z axis has become visible.
The axes with a different viewing position

Now let's set the camera position x value to 6., y value to -6., and z value to 6. so that the camera position is [6,6,6].
You can see that the yellow plane and the axes are, in fact, finite.

Viewing the edge of the plane

So far, the y axis has always been pointing upwards with respect to the camera view. This is because the default "up" vector
is [0.,1.,0.]i.e. the unit y vector.

Under the up vector label, let's set the y value to 0. and the z value to 1. We see that the view has rotated, and the blue line
of the z axis is now pointing upwards.
Using a different up vector

You may have noticed, as we've moved the camera further away from the origin, that the torus, plane, and axes have become
smaller. This is because the default viewing mode uses a perspective projection, which is similar to the way we see things in
the 3-dimensional world we inhabit. If you are familiar with camera lenses, you may also know that depending upon the
angle of the lens, objects will be smaller as the lens angle increases to accommodate a larger field of view. Similarly, we can
change the lens angle of our perspective transformation to increase the field of view, and in doing so the objects will become
yet smaller.

The default lens angle is 45 degrees, so let's change it to something like 60 degrees by changing the number box connected
to the message box lens_angle $1.

Using a 60-degree lens angle

Another type of projection supported by OpenGL is the orthographic projection. This type of projection does not diminish
the size of objects based on camera position. The orthographic projection is common to 3D CAD software used for tasks such
as mechanical engineering. Many early video games like Q-Bert also used an orthographic projection. You can switch
between the perspective projection and the orthographic projection by clicking on the toggle box labeled orthographic
projection. The message ortho 1 will turn on orthographic projection. If you try moving the camera with orthographic
projection turned on, you should not see the objects become any smaller. However, changing the lens angle will still change
the field of view, and the size of objects relative to the view.
Viewing our scene using orthographic projection

Click on the toggle again to turn off the orthographic projection with an ortho 0 message.
Let's examine the clipping planes that determine the extent along the camera's view that will be rendered. OpenGL has a
near clipping plane and a far clipping plane, and only geometry which lies in between these two planes will be rendered.
These clipping planes are specified in units of distance from the camera along the viewing vector using the clip_near and
clip_far messages. By default, the near clipping plane is set to 0.1 and the far clipping plane is set to 100.

Try increasing the near clipping plane to 10 and decreasing the far clipping plane to 12. You should see the near and far
edges of the yellow plane that fall outside the clipping planes disappear.

Using a more constrained clipping plane

Set the near clipping plane back to the default of 0.1 and the far clipping plane back to the default of 100.

So far, the camera has always been looking at the origin [0.,0.,0.]. If we change the lookat position's x value to 3., the
camera is now looking at [3.,0.,0.].

Let's move the torus to the position [3.,0.,0.], by clicking on the message box containing position 3. 0. 0. in the section
of the patch labeled UI Rotation and Position Control. The torus is now again located at the center point of the view,
[3.,0.,0.].
Changing the viewing position and the position of the shape

Not only did this send the position 3. 0. 0. message to the torus, but also to the jit.gl.handle object. The jit.gl.handle object
is a GL group object that uses mouse information to move and rotate objects in the 3D scene. Like the jit.gl.gridshape
object, the jit.gl.handle object requires a named draw context into which to draw. Unlike the jit.gl.gridshape object, it's
also a user interface object that translates mouse activity in the draw context's destination to Max messages.

In this patch, messages from the jit.gl.handle object are sent to the jit.gl.gridshape object. They are also sent to the
routerotate position object and formatted so you can see exactly what is being sent. These messages are the only
communication from the jit.gl.handle objectthere is nothing going on "behind the scenes."
If you click on the torus and drag the mouse, you will see the torus being rotated by the jit.gl.handle object as though it were
a virtual trackball. If you hold down the command key while dragging, you can move the torus left, right, up, and down. If
you hold the option key as you drag, you can move the torus towards you or away from you. Using the shift key as you
perform any of the above mouse actions will constrain the action to a single axis.

Try manipulating the orientation of the torus by clicking on it in the jit.window object. Get a feel for how the jit.gl.handle
object translates the 2-dimensional mouse information into 3-dimensional rotation information.

Using the jit.gl.handle object to manipulate the objects position

As with the displayable axes of the jit.gl.render object, the jit.gl.handle object shows colored lines that correspond to
the x (red), y (green), and z (blue) planes of the object being rotated. The lines appear as circles around the relevant
object being "handled." The mouse controls the axes whose circles are nearest to the front of your current field of view.
By manipulating the image so that those circles move to the back of the object, you can control a different pair of axes
with the next mouse click. The modifier keys let you reposition the object by relocating it on the three axes. The
jit.gl.handle object outputs the relevant messages to set the rotate and position attributes of the GL group object
attached to it. Note that if you are displaying a GL context in a jit.pwindow, the Help in Locked Patchers option of
Max (which you can change under the Options menu) needs to be disabled in order for zooming to work using
jit.gl.handle. Otherwise, the option key will cause the help patch for jit.pwindow to appear(!).

Summary
We have examined the several components which make up an OpenGL scene's camera view, and the necessary attributes of
the jit.gl.render object which control them. The camera attribute specifies the camera position; up specifies the upwards
vector; lookat specifies the position at which the camera is looking; ortho specifies whether to use an orthographic or
perspective projection; and near_clip and far_clip specify the clipping planes. Lighting and smooth shading attributes can
be enabled by setting the lighting_enable and smooth_shading attributes of the GL group object handling the geometry (in
this case the jit.gl.gridshape object).
The jit.gl.handle object lets us rotate and reposition OpenGL objects using the mouse and the modifier keys on the
keyboard. The jit.gl.handle object takes the name of a valid draw context to attach itself to, and sends messages to any
connected object that is also using that context, setting the rotation and position attributes of that object.

See Also
Name Description
jit.gl.gridshape Generate simple geometric shapes as a grid
jit.gl.handle Use mouse movement to control position/rotation
jit.gl.render Render Jitter OpenGL objects
jit.window Display data in a window
Polygon Modes, Colors and Blending
Tutorial 33: Polygon Modes, Colors and Blending
In the previous tutorial, you saw how to position the camera and objects in the GL group to construct an OpenGL scene in
Jitter. After understanding this tutorial, youll be able to hide selected polygons of an OpenGL object based on their spatial
orientations, draw selected polygons in filled and wireframe modes, and add the results to the draw buffer using antialiasing
and blending.

Open the tutorial patch 33jPolyColorBlend in the Jitter Tutorial folder Click on the toggle box labeled Start Rendering.
You should see a gray sphere in the jit.pwindow in the tutorial patch. It is drawn by a jit.gl.gridshape object, connected to a
jit.gl.handle object that allows you to control its rotation. The jit.gl.handle object's auto_rotate attribute is on, so once you
rotate it the sphere will continue to rotate along the axis you set. If you like, give it a spin.

The gray sphere.

Wireframe Mode and Culling Faces


Just below the label OpenGL Objects to Render in the example patch is an object pak poly_mode 1 1. This object
generates messages that set the polygon mode attribute of the jit.gl.gridshape object.
Click both toggle objects on above the pak poly_mode object. You should see the gray sphere in wireframe mode.

The sphere in wireframe mode.

Turning wireframe mode on allows you to see clearly that the jit.gl.gridshape object approximates a sphere using polygons -
- in this case, quadrilaterals. Every polygon drawn in OpenGL has a front side, defined as the side from which its vertices
appear to wrap in a clockwise direction. Each polygon in a scene can, therefore, be categorized as either front-facing or back-
facing, depending on whether its front side is pointed towards or away from the camera.

OpenGL can automatically hide either front-facing or back-facing polygons, which can serve to speed up drawing greatly or
highlight certain aspects of data being visualized. In Jitter, you can control polygon visibility on an object-by-object basis
using the cull_face attribute.

Set the number box above the prependcull_face object to 1.


The front-facing polygons of the sphere.

The cull_face attribute of a GL group object can be set to 0,1 or 2. A setting of 0 shows all polygons in the object. A setting
of 1 hides the back-facing polygons. A setting of 2 hides the front-facing polygons. With the current setting of 1, the
wireframe sphere appears solid, because the hidden lines -- polygon edges that would not be visible if the sphere were made
of a solid material -- are not drawn. The rotation (did you give it a spin?) convincingly depicts that of a real-world solid
object.

Set the number box above the prepend cull_face object to 2.

The back-facing polygons of the sphere.

Now the front-facing polygons are hidden. Its as if you are looking through the sphere and seeing only the inside part that
faces towards you. You can see from this picture that the perspective is somewhat strange, but watching the rotation in the
patch makes it really obvious that the scene is not drawn normally.

In general, setting cull_face 1 will do a good job of removing the polygons that should be hidden for solid, convex objects
such as the sphere. But for objects that arent solid, a combination of the front-facing and back-facing polygons may be in
view.

Set the number box above the prependcull_face object to 0 to show all the polygons. Set the left box to 0 (off). Set the
umenu above the prepend shape object to opencylinder.

Open cylinder, with solid front-facing polygons and wireframe back-facing polygons.

Using this new shape, we can see the distinction between front- and back-facing polygons. The message poly_mode a b,
given two integers a and b, sets the front-facing polygons to wireframe mode if a equals 1, and the back-facing ones to
wireframe if b equals 1.
RGBA Colors
The colors of objects in the GL group are specified using the message color R G B A, where R is the red component of the
color, B is blue, G is green, and A is the alpha or opacity component. All values range from 0 to 1.

Set the number box objects above the pakcolor object to the values 1., 0., 0., 0.5. This specifies pure red at 50%
opacity.

You will see the color of the cylinder turn red, but the opacity is not visible. This is because blending, the mixing of pixels
with those previously in the draw buffer, is turned off by default.

Click the toggle box above the blend_enable $1 message box to turn blending on for the jit.gl.gridshape object. You
should see something like this:

The red cylinder with blending enabled.

ARGB vs. RGBA If youve been using Jitters video-manipulation objects, you know that colors in those objects are
stored in planes and specified in arguments n the order A, R, G, B. In the GL group of objects, the order is RGBA, with
alpha last, as were seeing here. This may seem odd, so you are due bit of explanation. Jitter objects are tied as closely
to native formats as possible in both the OpenGL and video domains, to allow the fastest possible processing. OpenGL
stores colors of objects and vertices in RGBA format, and QuickTime stores its images in ARGB format. So the Jitter
objects reflect this. If you want to combine OpenGL and video matrix processing in your patch, the pack, unpack,
jit.pack and jit.unpack objects provide an easy way to convert between the two systems. You can also convert a matrix
of char values from ARGB to RGBA by sending the matrix through a jit.matrix object with the planemap attribute set
to 1 2 3 0 (effectively shifting all the planes by one). Tutorial 6 shows more examples of using the planemap attribute
of the jit.matrix object.

Erase Color and Trails


Right now, each time the jit.gl.render object receives the erase message, the draw buffer is filled with the dark gray that is
the default erase color. You can set a different erase color using the RGBA number boxes above the renderer object.

Set the number boxes above the jit.gl.render object to the values 0, 0, 0.5 and 0.1.
The background changes to a dark blue (Red = 0, Green = 0, Blue = 0.5). If the cylinder is spinning, you will also see trails in
the image. This is because the background is being erased with an opacity of 0.1. When the dark blue pixels are drawn on top
of the existing pixels in the draw buffer, they are overlaid such that the result is one-tenth dark blue and nine-tenths
whatever color was at each pixel previously. As a result, previous frames linger for some time before being fully erased. Note
that while the blend_enable attribute must be set in order to see draw colors with partial opacity, it is not necessary for
erasing with partial opacity.
The spinning cylinder, leaving trails.

Blend Modes
When the blend_enable attribute of an object in the GL group is on, each pixel is applied to the draw buffer using a blend
function. The blend function is the basic operation in image compositing. It controls the application of new pixels, the
source, over existing pixels, the destination. The function has two parts: a source blending factor and a destination blending
factor. The source blending factor specifies how the sources contribution to the finished image should be computed. The
destination blending factor specifies the destinations contribution.

Jitter recognizes eleven possible modes for blending factors. Some can be applied only to the source, some only to the
destination, and some to both. Each mode specifies a different set of multiplier values for red, green, blue and alpha. The
message blend_mode [src_factor] [dest_factor]allows you to specify both factors for any of the drawing objects in
the GL group.

The Blend Modes The source and destination blend factors are RGBA quadruplets which are multiplied
componentwise by the RGBA values of the source and destination pixels, respectively. The corresponding components
of the source and destination are added and then clamped to the range [0, 1] to produce the output pixel.

This table shows how the blend factors are calculated. The Mode column lists the number passed in the Jitter
message blend_mode [src_factor] [dest_factor]. The OpenGL name column lists the name of the mode. The
Relevant to column lists whether the mode can apply to the source factor, the destination factor, or both. Finally, the
Blend Factor Equation column specifies the actual formula that is used to calculate the pixel. The subscripts s and d
refer to source and destination components, respectively. For example, R s refers to the red component of the source
pixel.

Mode OpenGL name Relevant to Blend Factor Equation

0 GL_ZERO both (0, 0, 0, 0)

1 GL_ONE both (1, 1, 1, 1)

2 GL_DST_COLOR source (Rd, G d, B d, Ad)

3 GL_SRC_COLOR destination (Rs, G s, B s, As)

4 GL_ONE_MINUS_DST_COLOR source (1, 1, 1, 1)-(Rd, G d, B d, Ad)

5 GL_ONE_MINUS_SRC_COLOR destination (1, 1, 1, 1)-(Rs, G s, B s, As)

6 GL_SRC_ALPHA both (A s, As, As, As)


7 GL_ONE_MINUS_ SRC_ALPHA both (1, 1, 1, 1)- (As, As, As, As)

8 GL_DST_ALPHA both (A d, Ad, Ad, Ad)

9 GL_ONE_MINUS_ DST_ALPHA both (1, 1, 1, 1)-(A d, Ad, Ad, Ad)

10 GL_SRC_ALPHA_SATURATE source (f, f, f, 1); f = min(A s, 1-Ad)

The default source and destination blend modes for all objects in the GL group are 6 and 7, respectively. These correspond
to the GL blend factors GL_SRC_ALPHA and GL_ONE_MINUS_SRC_ALPHA. This is a very commonly used blending
operation, and you may never need another one. It allows you to crossfade intuitively between the source and destination by
changing the sources alpha value.

Other values are useful for simulating various real-world lighting situations, as well as special effects that have no physical
counterpart.

Set the RGBA number boxes above the jit.gl.render object, which control the erase_color attribute, to the values 1.0,
1.0, 0.5 and 1.0. This will set the background color to yellow and remove the trails, making the blend effect more visible.

Set the left and right number boxes above the object pak blend_mode to 0 and 7 respectively. This specifies a source
blend factor of GL_ZERO and a destination blend factor of GL_SRC_ALPHA.

The cylinder with a setting of blend_mode 0 7 .

Lets examine how this blend_mode produces the image we see here. The source factor is GL_ZERO. This means that all the
components of the source pixel are multiplied by zero -- the source pixel has no effect. You can verify this by trying different
RGB values for the cylinder. They all produce the same colors.

The destination factor is GL_SRC_ALPHA. Looking in the table above, we can find the blend factor equation this
corresponds to: (A s, As, As, As). Each component of the destination pixel is multiplied by the sources alpha, in this case
0.5, before being added to the source pixel times the source factor, which in this case is 0. So, each time a pixel is drawn, it
has its brightness reduced by one half.

Antialiasing
When OpenGL draws polygons and lines, it approximates their ideal geometric shapes by filling in pixels on a raster grid.
This process is prone to difficulties that parallel those in reconstructing ideal waveforms with digital audio. Inevitably,
aliasing, spatial frequencies that are not included in the ideal image, will be introduced once it is reconstructed from
discrete pixels. This aliasing is visible as what are commonly known as jaggies, especially in near-horizontal or near-
vertical lines or edges.

OpenGL has some antialiasing techniques for reducing the jaggies. Weve made these available in Jitter through attributes of
the GL group of objects. Using these attributes, you can specify whether any given object in the GL group will use antialiasing
when it is drawn.

Turn on the toggle box above the message box antialiasing $1 to send the message antialias 1 to the jit.gl.gridshape
object.
Antialiasing off

Antialiasing on

The antialiased lines have a smoother appearance, and also a fatter one. They may also draw more slowly, so if youre
concerned about drawing speed, you have to decide whether the improved appearance is worth the extra time.

The behavior of antialiasing in OpenGL is implementation-dependent. This means that makers of OpenGL hardware and
drivers have some leeway in deciding what exactly happens when you request antialiasing. In the pictures above, for
example, note that while the jaggies on the lines are reduced, the polygon edges in the lower left appear just the same. When
you turn antialiasing on, Jitter requests that polygon edges be antialiased. But the particular OpenGL implementation that
generated these pictures (an ATI Rage 128 accelerator with version 5.9.8 drivers) does not offer any help in this regard. Your
implementation may differ.

Summary
We have defined front-facing and back-facing polygons, and seen how to draw them in both solid and wireframe modes
(using the poly_mode and cull_face attributes). The renderers erase_color attribute and its use to draw trails have been
introduced. We defined in detail what happens when a source pixel is applied to a draw buffer destination, taking opacity
and blend modes into account. And finally, the handy if somewhat unpredictable antialiasing feature of OpenGL was
introduced.

See Also
Name Description
jit.gl.gridshape Generate simple geometric shapes as a grid
jit.gl.handle Use mouse movement to control position/rotation
jit.gl.render Render Jitter OpenGL objects
jit.pack Make a multiplane matrix out of single plane matrices
jit.pwindow Show data in a patcher
jit.unpack Make multiple single plane matrices out of a multiplane matrix
pack Create a list
unpack Break a list into individual messages
Using Textures
Tutorial 34: Using Textures
This tutorial shows you how to create and apply textures to 3D geometry data generated by the GL group. It will cover the
creation of a named texture with jit.gl.render, assigning a named texture to a GL object, the use of colors in conjunction
with textures, the conversion of image/video data to a texture, and various ways to wrap the geometry with a texture.

Open the tutorial patch 34jUsingTextures in the Jitter Tutorial folder, and click on the toggle object labeled Start
Rendering.

You will see a white parallelogram, but it is actually a tetrahedron being drawn by the jit.gl.plato object. The jit.gl.plato
object is capable of rendering several platonic solids including tetrahedrons, hexahedrons (also known as cubes),
octahedrons, dodecahedrons, and icosahedrons. Since lighting is not turned on and there is no texture being applied to the
tetrahedron, it is difficult to tell that it is actually a 3D shape.

Use the mouse to rotate the tetrahedron with the jit.gl.handle object, as covered in Tutorial 32.
This should illustrate that it is actually a 3D shape, but by applying a texture to the jit.gl.plato object, this will become even
more apparent.

Rotating the platonic solid.

What is a Texture?
A texture is essentially an image that is overlaid upon geometry. Just like other images in Jitter, textures have an alpha, red,
green, and blue component. In order to make use use the alpha component, blending must be enabled. Blending is covered
in detail in Tutorial 33.

In Jitter, a texture has a name and belongs to the jit.gl.render object. Other objects that are attached to the drawing context
associated with a given jit.gl.render object may make use of any of the named textures owned by that jit.gl.render object.
For efficiency reasons, most OpenGL implementations require that the dimensions of texture data must be integer powers of
two16, 32, 64, and so on. While there are some implementations that permit arbitrarily sized textures, this is not
supported in the current version of Jitter. There is a minimum size of 1 by 1 and a maximum size dependent upon the
OpenGL implementation, usually 1024 by 1024.

Creating a Texture
Create a texture named grid by clicking the message box labeled texture grid 64 64 in the section of the patch labeled
Textures. This message is being sent to the jit.gl.render object.
The first argument to the texture message is the texture name, and the two following arguments specify the width and
height of the texture. This creates a 64 by 64 texture named grid, and fills it with the default pattern (a white and grey
checkerboard). You will not see any of the results yet, because the texture has not yet been applied to the geometry.

Apply the texture to the tetrahedron by clicking on the message box labeled texture grid in the section of the patch
labeled Platonic Solid. This sets the jit.gl.plato object's texture attribute, and when drawing, it will use the texture named
grid. You should now see a checkered tetrahedron.

Tetrahedron with a checkerboard texture applied to it.

The jit.gl.plato object uses a "gift-wrapping" strategy to apply the texture to the tetrahedron. In thejit.gl.plato help file, the
texture_maps subpatch illustrates exactly how the different platonic solids are wrapped.

How texture maps are applied to different platonic solids.

Important Note: You will notice that both the jit.gl.render and jit.gl.plato objects use the texture message in
different ways. The jit.gl.render object uses this message to create a texture, while the jit.gl.plato and other GL
objects use this message to apply a texture. The jit.gl.render object also has a message to apply one of its named
textures to raw geometry data passed as Jitter matrices. That message is usetexture. The jit.gl.render object's ability
to render raw geometry data passed as Jitter matrices will be covered in Tutorial 37.

Textures and Color


When applying a texture to geometry, OpenGL also takes into account color and lighting information, so the current color
and lighting values will be multiplied with the texture image when drawn. If the color is white and lighting is turned off, the
texture colors will be unaltered.

In the section of the patch labeled Platonic Solid, set the color of the tetrahedron to red by setting the number box labeled
red to 1, the number box labeled green to 0, and the number box labeled blue to 0.
Manipulating the color of the rendered object.

Set the color of the tetrahedron back to white (1. 1. 1.) for our next section.

Converting an Image or Video to a Texture


While illustrative, typically you will want to make use of textures other than the default grey and white checkerboard. This
can be accomplished by loading an image or a movie into the jit.qt.movie or jit.matrix objects and sending the message
texture [texture-name] jit_matrix [matrix-name] to the jit.gl.render object. If the texture specified by [texture-name]
already exists, the incoming matrix will be resampled to the current dimensions of the texture. If no texture with that name
exists, a new texture will be created. Its dimensions will be the nearest power of two greater than or equal to the dimensions
of the Jitter matrix.

Click the message box containing texture picture 128 128 in the section of the patch labeled Textures. This creates a
128 by 128 texture named picture, and like before, fills it with the default white and grey checkerboard pattern.

Click the message box containing read colorbars.pict, bang to load the colorbars.pict image into the jit.qt.movie object,
and send it on its way to the texture named picture.

You still won't see any of the results yet, because the jit.gl.plato object is still using the texture named grid.
Click the message box containing texture picture in the section of the patch labeled Platonic Solid.

Now you should see the colorbars image wrapped around the tetrahedron.

Using an image as a texture.

In many instances you will only need to use still images as textures, but Jitter also supports the use of moving video as
textures by repeatedly copying the output of the jit.qt.movie object into the named texture.
Click the message box containing read dishes.mov to load dishes.mov into the jit.qt.movie object.
Click on the toggle object connected to the metro object to start copying the video to the texture named picture.

Texture-mapping using a movie.

Interpolation and Texture size


By default, texture interpolation is turned on, so screen pixels which are between texture pixels will use an interpolated value
of its neighbors within the texture image. This has the effect of blurring or smoothing out the texture. To apply textures
without interpolation, the interpolation may be turned off using the jit.gl.render object's interp message. This message only
affects the jit.gl.render object's current texture, so prior to sending the interp message, you can send the message
usetexture [texture-name] to make the current texture the one specified by [texture-name] argument.

Click the toggle object connected to the message box containing usetexture picture, interp $1 to have thejit.gl.render
object use the texture named picture and then to turn interpolation on and off for the texture named picture.

Once a texture has been created, the texture size can be changed, by sending the message texture [texture-name] [width]
[height] where [width] and [height] specify the new dimensions.

Set the number box labeled Resize texture to 16. This will send the jit.gl.render object the message texture picture 16
16, resizing the texture picture to be a 16 by 16 image.

Using an uninterpolated texture

Textures may be deleted in order to free up memory by sending jit.gl.render the message deletetexture [texture-
name].

Mapping Modes
So far we have only addressed the explicit texture mapping that the jit.gl.plato object provides. OpenGL also provides a few
other implicit texture mappings for applying textures to geometry data. These are the object linear, eye linear, and sphere
map mapping modes.

The object linear mode applies the texture in a fixed manner relative to the object's coordinate system. As the object is
rotated and positioned in the 3D scene, the texture mapping remains the same. In contrast, the eye linear mode applies the
texture in a fixed manner relative to the eye's coordinate system. As the object is rotated and positioned in the 3D scene, the
application of the texture to the object will change. Lastly, the sphere map mapping mode will produce the effect commonly
called "environment mapping"; the object is rendered as though it is reflecting the surrounding environment, and assumes
that the texture contains a sphere mapped image of the surrounding environment. As the object is rotated and positioned in
the 3D scene, the application of the texture to the object will change.

These implicit mapping modes may be used by setting the GL group tex_map attribute. A tex_map value of 0 is the default
and will use the GL object's explicit texture coordinates. A tex_map value of <m>1</m> will use OpenGL's object linear
mode. A tex_map value of 2 will use OpenGL's sphere map mode. A tex_map value of 3 will use OpenGL's eye linear mode.

Try changing the number box connected to the message box containing tex_map $1. Position and rotate the tetrahedron
with your mouse, and see how the various modes affect the texture mapping.

Using different implicit mapping modes: object linear (left), sphere map (middle), eye linear (right).

OpenGL's object linear and eye linear mapping modes have additional parameters that affect the way in which they apply the
texture. These are set with the GL group tex_plane_s and tex_plane_t attributes. These attributes are each vectors in 4
dimensional homogenous coordinates. The scalar product of tex_plane_s and a given point in 4 dimensional homogenous
coordinates determines the horizontal position of the texture image to apply. The scalar product of tex_plane_t and a given
point in 4 dimensional homogenous coordinates determines the vertical position of the texture image to apply. By default,
tex_plane_s is equal to (1. 0. 0. 0.) and tex_plane_t is equal to (0. 1. 0. 0.).

A more detailed description of how the tex_plane_s and tex_plane_t attributes affect the texture mapping are out of the
scope of this tutorial, but that doesn't mean you can't play with it anyway to generate interesting effects. For the curious,
please consult the OpenGL Red Book or Blue Book.

Experiment with the number box objects under the texture plane s and texture plane t labels (tex_map should be set to 1
or 3 in order to have any effect).

Experimenting with additional parameters.

Summary
We have established how to create textures and various ways to apply them to the geometry created by the GL group. The
jit.gl.render object's texture message may be used to create, size, and copy image or video data to named textures. The GL
group texture attribute specifies which named texture to use, and the GL group tex_map attribute selects either the explicit
texture mapping mode or one of the three implicit OpenGL texture mapping modes: object linear, eye linear, or sphere map.

See Also
Name Description
jit.gl.handle Use mouse movement to control position/rotation
jit.gl.plato Generate platonic solids
jit.gl.render Render Jitter OpenGL objects
jit.matrix The Jitter Matrix!
jit.qt.movie Play or edit a QuickTime movie
Lighting and Fog
Tutorial 35: Lighting and Fog
Lightingthe illumination of objects in the real worldis a very complex subject. When we view objects, our eyes focus and
detect photons throughout a range of energies that we call visible light. Between their origin in the Sun, lightning, fireflies or
other light sources and our eyes, they can travel on a multitude of complex paths as they are reflected from or refracted
through different materials, or scattered by the atmosphere. Our computers wont be dealing with this level of complexity
anytime soon, so OpenGL simplifies it greatly.

The OpenGL Lighting Model


Lighting in OpenGL is based on a very rough model of what happens in the real world. Though very crude compared to the
subtlety of nature, it is a good compromise, given todays technology, between the desire for realism and the cost of
complexity.

We have already seen how colors in OpenGL are described as RGB (red, green and blue) values. The lighting model in
OpenGL extends this idea to allow the specification of light in terms of various independent components, each described as
RGB triples. Each component describes how light thats been scattered in a certain way is colored. The continuum of possible
real-world paths is simplified into four components, listed here from most directional to least directional.

The specular light component is light that comes from a certain direction, and which also reflects off of surfaces primarily in
a given direction. Shiny materials have a predominant specular component. A focused beam of light bouncing off of a mirror
would be a situation where the specular component dominates.

Diffuse light comes from one direction, but scatters equally in all directions as it bounces off of a surface. If the surface is
facing directly at the light source, the light radiation it receives from the source will be the greatest, and so the diffuse
component reflected from the surface will be brightest. If the surface is pointing in another direction, it will present a smaller
cross-section towards the light source, and so the diffuse component will be smaller.

Ambient light is direction-less. It is light that has been scattered so much that its source direction is indeterminate. So it
appears equally bright from all directions. A room with white walls would be an environment with a high ambient lighting
component, because so many photons bounce from wall to wall, scattering as they do so, before reaching your eye.

Finally, emissive lighting is another component that doesnt really fall anywhere on the directionality scale. It is light that
only reaches your eye if youre looking directly at the object. This is used for modeling objects that are light sources
themselves.

These components are used to describe materials and light sources. Materials made of specular, diffuse, ambient and
emissive components are applied to polygons to determine how they will be colored. Polygons with materials applied are lit
based on their positions and rotations relative to light sources and the camera, and the specular and diffuse properties of
light sources, as well as the ambient light component of the scene.

Getting Started
Open the tutorial patch 35LightingAndFog in the Jitter Tutorial folder. Click on the toggle (in the lower left, this time)
labeled Start Rendering.

Click the message box reading name lt, depthbuffer 1 above the jit.pwindow object. This creates a depth buffer so that
hidden-surface removal can be done.

You will see a flat gray torus and a small white circle in the jit.pwindow object. The jit.gl.gridshape object in the center of
the tutorial patch draws the torus. The other jit.gl.gridshape object in the patch, towards the right, draws the white circle.
The scene is all presented in flat shades because lighting is not yet enabled.
Click the toggle box objects above the top three message box objects reading lighting_enable $1, smooth_shading $1,
and auto_material $1 to set those attributes of the jit.gl.gridshape object drawing the torus to 1.
Lighting is off by default for each object, so you must enable it. The same goes for smooth shading. When you set these two
attributes, you will see the torus go through the now-familiar progression (assuming youve been doing these tutorials in
order) from flat shaded to solid faceted to solid and smooth. When you set the auto_material attribute to 1, you wont see
any change, because its default value is already 1.

Click the toggle objects above the message box labeled auto_material $1 again, to set the auto_material attribute of the
jit.gl.gridshape object to 0.
Now you should see a change in the lighting of the torus. Instead of the dull gray appearance it started with, you will see a
shiny gray appearance like this:

The lit torus with the auto_material attribute off.

The auto_material attribute is provided in Jitter so that you dont always need to specify all the components of a material
just to see an object lit. When the auto_material attribute of an object in the GL group is on and lighting is enabled for the
object, the diffuse and ambient material components for the object will be set to the objects color, and the specular and
emissive lighting components are disabled. This resulted in the flat gray torus we saw initially. In this tutorial, though, we
want to see what happens when all the lighting components are specified explicitly, so we have turned the auto_material
attribute off.

The image that results appears shinier, because the material applied to the torus now has a specular component.

Moving the Light


The jit.gl.gridshape object drawing the white circle has a jit.gl.handle object attached to it. As weve seen before this allows
you to move the circle by clicking and dragging over it with the command key held down. By dragging with the option key
held down, you can move the circle towards and away from the camera in the scene.

The x, y and z position values from the jit.gl.handle object are also routed to an unpack object, which sends them to
number box objects for viewing. A pak object adds the symbol light_position to the beginning and another value to the end
of the list. This message is sent to the jit.gl.render object to set the position of the light in the scene. Note that the light
itself is not visible, except in its effect on other objects. The white circle is a marker we can use to see the lights position.

Click and drag the white circle with the command key held down to move it to the lower left corner of the scene. Then drag
with the option key held down to move it away from the camera.

The light source moves with the white circle. If you move it to the right place, you can create an image like this.

The same scene with the light source moved.

The diffuse and specular components of the light are combined with the diffuse and specular components of the material at
each vertex, according to the position of the light and the angle at which the light reflects toward the camera position. When
you move the light, these relative positions change, so each vertex takes on a different color.
Normals: For lighting to take place, each vertex of a model must have a normal associated with it. The normal is a
vector that is defined to be perpendicular to the surface of the object at the vertex. This is the value used to determine
the contribution of the specular and diffuse lighting components to the image. Creating reasonable normals for a
complex object can be a time-consuming process.

Jitter attempts to prevent you from worrying about this as much as possible, in a couple of ways. First, most objects in
the GL group have normals associated with them. These are calculated by the object that does the drawing. The
jit.gl.gridshape object is one example. If its shape is set to a sphere, it generates a normal at each vertex pointing
outwards from the center of the sphere. Each shape has a different method of calculating normals, so that the surfaces
of the various shapes are smooth where curved, yet the edges of shapes like the cube remain distinct and unsmoothed.

Secondly, if you send geometries directly to the jit.gl.render object in matrices, the jit.gl.render object will
automatically create normals for you to the best of its ability. If you draw a connected grid geometry by sending a
matrix followed by the tri_grid or quad_grid primitives, the generated normals will be smoothed across the surface of
the grid. If you send a matrix using other primitives such as triangles, jit.gl.render will make no attempt to smooth the
vertices, but will generate a normal for each distinct polygon in the geometry.

If you want to make your own normals, you can turn automatic normal generation off with by setting the attribute
auto_normals of the jit.gl.render object to 0.

Tutorial37, "Geometry Under the Hood" describes how vertices, colors and normals can be passed in Jitter matrices to
the jit.gl.render object. For more information on how to specify normals for geometry within a matrix, please refer to
the Jitter OpenGL Appendix in this publication.

Specular Lighting
Lets change the specular components of the lighting to get a better feel for them.

Locate the swatch object above the prepend mat_specular object. Move the circle in the swatch to the far left, centered
vertically. This sends the mat_specular message to the jit.gl.gridshape object, followed by RGB color values that describe a
pure red color.

The swatch object sends it output as a list of three integers from 0 to 255. The vexpr object divides each integer in the list
by 255. to generate a floating-point value in the range 0.to 1. , which is the range Jitters OpenGL objects use to specify
colors.

Setting the specular material component to red.

The resulting torus with red highlights.


The highlights of the image now have a red color. The specular component of the light source, which is currently white, is
multiplied by the specular material component to produce the color of the highlights.

The red, green and blue values of the specular light source are multiplied by the red, green and blue values of the specular
material component, respectively. So if the light source component and the material component are of different colors, its
possible that the result will be zero, and no highlights will be generated. This more or less models the real-world behavior of
lights and materials: if you view a green object in a room with red light, the object will appear black.

Try moving the circle in the swatch object above the prepend light_specular object to a green color. The highlights will
disappear. Different colors with varying amounts of red will produce different brightnesses of red. When you are done, move
the circle to the top of the swatch object so that the highlights are red again.

The shininess attribute of objects in the GL group is an important part of the material definition. It specifies to what extent
light is diffused, or spread out, when it bounces off of the object. To model a mirror, you would use a very high shininess
value. Values of approximately 2 to 50 are useful for making realistic objects.

Set the number box above the prepend shininess object to 50.
This makes the contribution of the specular lighting components much smaller in area. Accordingly, you can see the specular
lighting in red quite distinctly from the diffuse lighting, which is still gray.

A very shiny torus.

Diffuse Lighting
Lets manipulate the colors some more to see the effect of the diffuse component.

Locate the swatch object above the prepend mat_diffuse object. Move the circle in the swatch approximately to the
location in the illustration below, to produce a deep blue diffuse material component.

Setting the diffuse material to blue.

The diffuse reflections from the torus are now blue, and the highlights are magenta. This is because the color components of
an objects material, after being multiplied with the lighting components depending on positions, are added together to
produce the final color for the object at each vertex.
Red highlights added to blue diffuse lighting.

Ambient Lighting
We have yet to change the ambient component of the objects material. Currently, this is set to its default of medium gray,
which is multiplied by the dark gray of the global ambient component to produce the dark gray areas of the torus in the
picture above. The global ambient component is multiplied by all ambient material components in a scene, and added to
each vertex of each object. You can set this with the light_global_ambient attribute of the jit.gl.render object.
Set the circle in the swatch object above the prepend mat_ambient to a green color to produce a green ambient material
component.

Green ambient illumination.

The ambient material component is multiplied by the global ambient illumination component to make the dark green areas
that have replaced the gray ones.

The moveable light in the scene has an ambient component associated with it, which is added to the global ambient
component. To change this, you can move the circle in the swatch object above the prepend light_ambient object. If you
change this to a bright color, the whole object takes on a washed out appearance as the intensity of the ambient component
gets higher than that of the diffuse component.

Thats Ugly!
A green torus with blue diffuse lighting and magenta highlights is probably not something you want to look at for very long.
If you havent already, now might be a good time to play with the color swatches and come up with a more harmonious
combination.

Note that control over saturation isnt provided in this patch for reasons of space. But its certainly possible to specify less
saturated colors for all the lighting and material components.

Directional vs. Positional Lighting


The moveable light in a scene can be either directional or positional. In the message light_position [x] [y] [z] [w] sent to
jit.gl.render, the value [w] decides whether directional or positional lighting is used. If [w] is zero, the light is a directional
one, which means that the values [x], [y] and [z] specify a direction vector from which the light is defined to come. If [w] is
nonzero, the light is a positional oneit illuminates objects based on its particular location in the scene. The position of the
light is specified by the homogeneous coordinates [x]/ [w], [y] /[w] and [z]/ [w].

Positional lights are good for simulating artificial light sources within the scene. Directional lights typically stand in for the
Sun, which is so far away that moving objects within the scene doesnt change the angle of the lighting perceptibly.

Turn on the toggle above the p mover subpatch to start the torus moving towards and away from the camera.
Notice how the lighting shifts across the surface of the torus as it moves, if the torus moves past the general vicinity of the
light. You may have to move the lights position to see this clearly.

To see the effects of directional lighting, change the last number box above the pak light_position 0. 0. 0. 1. object to 1,
than back to 0.

Now, notice that because directional lighting is on, the lighting no longer shifts when the object changes its position.

Fog
Like other aspects of lighting, the simulation of fog in OpenGL is primitive compared to the real-world phenomenon. Yet, it
offers a convenient way to a richer character to an image. OpenGL fog simply blends the color of the fog with the color at
each vertex after lighting calculations are complete, in an amount that increases with the objects distance from the camera.
So faraway objects disappear into the fog.

In Jitter, fog can be turned on or off for each object in the GL group by using the fog attribute. Some objects in a scene can
have fog applied to them while others dont.

Turn on the toggle above the fog $1 message box, which turns fog on for the jit.gl.gridshape object drawing the
torus.

Set the rightmost number box above the pak fog_params object to the value of 10, which will send all the fog
parameters listed in the same jit.gl.gridshape object.
You should see the torus receding into the fog as it gets farther from the camera, assuming the p mover subpatch is still
active.

Set the red number box above the pak fog_params object to 1. This specifies a fog color of 1., 0.2, 0.2.
Now, when the torus gets farther away, it doesnt disappear. Rather, it turns bright red. Fog makes faraway objects tend
toward the fog color, which may or may not be equal to the background color. Only if the fog color and the color of the
background are nearly equal will realistic fog effects be achieved.

Torus receding into the fog.

If you like, try manipulating the other parameters of the fog with the number box objects above the fog_params message.

Implementation Dependent Like antialiasing, which was introduced in Tutorial 33, the effects of fog parameters
may vary from system to system, depending on what OpenGL renderer is being used. The basic characteristics of fog
discussed above should be basically the same, but details such as how the density parameter affects the fog may vary.

Summary
We have described OpenGLs lighting model and its implementation in Jitter in some detail. We discussed the specular,
diffuse and ambient components of the GL lighting model, how they approximate different aspects of a real world scene, and
how they combine to make an image. The distinction between positional and directional lighting was introduced. Finally, we
saw how to add fog to a scene on an object-by-object basis.

See Also
Name Description
jit.gl.gridshape Generate simple geometric shapes as a grid
jit.gl.handle Use mouse movement to control position/rotation
jit.gl.render Render Jitter OpenGL objects
jit.pwindow Show data in a patcher
swatch Select and display RGB colors
vexpr Evaluate a math expression for a list
3D Models
Tutorial 36: 3D Models
In this tutorial, we will show how to load 3D models using the jit.gl.model object and render them in Jitter with lighting,
materials and texture mapping.

Review and Setup


Open the tutorial patch 36j3Dmodels in the folder Tutorial 36 in the Jitter Tutorial folder. Click on the toggle labeled
Start Rendering.

You will see a brown background in the jit.pwindow object. The brown color comes from the erase_color attribute of the
jit.gl.render object.

Click on the message box reading name ml, depthbuffer 1 above the jit.pwindow object.

The name attribute allows the jit.pwindow object to be used as a drawing destination, although this was already done and
saved with the tutorial patch in this case. The message depthbuffer 1 causes a depth buffer to be attached to the
destination, so that automatic hidden-surface removal can be done.

Click on the message box reading texture grid 64 64 above the jit.pwindow object.
As we saw in the tutorial introducing textures, this message send to the jit.gl.render object causes it to build a texture 64
pixels in both width and height, filled in with a default checkerboard pattern. The texture can be used by any objects in the
GL group which are drawing to its context. We are now ready to load some models and render them.

Reading a Model File


The jit.gl.model object reads descriptions of 3D objects as collections of polygons. These descriptions are stored in the .obj
file format. The model files must have a .obj extension in order to load. This format is widely used, and has the advantage of
being readable and modifiable in ordinary text editors.

Click on the toggle object above theverbose $1message box in the upper left of the Draw a Model section of the
patch.

This sends the message verbose 1to thejit.gl.model object, enabling verbose mode. When this mode is on, you will see
information about the model file you are loading printed in the Max window. Its not good to leave verbose mode on while
you are rendering real-time graphics, but the messages can be very helpful while you are setting up and debugging a patch.

Click on the message box containing the message read mushrooms.obj. This object can be found above the jit.gl.model
object.

The file mushrooms.obj should have been installed into Maxs search path when Jitter was installed. If for some reason this
file has been moved, you will see the message error: jit.gl.model: cant find mushrooms.obj in the Max window. If
the file is found correctly, you will see the following in the Max window:

reading mushrooms.obj......
done.
jit.gl.model: rebuilding
groups: 11
materials: 0
triangles: 10560
vertices: 6199
texture coords: 5589
normals: 6046
636408 bytes used

When the file you specify after the read message is found and determined to be a valid model file, the message reading
[file].obj is printed. Then the dots are printed out every so often while the file loads. Reading large models from text files
can take quite a while, so its nice to see the dots appearing in order to know that something hasnt gone wrong.

When the model is done loading, jit.gl.model: rebuilding is printed. Some operations besides reading a new model cause
the models representation to be rebuilt internally -- all of them print this message so you know whats going on.
The groups: 11 message tells you that there are eleven polygon groups in the model. A model need not consist of one like
an apple or mushroom, it can be a group of things or an entire scene. Assigning different objects in the model to different
polygon groups allows them to be manipulated independently in your patch.

The materials:0 message tells you how many material definitions there are in the model file. A material definition can
specify the ambient, diffuse and specular components of an objects surface color, as we covered in Tutorial 35. A model file
can have multiple material definitions which can be applied to one or more polygon groups in the model. This model,
however, has none.

We can also see that this model consists of 10,560 triangles joining 6,199 vertices, 5,589 texture coordinates and 6,046
normals. There are fewer texture coordinates and normals than vertices by a bit, because these numbers are referenced in a
big index when the model is read, and can be reused when the triangles are constructed.

Finally, we see that approximately 636 kilobytes of memory have been used by Jitter to store the model internally. Though
memory is getting more plentiful all the time, this amount is not insignificant. Memory usage is definitely something to keep
an eye on when debugging larger patches.

.obj Model File Compatibility There are many extensions to the basic .obj file format in existence. Some of these
are NURBS and parametric surfaces. Right now, only vertices, polygons, groups, materials and texture coordinates are
supported.

Model Attributes
If you followed the directions, youve been reading all this dry text about messages in the Max window, while eleven
mushrooms hover tantalizingly in the tutorial patch. Now lets examine the attributes which affect how the model is
rendered.

Lighting and Shading


We see the mushrooms in space, but their outlines are simply filled in with the medium gray which is the default color for
objects in the GL group.

The flat-shaded mushrooms.

Click on the toggle object above the message box reading lighting_enable $1 to send the message lighting_enable 1
to the jit.gl.model object.
Now, the model has a more solid appearance because some polygonal areas are brighter and others darker. But each polygon
has its own color uniformly over its entire area. The result is rather crude.

Click on the toggle object above the message box reading smooth_shading $1 to send the message smooth_shading 1
to the jit.gl.model object.
With smooth shading on, the shade of each polygon in the model is blended from vertex to vertex. This hides the polygon
edges and gives a smoother appearance -- we are beginning to get somewhere, if realism is our goal.
Mushrooms with lighting and smooth shading enabled.

Texture Mapping
Like other objects in the GL group, you can set the texture applied to the entire model with the texture message.

Click on the message box reading grid above the prepend texture object to send the message texture grid to the
jit.gl.model object.

This sets the texture of the model. Since there is a jit.gl.handle object connected to the jit.gl.model object in this patch, we
can rotate and move the model as discussed in Tutorial 32, in order to get a better look at how the texture is applied.

Notice the care with which the texture is wrapped around the mushrooms. The caps are covered radially, the stems
cylindrically, and there are small variations in the look of each mushroom. These texture coordinates were created in a 3D
modeling program by the maker of the model. The coordinates specify what point on the 2D texture to use at each vertex.

Mushrooms texture-mapped with care.

To see what the model looks like with automatically generated coordinates, you can use the tex_map message. As
discussed in tutorial 34, tex_map modes of 1, 2 and 3 specify object linear, sphere map, and eye linear mappings
respectively. tex_map 0 uses the coordinates specified in the model.

Experiment with these modes if you like, by changing the number box above the message box reading tex_map $1.When
you are done, restore the model to its built-in texture coordinates by setting the number box to 0.

In addition to the standard GL group facilities for applying textures, the jit.gl.model object can be used to apply a different
texture to each polygon group in the model.

Click on the message box reading 0 above the prepend texture object to turn off texturing for the model.

Click on the message box reading texgroup 1 grid.


The texgroup [group-number] [texture-name] message sets the texture of polygon group [group-number] in the model
to the texture [texture-name]. As a result of the message just sent, polygon group 1 should be set to the grid texture, and
thus one of the mushrooms is grid-covered while the other ones remain solid gray. This message could be used in
conjunction with the methods for updating textures covered in Tutorial 34 to apply a different picture or movie to each
polygon group in the model.

If a texgroup message is received for a given polygon group, that group uses the texture named in the message, instead of
any texture which may have been sent to the whole model using the texture message. If a texgroup [group-number] 0
message is received, the named texture is no longer used for that group, and the group reverts to the models overall texture.

Click on the message box reading texgroup 1 0 to remove the grid texture from polygon group 1.

Drawing Groups
In addition to being texture differently, the polygon groups in a model can be drawn separately. You can control this drawing
using the drawgroup message.

Click on the bang object above the counter object on the right-hand side of the tutorial patch.

This increments the counter, which causes the message drawgroup 1 to be sent to the jit.gl.model object. The polygon
groups are indexed starting at the number 1. When the jit.gl.model object receives the message drawgroup [n], it only
draws polygon group n of the model until further notice. So now you should see a lone mushroom in the frame.

By clicking the bang object repeatedly, you can cycle through each mushroom in turn. You could use this technique to load a
3D animation, by storing one frame of the animated object in each polygon group of the model.

When it receives the message drawgroup 0, the jit.gl.model object turns the drawing of all polygon groups back on.
Click on the message box reading drawgroup 0 to turn all the polygon groups back on.

Material Modes
Models can contain material definitions, but this particular model doesnt have any. Lets load one that does.

Click on the message box containing the text read apple.obj to load the apple model in the Tutorial folder.

This model is less complicated than the previous one, so it will load much faster. By reading the output of the jit.gl.model
object in the Max window, we can see that it has 4,452 triangles. We can also see in the Max window that it has 3 materials.
In the rendered image of the model, we can see the effects of these materials. Even though no textures have been applied,
the apple is red with a brown stem.

The apple model showing two materials.

The material_mode attribute of the jit.gl.model object determines to what extent the materials specified in the model file
will be used to render the model. Right now the material mode is 1, the default.

Set the number box above the message box reading material_mode $1 to the value 2.

You will notice that the skin of the apple takes on a shinier and slightly bluer appearance, while the stem remains the same
flat brown. This is because the specular components of the materials are now being used in the rendering. When we first
loaded the apple with the default setting for the material_mode attribute of 1, only the diffuse components of the materials
were being used in the rendering.
The apple with specular material components enabled.

Set the same number box to the value 0.

Now, none of the material properties of the model are being used in the rendering. Instead, the color attribute of the object is
used to determine the objects diffuse color. So, the model appears in the default gray. Lets try one more setting to see how
the various material modes can be useful.

Turn the toggle object above the lighting_enable $1 message box off. Then, try all the different settings for the
material_mode attribute.

You will see that with lighting disabled, only in material mode 1 do the objects materials have any effect. Since the diffuse
component of the material is being used to determine the objects color, the flat-shaded drawing takes on a different color for
each polygon group.

The flat-shaded apple with a material mode of 1.

Heres a quick recap of the settings of the material_mode attribute:


material_mode 0 dont use materials from model file. The objects color attribute determines the diffuse color, and the flat
color if lighting is not enabled.

material_mode 1 Use diffuse material component from model file to determine the diffuse color or flat color of the
rendered model.

material_mode 2 Use all material components from the model file.

Summary
We have seen how to load complex, multi-part 3D models from .obj format files on disk. The attributes of the jit.gl.model
object can be used to affect the models lighting and shading and to determine how its materials affect the rendering. The
model file may contain different polygon groups which may be drawn and texture-mapped individually.

Thanks to Oliver Ffrench http://o.ffrench.free.fr/meshbank for the use of these elegant freeware models.
See Also
Name Description
jit.gl.handle Use mouse movement to control position/rotation
jit.gl.model Read and draw various 3D model formats
jit.gl.render Render Jitter OpenGL objects
jit.pwindow Show data in a patcher
Geometry Under the Hood
Tutorial 37: Geometry Under the Hood
This tutorial demonstrates the low-level support in Jitter to specify geometry data as matrices and render them with the
jit.gl.render object. Since the data is contained in an ordinary Jitter matrix, this opens up a world of possibilities where
arbitrary matrix operators may be used to generate and/or process the geometry matrices. The tutorial will cover the
matrixoutput attribute of the GL group, the organization of data in geometry matrices, an example of how geometry
matrices can be processed using matrix operators, and introduce various drawing primitives supported by the jit.gl.render
object.

Open the tutorial patch 37jGeometryUnderTheHood in the Jitter Tutorial folder, and click on the toggle object labeled
Start Rendering.

Matrix Output
Click on the toggle box labeled Turn matrixoutput on/off.

Wait a minutethe sphere that was just there a moment ago has disappeared. What's going on?

Some of the objects in the GL group support the matrixoutput attribute, and jit.gl.gridshape is one such object. This
attribute determines whether or not the object's geometry is rendered directly in the object's associated drawing context or if
the object sends a matrix containing geometry data out its left outlet. The geometry is not visible because it is being sent to a
gate, which is closed.

Select the menu item print from the umenu object labeled "Matrix Destination"
In the max window you should see a series of messages like "print: jit_matrix u26300000007 quad_grid". This is similar to
what you've seen in previous tutorials as the output of objects, which pass matrix data, with the exception, that there is an
extra element. Rather than sending the message jit_matrix [matrix-name], as you should be familiar with, the
jit.gl.gridshape object sends message jit_matrix [matrix-name] [drawing-primitive]. In this case the drawing primitive
is quad_grid, which means interpret the matrix as a grid of quadrilaterals.
The output of the jit.gl.gridshape object in the Max window

At the time this tutorial was written, the only objects that support the matrixoutput attribute are the jit.gl.gridshape
, jit.gl.nurbs, and jit.gl.plato objects. However, by the time you read this, there may be other objects, which support
this mode of operation.

There is still no excitement in our window, but this is easily remedied.

Select the menu item direct from the umenu object labeled Matrix Destination.
The sphere is now visible again, because the message jit_matrix [matrix-name] [drawing-primitive] is being sent to the
jit.gl.render object. In response to this message, the jit.gl.render object draws the supplied matrix using the specified
drawing primitive. If no drawing primitive is specified, the jit.gl.render object's current drawing primitive will be used.
Valid drawing primitives are: points, lines, line_strip, line_loop, triangles, tri_strip, tri_fan, quads, quad_strip,
polygon, tri_grid, and quad_grid.

The jit.gl.render object's current drawing primitive may be set by sending the message [drawing-primitive] where
[drawing-primitive] is any one of the valid drawing primitives mentioned above.

In the same fashion that you can change the dimensions of video data, you can change the dimensions of the matrix output
by sending the jit.gl.gridshape object the dim message. By default the dimensions of the matrix output by the
jit.gl.gridshape object is 20 by 20.

Click on the toggle box labeled Wireframe.

Change the number box labeled Matrix Dimensions.

Try rotating the wireframe sphere with the mouse

The Death Star plans are not in the main computer.

You may have noticed that in this patch the jit.gl.handle object is communicating with the jit.gl.render object rather
than the jit.gl.gridshape object. This has the effect of rotating and positioning the entire scene. The
@inherit_transform 1 argument is necessary in order to do this correctly, otherwise the rotation would be
compositied again with the scene's rotation, causing major confusion.

Geometry Matrix Details


Video in Jitter is typically represented by 4-plane char data, but how is the geometry data being represented?

Each vertex in the geometry is typically represented as float32 data with 3, 5, 8, 12, or 13 planes. Planes 0-2 specify the x, y
and z position of the vertex. Planes 3 and 4 specify the texture co-ordinates s and t. Planes 5-7 specify the normal vector nx,
ny and nz used to calculate the effects of lighting on the geometry. Planes 8-11 specify the red, green, blue, and alpha vertex
color. Plane 12 specifies the edge flag e.

The output matrix of the jit.gl.gridshape object has 12 planes, but since we are not applying a texture to the geometry, and
lighting is not enabled, the texture coordinates and normal vectors are ignored.

Processing the Geometry Matrix


Instead of simply rendering the geometry unaltered, as you've done so far, it is possible to process this geometry with matrix
operators.

Select the menu item xfade from the umenu object labeled Matrix Destination.
Now the matrix is being sent through the jit.xfade object to cross fade the geometry matrix with a matrix of noise. Just as
the jit.xfade object may be used to crossfade between video matrices, it may be used to crossfade between geometry
matrices.

Click on the button object labeled "Generate Noise"


Gradually change the number box labeled "Crossfade Value" to 0.1.

Turn wireframe rendering on and off by clicking the toggle box labeled Wireframe. Notice how the noise deforms both the
geometry and the color of the shape.

This will subtly deform the sphere with noise, as well as introduce random colors. The texture coordinates and normal
vectors are also being affected, but this is not visible since there is no texture being applied, and lighting is not enabled.

A slightly distorted sphere (wireframe and filled)

Click on the button object labeled "Generate Noise" several more times, or turn on the toggle box labeled "Rapid Noise" to
generate a new matrix of noise for each time the geometry is drawn

Gradually change the number box labeled "Crossfade Value" to 1.0. Again, turn wireframe rendering on and off to see how
the noise is visualized.

Now the geometry being drawn is pure noise.


White noise expressed as a geometry (wireframe and filled)

Set the number box labeled "Crossfade Value" back to 0.

Drawing Primitives
You will notice that despite the fact that jit.gl.gridshape is outputting the message jit_matrix [matrix-name] quad_grid,
we are appending the output of jit.xfade with quad_grid. This is because most matrix operators will ignore the drawing
primitive argument and simply output the message jit_matrix [matrix-name]. Hence we need to append the name of the
drawing primitive to the message. This provides a good opportunity to experiment with various drawing primitives.

Try selecting the various menu items available in the umenu labeled Drawing Primitive.
Using different drawing primitives: points (left), line_strip (center), and triangles (right)

Summary
In addition to drawing directly to their associated drawing contexts, some objects in the GL group support the matrixoutput
attribute. When enabled, the geometry matrix is sent out the object's left output with the message jit_matrix [matrix-
name] [drawing-primitive].

Geometry matrices are typically float32 data with a plane count of 3, 5, 8, 12, or 13 planes, and may be processed using
arbitrary matrix operators in a similar fashion to processing video matrices.

The jit.gl.render object supports various drawing primitives to render these geometry matrices: points, lines, line_strip,
line_loop, triangles, tri_strip, tri_fan, quads, quad_strip, polygon, tri_grid, and quad_grid.

See Also
Name Description
jit.gl.gridshape Generate simple geometric shapes as a grid
jit.gl.handle Use mouse movement to control position/rotation
jit.gl.render Render Jitter OpenGL objects
jit.xfade Crossfade between 2 matrices
Basic Performance Setup
Tutorial 38: Basic Performance Setup
In this chapter, we will walk through the various steps involved in setting up your Jitter patch for live performance. Along the
way, we'll look at using a second video monitor for fullscreen output.

Open the tutorial patch 38jPerformanceSetup in the Jitter Tutorials folder.


Most of the patches we've looked at so far use the jit.pwindow object for displaying video data. While that object is
extremely practical for looking at video inside of your patch, it's not so ideal for live performance (unless you want the
audience to see your patch, too). In these situations, we use the jit.window object (which you may remember from way back
in Tutorial 1: Play A Movie).

Click on the message box labeled read dishes.mov and turn on the toggle box labeled Start Movie to begin movie
playback. You should see the movie playing in the jit.window object's window.

What's that @noaccel 1 attribute typed into the jit.window object? That tells the object that we want to disable
OpenGL acceleration. For the purposes of this tutorial, we're going to ignore some of the more advanced features of
jit.windowin particular, the ability to use Jitter's OpenGL support to improve the appearance and overall speed of
video data. Don't worry, though. Those features will be covered in later Tutorial chapters.

Let's take a look at some of the capabilities of the jit.window object. In addition to moving and sizing the window with the
mouse (clicking in the lower right hand corner lets us resize the window manually), we can send messages to the object and
cause the window to move or resize, we can remove the window's border, make the window float above all other windows,
and we can make the window fill the entire screen.

Resizing the jit.window object's window with the mouse.


Click on the message box labeled size 160 120 and see what happens. Just like the jit.pwindow object, the jit.window
object automatically scales incoming video to fit the size of the window when it receives the message size 160 120. Click on
the message box labeled size 320 240 to return to the original size.
Click on the message box labeled pos 300 400 and see what happens. We can move the window to any valid screen
position, just by sending it the pos (position) message followed by coordinates. We'll use this feature in a little bit to create
an automatic window-placement patch. Click on the message box labeled pos 800 100 to return to the original position.

Turn off the toggle labeled Border On/Off and see what happens. The window's title bar and (on Windows) border should
have disappeared. Turn the toggle on to bring the border back.
Turn on the toggle labeled Float On/Off and see what happens. A floating window "floats" above all non-floating
windows, and can never be sent to the back (although another floating window could cover it). Causing a window to float can
help you to ensure that your video data is always visible if you have a complex patch with many windows. Turn the toggle off
to turn off floating for this window.

Finally, press the escape key (esc) on your computer keyboard and watch how the window automatically fills the entire
screen of your primary monitor. Pressing the escape key again will collapse the window back to its previous size.

If you look in the patch, we can see clearly how this last trick functions. We've simply used the Max key object in
combination with a select object to listen for the escape key (ASCII key code 27). When that key is pressed, a bang is sent
from the select object to the toggle, causing it's state to change from 1 to 0 or from 0 to 1 (depending on what it was before
it received the bang). This value is sent to the message box labeled fullscreen $1, causing the messages fullscreen 1 and
fullscreen 0 to be sent to the jit.window object.
Hooking this message up to a key is particularly clever, because once the window is fullscreen, it's sometimes a little tricky to
get back to your patch! By the way, the jit.window object has a useful attribute fsmenubarwhich tells it whether or not
to hide the system menu bar when the object is in fullscreen mode. By default, the fsmenubar attribute is set to 1, meaning
that the menubar should stay where it is.

Toggling the fullscreen state of the jit.window object with the escape key.

Got It Covered
Most of the time, though, we want to be able to use our patch on one screen, while looking at the output on another. The
jit.window object is capable of putting a window on any display attached to your computer (or display device, like a video
projector).

As far as your computer is concerned, once you've attached additional displays in a spanning configuration (that means, the
displays aren't mirroring one another), you simply have one large display area. Moving windows to a second screen is simply
a matter of knowing the correct coordinates.
A view of a two-monitor system, with coordinates.

Of course, figuring out where your second monitor is located and doing the math is a little bit boring. Luckily, Jitter includes
an object, jit.displays, which can figure it all out for you.

The jit.displays object in action.

Using the jit.displays object to enumerate the number and coordinates of attached monitors is simple. The count message
causes the word count, followed by the number of attached displays to be sent from the object's left outlet. In our patch,
we're testing to make sure that there are more than one attached display using the > (greater-than) object. If there are, the
message coords 1 is sent to the jit.displays object, requesting the coordinates of monitor 1 (monitors are numbered
starting at 0your primary display is typically monitor 0).

Click on the message box labeled count. If you have a second monitor attached to your computer, the jit.window object's
window should have appeared on it. By simply using the top-left coordinates of the second display as the basis for a simple
calculation (we added 50 pixels to each coordinate to make sure that we avoided any menubars), we were able to send a pos
message to the jit.window object and position the window squarely on it.
Press the escape key again. The window should have gone into fullscreen mode, but this time, on the second display. The
jit.window object figures out which display it's on before entering fullscreen mode, to ensure that the correct area of the
screen gets covered.

Press the escape key again to disable fullscreen mode.


Of course, the jit.displays object will work with systems comprising more than two displays.

Typically, you'll want to keep a variation of this portion of the patch as part of your performance setup. We've noticed that
the position settings for a second (or third) display don't always remain the same from use to use, when connecting different
kinds of devices to our computers. Using the jit.displays object to automatically determine the exact position of your
attached hardware and move your output window eliminates some of the hassle and worry of working in new venues or with
unfamiliar equipment.

A Little Performance Tip


Now that we've mastered the jit.window object, let's turn our attention back to the jit.pwindow object. Although the
purpose of this tutorial isn't to offer tips and tricks for improving Jitter's performance, the jit.pwindow object is so often
used as a small monitor in live performance settings, that a quick look at its effect on playback speed is worth our time.

Click the cell in the matrixctrl object labeled jit.pwindow to route the video data to the jit.pwindow object. You should see
video in both the jit.window object's window and the jit.pwindow object. Compare the framerates (as reported by the
jit.fpsgui object) with the jit.pwindow object enabled and disabled. On our computer, we get around 300 frames per second
with the jit.pwindow disable and about 110 frames per second with it enabled. With the jit.pwindow object enabled and the
jit.window object turned off, we get around 260 frames per second. Your results will vary widely depending on your
computer's operating system and hardware.

Unlock the patch and open the jit.pwindow object's Inspector (on Macintosh, this is accomplished by selecting the object
and pressing Command(Apple)-I. On Windows, Ctrl-I. You can also open the Inspector on both platforms by choosing Get
Info... from the Object menu with the object selected).

The jit.pwindow object's Inspector

Do you see the checkbox labeled Onscreen in the jit.pwindow object's Inspector? Uncheck it, and compare framerates with
both windows active. On our system, we get around 160 frames per second nownearly 50% faster! Anytime you are using a
jit.pwindow object which is smaller than the video being displayed (here, our video is 320x240, and our jit.pwindow is
80x60), you should turn off onscreen mode. It's a simple rule that will get the best possible speed from your performance
patch.

Onscreen and offscreen modes use different drawing algorithms to do their workdata is drawn directly to the display
in onscreen mode, while offscreen mode draws the data first to an offscreen buffer and then copies it to the display.
The algorithm used in onscreen mode doesn't favor downsampling, so the performance is not as good.

The Use Onscreen setting in the jit.pwindow object's Inspector is saved with the patch, so it need only be set once. You
can set the onscreen attribute directly from Max using messages, as well.

Another strategy for reducing the impact of jit.pwindow objects in your performance patch is to reduce the amount of data
being drawn. The Max speedlim and qlim objects are ideal for this purpose, although we're not going to demonstrate their
use in this tutorial (the speedlim object is discussed in Max Tutorial 16).

Summary
In this tutorial, we learned a few strategies for overcoming typical challenges in a performance environment: the appearance
settings for the jit.window object; the fullscreen mode; the use of the jit.displays object to sense additional display
hardware attached to your computer and autoconfigure the position of a jit.window object's window; and the management
of the jit.pwindow object's onscreen drawing mode to improve the performance of your in-patch screens.

See Also
Name Description
jit.displays Set and query monitor attributes
jit.pwindow Show data in a patcher
jit.window Display data in a window
Spatial Mapping
Tutorial 39: Spatial Mapping
In this tutorial, we will look at ways to remap the spatial layout of cells in a Jitter matrix using a second matrix as a spatial
map. Along the way, well investigate ways to generate complete maps through the interpolation of small datasets as well as
ways to use mathematical expressions to fill a Jitter matrix with values.

Jitter matrices can be remapped spatially using lookup tables of arbitrary complexity. In Tutorial 12, we learned that the
jit.charmap object maps the cell values (or color information) of one Jitter matrix based on a lookup table provided by a
second Jitter matrix. In a similar fashion, the jit.repos object takes a Jitter matrix containing spatial values that it then uses
as a lookup table to rearrange the spatial positions of cells in another matrix.

Open the tutorial patch 39jSpatialMapping in the Jitter Tutorials folder.


The tutorial patch shows the matrix output of a jit.qt.movie object being processed by a new object, called jit.repos. The
right inlet of jit.repos receives matrices from the output of a jit.xfade object fed by two named matrices, each of which has
been given a name (stretch and cartopol) so that they share data with jit.matrix objects elsewhere in the patch. To the right
of the main processing chain are two separate areas where we construct those two matrices, which will serve as our spatial
maps for this tutorial.

Click the message box that reads read colorswatch.pict to load an image into the jit.qt.movie object. Click the toggle
labeled Display to start the metro object.
Notice that at this point, we only see a solid white frame appear in the jit.pwindow object at the bottom-left of the patch.
This is because we havent loaded a spatial map into our jit.repos object.
Click the first box in the preset object in the area of the patch labeled Generate stretch matrix. Youll see the pictslider
objects snap to various positions and a gradient progressing from magenta to green appear in the jit.pwindow at the bottom
of that section.

We now see a normal looking image appear in the jit.pwindow at the bottom of our patch.

The Wide World of Repos


Try manipulating the pictslider objects that set values in the stretch matrix. Notice that the effect is to stretch and twist
our image. By manipulating the pictslider objects one at a time, we can see that they distort different areas of the screen in a
3x3 grid. Clicking the first box in the preset object will return the image to normal.
Hall of mirrors.

The pictslider objects in our patch set individual cells in a 2-plane, 3x3 Jitter matrix of type long. This matrix is then
upsampled with interpolation to a 320x240 matrix named stretch. This matrix contains the instructions by which jit.repos
maps the cells in our incoming matrix. The interpolation here is necessary so that we can infer an entire 320x240 map from
just nine specified coordinate points.

The spatial map provided to the jit.repos object in its right inlet contains a cell-by-cell description of which input cells are
mapped to which output cells. The first plane (plane 0) in this matrix defines the x coordinates for the mapping; the second
plane (plane 1) represents the y coordinates. For example, if the cell in the upper-left hand corner contains the values 50 75,
then the cell at coordinates 50 75 from the matrix coming into the left inlet of the jit.repos object will be placed in the
upper left-hand corner of the output matrix.

The following example will give us a better sense of what jit.repos is doing with its instructions:
A simple spatial map.

In this example, we have a simple single-plane 5x5 matrix filled with ascending numbers being remapped by a spatial map.
Notice the correlation between the values in the spatial map and where the corresponding cells in the output matrix get their
original values from in the input matrix. For example, the cell in the lower-left of the spatial map matrix reads 4 0. The cell
at coordinate {4, 0} in the incoming matrix is set to value 5. As you can see, the cell in the lower-left of the output matrix
contains that value as well.

Similarly, you can see that the cells comprising the middle row of the output matrix are all set to the same value (19). This is
because the corresponding cells in the spatial map are all set to the same value (3 3). Cell {3, 3} in the input matrix contains
the value 19; that value is then placed into that entire row in the output matrix.

In our tutorial patch, our spatial map needs to be able to contain values in a range that represents the full size (or dim) of
the matrix to be processed. Because the image that we want to distort is 320x240, we need to use a matrix of type long for
our spatial map. If it was of type char, we would be constrained to values in the range of 0 to 255, limiting what cells we can
choose from in our spatial map. Note that in order to correctly view these long matrices in jit.pwindow objects we use the
jit.clip object to constrain the values in the matrix before viewing to the same range as char matrices.

Technical Note: The default behavior of jit.repos is to interpret the spatial map as a matrix of absolute coordinates,
i.e. a literal specification of which input cells map to which output cells. The mode attribute of jit.repos, when set to 1,
places the object in relative mode, wherein the spatial map contains coordinates relative to their normal position. For
example, if cell {15, 10} in the spatial map contained the values -3 7, then a jit.repos object working in relative mode
would set the value of cell {15, 10} in the output matrix to the contents of cell {12, 17} in the input matrix (i.e. {15-3,
10+7}).

Play around some more with the pictslider objects to get a better feel for how jit.repos is working. Notice that if you set
an entire row (or column) of pictslider objects to approximately the same position you can stretch an area of the image to
cover an entire horizontal or vertical band in the output image. If you set the pictslider objects in the left columns to values
normally contained in the right columns (and vice versa), you can flip the image on its horizontal axis. By doing this only
part-way, or by positioning the slider values somewhere in between where they sit on the normal map (as set by the preset
object) you can achieve the types of spatial distortion commonplace in funhouse mirrors, where a kink in the glass bends the
reflected light to produce a spatial exaggeration.

Spatial Expressions
Now that weve experimented with designing spatial maps by hand, as it were, we can look at some interesting ways to
generate them algorithmically.

In the lower-right section of the tutorial patch, click the button labeled Generate. Set the number box labeled Crossfade
(attached to the trigger object in the main part of the patch) to 1.0.
Lollipop space.

The cartopol spatial map has been set by a mathematical expression operated on the output of the jit.gencoord object by
the jit.expr object. The results of this expression, performed on float32 Jitter matrices, are then copied into a long matrix
that serves as our spatial map. This spatial map causes jit.repos to spatially remap our incoming matrix from Cartesian to
polar space, so that the leftmost edge of our incoming matrix becomes the center of the outgoing matrix, wrapping in a spiral
pattern out to the final ring, which represents the rightmost edge of the input matrix. The boundmode attribute of jit.repos
tells the object to wrap coordinates beyond that range back inwards, so that the final edge of our output image begins to fold
in again towards the left side of the input image.

The jit.gencoord object outputs a simple Cartesian map of floating-point values; when you multiply the values in the matrix
by the dim of the matrix, you can easily get coordinates which literally correspond to the locations of the cells, as shown in
this illustration:
Normal Cartesian map.

The scale and offset attributes of jit.gencoord allow us to manipulate the range of values put out by the object, saving us
the step of using multiple jit.op objects to get our Cartesian map into the range we want. For our equation to work, we want
our starting map to be in the range of {-1, 1} across both dimensions (hence we multiply the normal Cartesian space by 2 and
offset it by -1).

The jit.expr object takes the incoming matrix provided by jit.gencoord and performs a mathematical expression on it, much
as the Max vexpr object works on lists of numbers. The expr attribute of the jit.expr object defines the expression to use.
The in[i].p[j] notation tells jit.expr that we want to operate on the values contained in plane j of the matrix arriving at inlet i.
The dim[i] keyword returns the size of the dimension i in the matrix. In our case, the notation dim[0] would resolve to 320;
dim[1] would resolve to 240.

Note that there are actually two mathematical expressions defined in the message box setting the expr attribute. The first
defines the expression to use for plane 0 (the x coordinates of our spatial map), the second sets the expression for plane 1
(the y coordinates).

Placed in a more legible notation, the jit.expr expression for plane 0:


hypot(in[0].p[0]*in[1]\,in[0].p[1]*in[2])*dim[0]

works out to something like this, if x is the value in plane 0 of the input, y is the value in plane 1 of the input, and a and b are
the values in the number box objects attached to the second and third inlets of the jit.expr object:
sqrt(ax2+by 2)*320

Similarly, the expression for plane 1:

(((atan2(in[0].p[1]*in[2]\,in[0].p[0]*in[1])/PI)*0.5)+0.5)*dim[1]

works out to something like this:

(((atan(by/ax)/)/2)+0.5)*240

Therefore, we can see that we are filling the x (plane 0) values of our spatial map with numbers corresponding to the length
of the hypotenuse of our coordinates (i.e. their distance from the center of the map), while we set the y (plane 1) values to
represent those values angle () around the origin.

In the lower-right section of the tutorial patch, change the number box objects attached to the jit.expr object. Note that
they allow you to stretch and shrink the spatial map along the x and y axes.

The jit.expr object can take Max numerical values (int or float) in its inlets in lieu of matrices. Thus the in[1] and in[2]
notation in the expr attribute refers to the numbers arriving at the middle and right inlets of the object.

Technical Note: The jit.expr object parses the mathematical expressions contained in the expr attribute as
individual strings (one per plane). As a result, each individual expression should be contained in quotes and commas
need to be escaped by backslash (\) characters. This is to prevent Max from atomizing the expression into a list
separated by spaces or a sequence of messages separated by commas. We can gain some insight into how jit.expr
parses its expressions by turning on the verbose attribute to the object (as we do in this tutorial). When an expr
attribute is evaluated, the object prints the expressions evaluation hierarchy to the Max window so we can see exactly
how the different parts of the expression are tokenized and interpreted.

Open the patcher object labeled steps. Click through the different expressions contained in the message boxes, each of
which shows a simpler stage of how we computed the cartopol map. The norm[i] and snorm[i] notation essentially
replicates the function of jit.gencoord here, generating a map of Cartesian values (0 to 1) or signed Cartesian values (-1 to
1) across the specified dimension.

Different stages of the Cartesian-to-polar mapping: (a) normal map, (b) normal map scaled and offset to a signed {-1, 1}
range, (c) hypotenuse only, (d) theta only

An important thing to notice with this subpatch is that the message box objects are directly connected to the jit.matrix
object in the main patch. The exprfill message to jit.matrix allows us to fill a Jitter matrix with values from a mathematical
expression without having to resort to using jit.expr as a separate object. The syntax for the exprfill method is slightly
different from the expr attribute to jit.expr: the first argument to exprfill is the plane to fill with values, so two exprfill
messages (separated by commas) are necessary to generate the spatial map) using this method.

Still Just Matrices


Slowly change the number box attached to the trigger object on the left of the patch from 1 to 0 and back again.
A partial cross-fade of the two spatial maps used in this tutorial.

The number box controls the xfade attribute of the jit.xfade object directly attached to the jit.repos object at the heart of
our processing chain. As a result, we can smoothly transition from our manually defined spatial map (the stretch matrix) to
our algorithmically defined one (the cartopol matrix). The ability to use Jitter processing objects to composite different
spatial maps adds another layer of potential flexibility. Because the two matrices containing our maps have the same
typology (type, dim, and planecount) they can be easily combined to make an infinite variety of composites.

Summary
The jit.repos object processes an input matrix based on a spatial map encoded as a matrix sent to its second inlet. The
default behavior is for jit.repos to process matrices spatially using absolute coordinates, such that the cell values in the
second matrix correspond to coordinates in the input matrix whose cell values are copied into the corresponding position in
the output matrix.

Spatial maps can be created by setting cells explicitly in a matrix and, if desired, upsampling with interpolation from a
smaller initial matrix. Maps can also be created by generating matrices through algorithmic means, such as processing a
normal Cartesian map generated by a jit.gencoord object through a mathematical expression evaluated by a jit.expr
object. The jit.expr object takes strings of mathematical expressions, one per plane, and parses them using keywords to
represent incoming cell values as well as other useful information, such as the size of the incoming matrix. If you want to fill
a Jitter matrix with the results of a mathematical expression directly, you can use the exprfill message to a jit.matrix object
to accomplish the same results without having to use a separate jit.expr object.
The jit.repos object can be used to generate a wide variety of spatial maps for different uses in image and data processing.
The jitter-examples/video/spatial folder of the Max examples folder contains a number of patches that illustrate the
possibilities of jit.repos.

See Also
Name Description
jit.cellblock Two-dimensional storage and viewing
jit.charmap Map 256-point input to output
jit.clip Limit data to a range
jit.expr Evaluate an expression to fill a matrix
jit.gencoord Evaluate a procedural basis function graph
jit.matrix The Jitter Matrix!
jit.pwindow Show data in a patcher
jit.qt.movie Play or edit a QuickTime movie
jit.repos Reposition spatially
jit.xfade Crossfade between 2 matrices
Drawing in OpenGL using jit.gl.sketch
Tutorial 40: Drawing in OpenGL using jit.gl.sketch
The OpenGL capabilities of Jitter provide us with a variety of tools for creating animated scenes in three dimensions. The
Jitter OpenGL objects weve looked at thus far each perform a fairly straightforward task, be it creating simple geometries
(jit.gl.gridshape and jit.gl.plato), importing OBJ models (jit.gl.model), or manipulating the position of objects and scenes
(jit.gl.handle). More complex scenes can be built by using several of these objects at once. After a certain point, however, it
may make sense to work with an object that understands OpenGL commands directly and can be used to perform a large
number of drawing commands at once. This object is jit.gl.sketch, and it is the subject of this Tutorial.
The jit.gl.sketch object interfaces with the OpenGL system in Jitter just as other OpenGL objects; as a result, it may help to
review Tutorial 30: Drawing 3D Text and Tutorial 31: Rendering Destinations before we begin. In addition, the messages
and attributes understood by jit.gl.sketch bear a strong resemblance to the methods and properties of the JavaScript sketch
object used in the Max jsui object. Tutorial 51: Designing User Interfaces in JavaScript in the Max Tutorials and Topics
manual will give you some additional information on the capabilities of OpenGL vector graphics that is common to both of
these systems.

The majority of the messages used by jit.gl.sketch are slightly modified versions of standard functions within the OpenGL
API. The entire API is outside the scope of this Tutorial; however, the standard reference for these functions (the OpenGL
Redbook) is available online at:
http://www.opengl.org/documentation/red_book/

Converting between OpenGL code as given in the Redbook and elsewhere (in the C programming language) and messages
to jit.gl.sketch is reasonably straightforward if the following conventions are kept in mind:
All OpenGL commands are lowercase in jit.gl.sketch. Thus the OpenGL function glColor() becomes the Max message
glcolor sent to jit.gl.sketch.
OpenGL symbolic constants, in addition to being lowercase, lose their GL_ prefix, so that GL_CLIP_PLANE1 (in
OpenGL) becomes clip_plane1 when used with jit.gl.sketch, for example.
In addition to the basic OpenGL API, jit.gl.sketch also understands a number of high-level drawing commands to instruct
the object to render basic shapes and perform vector graphics-style drawing operations.

Open the tutorial patch 40jSketch in the Jitter Tutorials folder.


The Tutorial patch consists of a series of Jitter objects used for rendering in OpenGL: a jit.gl.render object, a jit.pwindow
object, and a jit.gl.sketch object. The jit.gl.sketch object is sent messages from a bpatcher object containing message box
objects containing lists of commands. Different views of the bpatcher can be obtained by selecting different offsets from
the umenu object connected to it. In this Tutorial well step through the different sections of the bpatcher one-by-one and
look at the messages contained in each view.

Our jit.gl.sketch object receiving messages from within a bpatcher.

Click on the toggle box labeled Display attached to the qmetro object at the top-left of the patcher.
By starting the qmetro object, weve begun rendering our OpenGL scene. Our jit.gl.render object shares its name (sketchy)
with the jit.pwindow object and the jit.gl.sketch object in the patch. Because of this, the jit.pwindow will display anything
drawn by the jit.gl.render object, which in turn will draw whatever the jit.gl.sketch object instructs it to draw.

The command list


Set the umenu object attached to the bpatcher to read one. The bpatcher object will show a message box containing a
series of messages separated by commas. Click on the message box to send its contents to our jit.gl.sketch object.
A green triangle should appear in the jit.pwindow object.

A green triangle drawn with a sequence of messages to jit.gl.sketch.

Technical Detail: The jit.gl.sketch object works by maintaining a command list of OpenGL commands that are then
executed every time the scene is drawn (in our patch, when the jit.gl.render object receives a bang). Most of the
messages we send to jit.gl.sketch become part of this command list. This command list can be stored in the internal
memory of the object or, if the displaylist attribute of jit.gl.sketch is set to 1, it can be stored on the GPU of our
computer. When working with large numbers of commands, turning on the displaylist attribute will speed up
rendering time; however, new commands added onto the list may take longer to be added if they are sent very quickly,
as they need to be loaded onto the GPU.

Our message box sends the following messages in sequence to jit.gl.sketch:

reset,

glcolor 0 1 0 1,

glbegin line_loop,

glvertex -0.5 -0.5,

glvertex 0 0.5,

glvertex 0.5 -0.5,

glend

The reset message to jit.gl.sketch simply tells the object to clear its command list and reinitialize itself. What follows are a
sequence of OpenGL commands. The glcolor command tells jit.gl.sketch to change the color it uses to draw. As with all
OpenGL objects in Jitter, these colors are floating-point values in RGBA (red, green, blue, alpha) order; thus, glcolor 0 1 0
1 tells jit.gl.sketch to draw in a fully opaque (alpha="1)" green.
The glbegin message tells jit.gl.sketch to interpret what follows as instructions defining an object. The argument to
glbegin specifies the drawing primitive to use when rendering the shape. The primitive weve chosen, line_loop, will take a
set of points (called vertices) and connect them with lines, completing the shape by connecting the last vertex to the first
vertex again. Thus in a shape with four points A, B, C, and D, our object will contain lines from A to B, B to C, C to D, and D
to A.

The glvertex messages contain the coordinates of the points in our shape. If only two coordinates are given, they are
interpreted as x and y values. If three coordinates are given, the last value is interpreted as a z coordinate. The glend
message tells jit.gl.sketch that weve finished defining the shape. We could then move on to another shape (or execute other
commands) if we so desired.

Step one of our patch therefore resets the object, sets the color to green, and instructs it to draw an outlined shape with three
vertices connected to one another. These messages (with the exception of the reset message) form the command list for
jit.gl.sketch for the image we see in the jit.pwindow.

More about drawing primitives


Select the umenu object and set it to two. Click on the message box that appears in the bpatcher. Our outlined triangle
should disappear and a filled green triangle should take its place.

A filled green triangle.

The list of commands in our message box is very similar to the first one:

reset,

glcolor 0 1 0 1,

glbegin triangles,

glvertex -0.5 -0.5,

glvertex 0 0.5,

glvertex 0.5 -0.5,

glend

Once again, we reset the object and then define a color (green) and an object with three vertices to be drawn. The only
difference is the drawing primitive specified as an argument to the glbegin message. In this example, were using triangles
as our drawing primitive. This tells jit.gl.sketch to interpret triplets of vertices as triangles. Rather than outlining the shape
as we did before, weve now instructed jit.gl.sketch to generate a polygon. As a result, the interior of our vertices is filled
with the specified glcolor (green).

There are ten (10) different drawing primitives recognized by OpenGL and, as a result, by objects such as jit.gl.render
and jit.gl.sketch. They are points, lines, line_strip, line_loop, triangles, triangle_strip (abbreviated tri_strip),
triangle_fan (abbreviated tri_fan), quads, quad_strip, and polygon. These primitives each specify the algorithm by
which a series of vertices will be connected. Tutorial 37: Geometry Under the Hood and Table 2-2 and Figure 2-7 of
the OpenGL Redbook give descriptions and examples of each and describe their common uses.

Set the umenu object in the Tutorial patch to three and click the message box that appears in the bpatcher. A triangle
with a rainbow surface will appear in place of the solid green triangle.
A shape with different colored vertices.

In this command list, weve embedded glcolor commands for each vertex of our triangle:

reset,

glbegin triangles,

glcolor 1 0 0 1,

glvertex -0.5 -0.5,

glcolor 0 1 0 1,

glvertex 0 0.5,

glcolor 0 0 1 1,

glvertex 0.5 -0.5,

glend

As a result, our jit.gl.sketch object sets our three vertices to red, green, and blue, respectively, and fills in the interior
surface with a color gradient that fades smoothly between the three colors. The smooth_shading attribute of jit.gl.sketch
allows this behavior when set to 1 (as is the case with the jit.gl.sketch object in our Tutorial patch).
Set the umenu object in the Tutorial patch to four. Set the umenu inside the bpatcher to fill. Our jit.pwindow now
contains a square with a rainbow-colored surface. Set the umenu to outline. Now we only see rainbow-colored lines
outlining the shape, as well as a diagonal across it.

A square made up of connected triangles, filled and unfilled.

This section of the bpatcher allows us to see how a drawing primitive works to make a more complex shape. We begin our
command list with the glpolygonmode command, which tells jit.gl.sketch whether to fill in complete polygons or leave
them as outlines, exposing the skeleton that defines how the vertices are connected. The first argument to glpolygonmode
defines whether were talking about the front of the shape, the back of the shape, or both (front_and_back, as were using
here). The second argument defines whether that side of the shape will be filled (fill) or left outlined (line). The poly_mode
attribute of the Jitter OpenGL objects accomplishes the same thing.

After weve reset and decided how we want our shape drawn (filled or outlined), we supply a shape description:

glbegin tri_strip,

glcolor 1 0 0 1,

glvertex -0.5 -0.5,

glcolor 0 1 0 1,

glvertex -0.5 0.5,

glcolor 0 0 1 1,

glvertex 0.5 -0.5,

glcolor 1 1 1 1,

glvertex 0.5 0.5,

glend

As with the triangle in our previous example, we provide a glcolor for each glvertex (in this example red, green, blue, and
white for the four points of the square). The tri_strip drawing primitive used as an argument to glbegin tells jit.gl.sketch to
draw the shape as a series of triangles where the last two vertices of a triangle are recycled into the next triangle. Thus a
polygon with six vertices A, B, C, D, E, and F would be drawn as four triangles using the tri_strip primitive: ABC, CBD, CDE,
and EDF (the ordering ensures that the triangles are all drawn with the same orientation). In our code, we get a shape with
two triangles that when connected and filled appear to us as a square.

Rotation, translation, and scaling


Set the umenu in the Tutorial patch to five. Click and drag the number box in the bpatcher slowly upwards from 0 to
360. The filled rainbow square from the previous example will reappear and rotate in a counter-clockwise direction.

An rotation matrix applied to an object.

In addition to defining shapes containing vertices and colors, we can instruct jit.gl.sketch to manipulate these shapes as
objects that can be animated and scaled. Our command list sets this up for us by supplying some additional commands:

reset,

glmatrixmode modelview,
glpushmatrix,

glrotate $1 0 0 1,

After resetting everything, we send the glmatrixmode message, which tells jit.gl.sketch we are going to be performing
perspective operations to define something called the modelview matrix. This allows us to perform rotation, translation, and
scaling on the object. The glpushmatrix message copies our current modelview matrix onto a stack, allowing us to return
to it later. This allows us to create nested translations for drawing complex objects. For example, we could draw a series of
polygons, each with rotations relative to the previous polygon; in this way we could generate sequences of shapes that have
the same orientation with respect to each other but could then all be rotated with respect to another group of shapes. The use
of a stack for this process greatly aids in modeling as we can use simple face-on coordinates for the vertices in our shapes
and then tell the renderer to compute the rotations for us. The glrotate command specifies the degrees of rotation for our
shape followed by three values that specify the axis of rotation as an xyz vector. Thus were rotating our object around the z
axis (which spins the shape along the x-y plane of the screen).

Following the rotation, we continue with our command list as in the previous example. At the end of the shape specification,
we complete our command list with the glpopmatrix command, which returns our jit.gl.sketch object to the previous
rotation. New commands added to the command list after that would then use the original rotation vector, not the one weve
applied to our shape.

Set the umenu to six, and manipulate the number box objects attached to the pak object inside the bpatcher. We can
now rotate our square around all three axes. In addition, lines are rendered to provide us with unit vectors to guide us in our
rotation.

A rotation matrix applied to multiple objects (a square and three vectors).

Our command list here sets up a new modelview matrix and performs the rotation three times in series:

reset,

glmatrixmode modelview,

glpushmatrix,

glrotate $1 1 0 0,

glrotate $2 0 1 0,

glrotate $3 0 0 1,

This allows us to rotate our shape along the x axis, y axis, and z axis in sequence according to the values of the number box
objects in our patch. We then create four objects using this rotation before we send a glpopmatrix to return to our original
orientation. After our square is rendered, we create three two-vertex lines in different colors oriented along the same axes as
the plane:

glcolor 1 0 0 1, glbegin lines, glvertex 0 0 0, glvertex 1 0 0, glend,

glcolor 0 1 0 1, glbegin lines, glvertex 0 0 0, glvertex 0 1 0, glend,


glcolor 0 0 1 1, glbegin lines, glvertex 0 0 0, glvertex 0 0 1, glend,

glpopmatrix

The drawing primitive lines simply connects all the vertices in the shape (unlike line_loop, it does not connect the last
vertex back to the first). Notice that because these objects (and our square) are all within the same modelview matrix, they
all share the same rotation.

Set the umenu to seven and manipulate the number box objects in the bpatcher. The colored square can be moved
along the x and y axes of the space.

A translation matrix applied to our shape.

In addition to image rotation, the modelview matrix can apply translation of an image. This allows us to specify vertices for
our object centered around (0, 0) and then move the object anywhere we want in the space. The gltranslate message in our
command list performs this function, taking as arguments the x and y offsets that will be applied to every vertex in the
shape(s) affected by the transformation.

Set the umenu to eight and manipulate the number box objects in the bpatcher. The colored square can be stretched
along both axes.

Our object transformed by scaling.

Just as we can rotate and translate a shape or shapes, we can also control their scaling with the glscale message. The
vertices in our shape are multiplied by the arguments to the glscale message (specified as x, y, and optional z scaling
factors).

The order in which you provide glrotate, gltranslate, and glscale commands to jit.gl.sketch is important, as they are
processed sequentially and cumulatively to create the final transformation of the affected objects. For example, say you
have a vertex at coordinates (0.5, 1). If you translate that vertex by (0.2, 0.2) and then scale it by (1.5, 1.5) the vertex
will end up at (1.6, 1.7). If you reverse the order of those operations (scale then translate), your vertex will end up at
(0.95, 1.7).

Summary
The jit.gl.sketch object gives us access to the powerful OpenGL API, allowing us to define and execute an OpenGL
command list within a Max patch. Lists of vertices, specified by glvertex messages and bracketed by glbegin and glend
messages, can be used to specify the shapes of objects. The glbegin command takes a drawing primitive as its argument
that defines the algorithm by which the vertices are connected and filled. You can use the glpolygonmode command to
expose the outlined structure of a shape, and you can color entire shapes or vertices using glcolor messages. You can
perform rotation, translation, and scaling of a defined shape by sending the glmatrixview command with the argument
modelview. Using glrotate, gltranslate, and glscale commands, you can then specify a viewing transformation. The
glpushmatrix and glpopmatrix commands allow you to define a stack of these transformations so that you can change the
rotation, position, and size of shapes either independently or in nested groups within a sequence of OpenGL commands.

See Also
Name Description
bpatcher Embed a subpatch with a visible UI
jit.gl.render Render Jitter OpenGL objects
jit.gl.sketch Use drawing commands with OpenGL
jit.pwindow Show data in a patcher
Shaders
Tutorial 41: Shaders
One of the primary purposes of graphics cards is to render 3D objects to a 2D frame buffer to display. How the object is
rendered is determined by what is called the "shading model", which is typically fed information such as the object's color
and position, lighting color and positions, texture coordinates, and material characteristics like how shiny or matte the object
should appear. The program that executes in hardware or software to perform this calculation is called the shader.
Traditionally graphics cards have used a fixed shading pipeline for applying a shading model to an object, but in recent years,
graphics cards have acquired programmable pipelines so that custom shaders can be executed in place of the fixed pipeline.
For a summary off many of the ways to control the fixed OpenGL pipeline, see Tutorial 35: Lighting and Fog.

Hardware Requirement: To fully experience this Tutorial, you will need a graphics card that supports
programmable shaders, e.g. ATI Radeon 9200, NVIDIA GeForce 5000 series or later graphics cards. It is also
recommended that you update your OpenGL driver with the latest available for your graphics card. On Macintosh, this
is provided with the latest OS update. On PC, you can acquire the latest driver from either your graphics card
manufacturer or your computer manufacturer.

Flat Shading
One of the simplest shading models which takes lighting into account is called Flat Shading or Facet Shading, where each
polygon has a single color across the entire polygon based on surface normal and lighting properties. As we saw
demonstrated in Tutorial 35, this can be accomplished in Jitter by setting the lighting_enable attribute of a Jitter OpenGL
object (e.g. jit.gl.gridshape) to 1.

Getting Started
Open the Tutorial patch 41jShaders in the Jitter Tutorial folder. Click on the toggle box labeled Start Rendering.

Click the toggle box object above the message box object reading lighting_enable $1 to turn on lighting for the
jit.gl.gridshape object drawing the torus. The smooth_shading attribute is 0 by default.

Now you should see a change in the lighting of the torus. Instead of the dull gray appearance it started with, you will see a
shiny gray appearance like this:

A rendered torus showing Flat shading.

Smooth Shading
While this might be a desirable look, the color of most objects in the real world changes smoothly across the surface.
"Gouraud Shading" (1971) was one of the first shading models to efficiently address this problem by calculating a per vertex
color based on surface normal and lighting properties. It then linearly interpolates color across the polygon for a smooth
shading look. While the artifacts of this simple approach might look odd when using a small number of polygons to
represent a surface, when using a large number of polygons, the visible artifacts of this approach are minimal. Due to the
computational efficiency of this shading model, Gouraud Shading has been quite popular and remains the primary shading
model used today by computer graphics cards in their standard fixed shading pipeline. In Jitter, this can be accomplished by
setting the smooth_shading attribute to 1 (on). Let's do this in our patch, increasing and decreasing the polygon count by
changing the dim attribute of the jit.gl.gridshape object.
Click the toggle box attached to the message box reading smooth_shading $1. Try increasing and decreasing the
polygon count by changing the number box attached to the message box reading dim $1 $1 in the lower right of the patch.

A torus rendered with smooth shading.

Per-Pixel Lighting
As mentioned, smooth shading with a low number of polygons has visible artifacts that result from just performing the
lighting calculation on a per vertex basis, interpolating the color across the polygon. Phong Shading (1975) smooths not only
vertex color across a polygon, but also smooths the surface normals for each vertex across the polygon, calculating a per
fragment (or pixel) color based on the smoothed normal and lighting parameters. The calculation of lighing values on a per
pixel basis is called "Per Pixel lighting". This is computationally more expensive than Gouraud shading but yields better
results with fewer polygons. Per pixel shading isn't in the OpenGL fixed pipeline; however we can load a custom shader into
the programmable pipeline to apply this shading model to our object.

Load the per-pixel lighting shader by clicking the message box that says read mat.dirperpixel.jxs connected to the
jit.gl.shader object.

Apply the shader to our object by clicking the message box shader shademe connected to the jit.gl.gridshape object.
This sets objects shader attribute to reference the jit.gl.shader object by its name (shademe).

Per-pixel shading applied to the torus.

Programmable Shaders
In 1984, Robert Cook proposed the concept of a shade tree, where one could build arbitrary shading models out of some
fundamental primitives using a "shading language". This shading language made it so that a rendering pipeline could be
extended to support an infinite number of shaders rather than a handful of predefined ones. Cook's shading language was
extended by Ken Perlin to contain control structures and became the model used by Pixar's popular RenderMan shading
language. More recently the GPU-focused Cg and GLSL shading languages were established based on similar principles. The
custom shaders used in this tutorial, including the per-pixel lighting calculation, were written in GLSL.

A brief introduction to how to write your own shaders will be covered in a subsequent Tutorial. For now, lets continue to use
pre-existing shaders and show how we can dynamically change shader parameters. Gooch shading is a non-photorealistic
shading model developed primarily for technical illustration. It outlines the object and uses warm and cool colors to give the
sense of depth desired for technical illustrations. We have a custom shader that implements a simplified version of Gooch
Shading which ignores the application of outlines.

Load the simplified Gooch shader by clicking the message box read mat.gooch.jxs connected to the jit.gl.shader object.

The simplified Gooch shading model applied to our torus.

You should notice that the warm tone is a yellow color and the cool tone is a blue color. These values have been defined as
defaults in our shader file, but are exposed as parameters that can be overridden by messages to the jit.gl.shader object.
Using the number boxes in the patch, send the messages param warmcolor <red> <blue> <green> <alpha> and
param coolcolor <red> <green> <blue> <alpha> to the jit.gl.shader object to change the tones used for the warm
and cool colors.

We can determine parameters available to the shader by sending the jit.gl.shader object the message dump params to
print the parameters in the Max window, or by sending the message getparamlist, which will output a parameter list out the
objects rightmost (dump) outlet. An individual parameter's current value can be queried with the message getparamval
<parameter-name>. A parameters default value can be queried with the message getparamdefault <parameter-
name>, and the parameters type can be queried with getparamtype <parameter-name>.

Vertex Programs
Shaders can be used not only to determine the surface color of objects, but also the position and attributes of our object's
vertices, and as we'll see in our next Tutorials. For now, let's look at vertex processing. In the previous shaders we just
discussed how the different shaders would render to pixels. In fact, for each of these examples we were running two
programs: one to process the vertices (the vertex program) and one to render the pixels (the fragment program). The vertex
program is necessary to transform the object in 3D space (rotation, translation, scaling), as well as calculate per-vertex
lighting, color, and other attributes. Since we see the object move and rotate as we make use of the jit.gl.handle object in
our patch, obviously some vertex program must be running. Logically, the vertex program runs on the programmable vertex
processor and the fragment program runs on the programmable fragment processor. This model fits with the fixed function
pipeline that also separates vertex and fragment processing tasks.

The custom vertex program in the previous examples, however, didnt visibly perform any operation that is noticeably
different than the fixed pipeline vertex program. So lets load a vertex shader that has a more dramatic effect. The
vd.gravity.jxs shader can push and pull geometry based on the vertex distance from a point in 3D space.

Load the simplified gravity vertex displacement shader by clicking the message box read vd.gravity.jxs connected to the
jit.gl.shader object.

Control the position and amount of the gravity vertex displacement shader by changing the number boxes connected to the
pak object and message box outputting the messages param gravpos <x> <y> <z> and param amount <n>,
respectively.
Vertex Distortion.

Summary
In this tutorial we discussed the fixed and programmable pipelines available on the graphics card and demonstrated how we
can use the programmable pipeline by loading custom shaders with the jit.gl.shader object. Shaders can then be applied
them 3D objects to obtain different effects. We can also set and query shader parameters through messages to the
jit.gl.shader object.

See Also
Name Description
jit.gl.gridshape Generate simple geometric shapes as a grid
jit.gl.handle Use mouse movement to control position/rotation
jit.gl.shader Manage a GL shader
Slabs and Data Processing on the GPU
Tutorial 42: Slab: Data Processing on the GPU
We saw in the previous tutorial how custom shaders can be executed on the Graphics Processing Unit (GPU) to apply
additional shading models to 3D objects. While the vertex processor and fragment processor are inherently designed to
render 3D geometry, with a little creativity we can get these powerful execution units to operate on arbitrary matrix data sets
to do things like image processing and other tasks. You might ask, "If we can already process arbitrary matrix data sets on
the CPU with Jitter Matrix Operators (MOPs), why would we do something silly like use the graphics card to do this job?"
The answer is speed.

Hardware Requirement: To fully experience this tutorial, you will need a graphics card which supports
programmable shaderse.g. ATI Radeon 9200, NVIDIA GeForce 5000 series or later graphics cards. It is also
recommended that you update your OpenGL driver with the latest available for your graphics card. On Macintosh, this
is provided with the latest OS update. On PC, this can be acquired from either your graphics card manufacturer, or
computer manufacturer.

Recent Trends in Performance


The performance in CPUs over the past half century has more or less followed Moores Law, which predicts the doubling of
CPU performance every 18 months. However, because the GPUs architecture does not need to be as flexible as the CPU and
is inherently parallelizable (i.e. multiple pixels can be calculated independently of one another), GPUs have been
streamlined to the point where performance is advancing at a much faster rate, doubling as often as every 6 months. This
trend has been referred to as Moores Law Cubed. At the time of writing, high-end consumer graphics cards have up to 8
vertex pipelines and 24 fragment pipelines which can each operate in parallel, enabling dozens of image processing effects at
DV resolution at full frame rate; we can even begin to process HD resolution images with full frame rate. Given recent
history, it would seem that GPUs will continue to increase in performance at faster rates than the CPU.

Getting Started
Open the Tutorial patch 42jSlabDataProcessing and double-click on the p slab-comparison-CPU subpatch to open it.
Click on the toggle box connected to the qmetro object. Note the performance of the patch as displayed by the jit.fpsgui
object at the bottom.

Close the subpatch and double-click on the p slab-comparison-GPU subpatch to open it. Click on the toggle box
connected to the qmetro object. Note the performance in the jit.fpsgui and compare it to what you got with the CPU
version.

The patches dont do anything particularly exciting; they are simply a cascaded set of additions and multiplies operating on a
640x480 matrix of noise (random values of type char). One patch performs these calculations on the CPU, the other on the
GPU. In both examples the noise is being generated on the CPU (this doesnt come without cost). The visible results of these
two patches should be similar; however, as you probably will notice if you have a recent graphics card, the performance is
much faster when running on the graphics card (GPU). Note that we are just performing some simple math operations on a
dataset, and this same technique could be used to process arbitrary matrix datasets on the graphics card.

CPU (left) and GPU (right) processed noise.


What about the shading models?
Unlike the last tutorial, we are not rendering anything that appears to be 3D geometry based on lighting or material
properties. As a result, this doesnt really seem to be the same thing as the shaders weve already covered, does it? Actually,
we are still using the same vertex processor and fragment processor, but with extremely simple geometry where the pixels of
the texture coordinates applied to our geometry maps to the pixel coordinates of our output buffer. Instead of lighting and
material calculations, we can perform arbitrary calculations per pixel in the fragment processor. This way we can use shader
programs in a similar fashion to Jitter objects which process matrices on the CPU (Jitter MOPs).

Open the Tutorial patch 42jSlabDataProcessing and double-click on the p slab-composite-DV subpatch to open it.
Click on the toggle connected to the leftmost qmetro object.
Click the message boxes containing dvducks.mov and dvkite.mov to load two DV movies, and turn on the corresponding
metro objects to enable playback.

Load a desired compositing operator from the umenu object connected to the topmost instance of jit.gl.slab.

UYVY DV footage composited on GPU using "difference" op.

Provided that our hardware can keep up, we are now mixing two DV sources in real time on the GPU. You will notice that
the jit.qt.movie objects and the topmost jit.gl.slab object each have their colormode attribute set to uyvy. As covered in
the Tutorial 49: Colorspaces, this instructs the jit.qt.movie objects to render the DV footage to chroma-reduced YUV 4:2:2
data, and the jit.gl.slab object to interpret incoming matrices as such. We are able to achieve more efficient decompression
of the DV footage using uyvy data because DV is natively a chroma-reduced YUV format. Since uyvy data takes up one half
the memory of ARGB data, we can achieve more efficient memory transfer to the graphics card.

Lets add some further processing to this chain.

Click the message boxes containing read cf.emboss.jxs and read cc.scalebias.jxs connected to the lower two instances
of jit.gl.slab.
Adjust these two effects by playing with the number boxes to the right to change the parameters of the two effects.
Additional processing on GPU.

How Does It Work?


The jit.gl.slab object manages this magic, but how does it work? The jit.gl.slab object receives either jit_matrix or
jit_gl_texture messages as input, uses them as input textures to render this simple geometry with a shader applied,
capturing the results in another texture which it sends down stream via the jit_gl_texture <texturename> message. The
jit_gl_texture message works similarly to the jit_matrix message, but rather than representing a matrix residing in main
system memory, it represents a texture image residing in memory on the graphics hardware.

The final display of our composited video is accomplished using a jit.gl.videoplane object that can accept either a jit_matrix
or jit_gl_texture message, using the received input as a texture for planar geometry. This could optionally be connected to
some other object like jit.gl.gridshape for texturing onto a sphere, for example.

Moving from VRAM to RAM


The instances of jit.gl.texture that are being passed between jit.gl.slab objects by name refer to resources that exist on the
graphics card. This is fine for when the final application of the texture is onto to 3D geometry such as jit.gl.videoplane or
jit.gl.gridshape, but what if we want to make use of this image in some CPU based processing chain, or save it to disk as an
image or movie file? We need some way to transfer this back to system memory. The jit.matrix object accepts the
jit_gl_texture message and can perform what is called texture readback, which transfers texture data from the graphics
card (VRAM) to main system memory (RAM).

Open the Tutorial patch 42jSlabDataProcessing and double-click on the p slab-readback subpatch to open it. Click on
the toggle boxes connected to the leftmost qmetro object. As in the last patch we looked at, read in the movies by clicking
on the message boxes and start the metro object on the right side of the patch.
Matrix readback from GPU.

Here we see that the image is being processed on the GPU with jit.gl.slab object and then copied back to RAM by sending
the jit_gl_texture <texturename> message to the jit.matrix object. This process is typically not as fast as sending data to
the graphics card, and does not support reading back in a chroma-reduced UYVY format. However, if the GPU is performing
a fair amount of processing, even with the transfer from the CPU to the GPU and back, this technique can be faster than
performing the equivalent processing operation on the CPU. It is worth noting that readback performance is being improved
in recent generation GPUs; in particular, PCI-e based graphics cards typically offer better readback performance than AGP
based graphics cards.

Summary
In this tutorial we discussed how to make use of jit.gl.slab object to use the GPU for general-purpose data processing. While
the focus was on processing images, the same techniques could be applied to arbitrary matrix datasets. Performance tips by
using chroma reduced uyvy data were also covered, as was how to read back an image from the GPU to the CPU.

See Also
Name Description
jit.fpsgui Display fps, ms, and matrix attributes
jit.gl.slab Process texture data
jit.gl.texture Create OpenGL textures
jit.gl.videoplane Display video in OpenGL
jit.matrix The Jitter Matrix!
jit.qt.movie Play or edit a QuickTime movie
qmetro Queue-based metronome
A Slab of Your Very Own
Tutorial 43: A Slab of Your Very Own
While there are many shaders that provided with the Jitter distribution, many of which can be composed to form more
complicated operations, one of the most exciting aspects of Jitters shader support is that you can write your own. Writing
shaders is fundamentally not a difficult process; however, it does involve text-based programming, so some understanding
of a programming language like C, Java, or Javascript is recommended before you take a crack at writing a shader.

Since there are a few more things to consider once you take lighting and complex geometry into account, we are going to
focus on the simple data processing of the jit.gl.slab object. We will use the GLSL shader language for this Tutorial, but note
that Jitter also supports programs written in Cg, as well as the ARB and NV assembly languages. Unfortunately it is out of
the scope of the Jitter documentation to fully describe any of these languages. This Tutorial is meant to give you a very
simple introduction to GLSL and demonstrate how to integrate shader code into a format Jitter understands. We will show
you the basics of what you need to know and refer you to more authoritative sources to find out more.

Hardware Requirement: To fully experience this tutorial, you will need a graphics card that supports
programmable shaders--e.g. ATI Radeon 9200, NVIDIA GeForce 5000 series or later graphics cards. It is also
recommended that you update your OpenGL driver with the latest available for your graphics card. On Macintosh, this
is provided with the latest OS update. On PC, this can be acquired from either your graphics card manufacturer, or
computer manufacturer.

Mixing Multiple Sources


Let's start with a 4-source video mixer. This could already be accomplished with a handful of instances of either the provided
math or compositing shaders, but it will be more efficient to do this all at once in a single shader. A mathematical formula for
this 4 source mix might look something like the following, where a, b, c, and d are constants for how much of each input we
want to accumulate.

output = a*input0 + b*input1 + c*input2 + d*input3

In GLSL, this might look something like the following:

uniform vec4 a;

uniform vec4 b;

uniform vec4 c;

uniform vec4 d;

void main (void)

vec4 input0;

vec4 input1;

vec4 input2;

vec4 input3;

vec4 output;

output = a*input0 + b*input1 + c*input2 + d*input3;

Weve defined a few global variables: a, b, c, and d, as well as a function called main() that contains local variables input0,
input1, input2, input3, and c, and d. The vec4 type is a vector with four values, which typically refer to a point (x,y,z,w) in
homogenous coordinates or a color (r,g,b,a). When we multiply two vec4 elements in GLSL as above, it is a pointwise
multiplication, resulting in another vec4 where each element of the multiplication is the product of the same element from
the two operandse.g. with m = p*q: m.r =p.r*q.r; m.g =p.g*q.g; m.b =p.b*q.b; m.a =p.a*q.a.

This program is a fragment program, and our main function will be executed once for each fragment (or pixel) in the image.
It has no knowledge about adjacent output pixels or when it is being run. This is what permits it to run several instances in
parallel for multiple fragments in order to obtain such high performance. CPUs dont have the same kind of restrictions, but
then the computation is not inherently parallelizable.

For detailed information about all things GLSL related (keywords, built in operators, built-in variables, syntax, etc.), we
recommend reading the OpenGL Shading Language Reference (aka The Orange Book) and the OpenGL Shading
Language Specification. The specification is available online at opengl.org. There are also several tutorials online for GLSL
such as the one hosted at lighthouse3d.com.

Fragment Program Input and Output


The above code is valid GLSL and looks similar to our original formula. However, it wont work yet. Right now weve declared
variables for input and output, but these values arent actually making use of any input and not assigning any values to the
output in the OpenGL pipeline. To get input, we need to sample values from textures, and to write to our output, we need to
write to the built-in gl_FragColor variable. With this in mind, we make the following modifications to our code:

uniform vec4 a;

uniform vec4 b;

uniform vec4 c;

uniform vec4 d;

// define our varying texture coordinates

varying vec2 texcoord0;

varying vec2 texcoord1;

varying vec2 texcoord2;

varying vec2 texcoord3;

// define our rectangular texture samplers

uniform sampler2DRect tex0;

uniform sampler2DRect tex1;

uniform sampler2DRect tex2;

uniform sampler2DRect tex3;

void main (void)

// sample our textures

vec4 input0 = texture2DRect(tex0, texcoord0);

vec4 input1 = texture2DRect(tex1, texcoord1);

vec4 input2 = texture2DRect(tex2, texcoord2);

vec4 input3 = texture2DRect(tex3, texcoord3);

vec4 output;

// perform our calculation

output = a*input0 + b*input1 + c*input2 + d*input3;


// write our data to the fragment color

gl_FragColor = output;

The varying keyword means that the parameter will be changing for each fragment. For example, texcoord0 will reference
the interpolated (x,y) pixel coordinate to extract from our leftmost input texture. We are able to sample this texture (i.e. get
the color value associated with the texture coordinate) by calling the texture2DRect() function with the corresponding
sampler ID and texture coordinate vector. The sampler2DRect data type and texture2DRect() function indicate that we are
using rectangular textures. Ordinary textures in OpenGL have dimensions restricted to powers of two for each dimension
(e.g. 256x256) and the values are indexed with normalized coordinates (fractional values from 0.-1.). Rectangular textures
on the other hand permit arbitrary dimensions (e.g. 720x480), and the coordinates are in terms of pixel position (e.g. 0.-
720., and 0.-480.). In Jitter we use rectangular textures as our default texture type for increased performance when working
with datasets that are not powers of two, as is often the case when working with video. Ordinary textures can still be used via
the sampler2D data type and the texture2D() function, but they require that the input textures have been created with the
rectangle attribute set to 0.

The Vertex Program


The above code is now our complete GLSL fragment program, but it still wont do anything yet, because it requires a vertex
program pass on our texture coordinates. As the name suggests, the vertex program runs once for each vertex in the
geometry. It is where any modification to the geometry is calculated, including the attachment of texture coordinates to that
geometry. Values generated by the vertex program can be automatically interpolated across the surface of the geometry as
we typically want to do with texture coordinates. For our vertex program, we will want to transform our vertex by the current
model-view projection matrix, transform our texture coordinates by the current texture transform matrix (this is how we
scale and possibly flip our rectangular texture coordinates), and then pass on our texture coordinates as varying values to our
fragment program. Such a vertex program might look like this:

// define our varying texture coordinates

varying vec2 texcoord0;

varying vec2 texcoord1;

varying vec2 texcoord2;

varying vec2 texcoord3;

void main( void )

// the output vertex postion to the input vertex position

// transformed by the current ModelViewProjection matrix

gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex;

// assign our varying texture coordinates to the

// input texture coordinate values transformed

// by the appropriate texture matrix. This is

// necessary for rectangular and flipped textures

texcoord0 = vec2(gl_TextureMatrix[0] * gl_MultiTexCoord0);

texcoord1 = vec2(gl_TextureMatrix[1] * gl_MultiTexCoord1);

texcoord2 = vec2(gl_TextureMatrix[2] * gl_MultiTexCoord2);

texcoord3 = vec2(gl_TextureMatrix[3] * gl_MultiTexCoord3);

}
(JXS)
These programs together will perform all the hard work to process all of our pixel data, but were still missing one final
component. In order for Jitter to load these programs and expose parameters to the user, we need to package these
programs in a Jitter XML Shader file (JXS). In this file we will specify user settable variables a, b, c, and d with default
values, bind our multiple texture units so that the program can access them properly, define our programs, and bind our user
variables to our program variables:

<jittershader name="fourwaymix>"

<param name="a" type="vec4" default="0.25" 0.25 0.25 0.25 />

<param name="b" type="vec4" default="0.25" 0.25 0.25 0.25 />

<param name="c" type="vec4" default="0.25" 0.25 0.25 0.25 />

<param name="d" type="vec4" default="0.25" 0.25 0.25 0.25 />

<param name="tex0" type="int" default="0" />

<param name="tex1" type="int" default="1" />

<param name="tex2" type="int" default="2" />

<param name="tex3" type="int" default="3" />

<language name="glsl" version="1.0>"

<bind param="a" program="fp" />

<bind param="b" program="fp" />

<bind param="c" program="fp" />

<bind param="d" program="fp" />

<bind param="tex0" program="fp" />

<bind param="tex1" program="fp" />

<bind param="tex2" program="fp" />

<bind param="tex3" program="fp" />

<program name="vp" type="vertex"

source="43j-fourwaymix.vp.glsl" />

<program name="fp" type="fragment"

source="43j-fourwaymix.fp.glsl" />

</language>

</jittershader>

The jittershader tag defines our shader with an optional name. The param tag defines a parameter to be exposed to the Max
environment with a name, type, and optional default value. The language tag defines a block of programs in the specified
language and version. The bind tag binds user-exposed parameters to variables in specific programs. Finally, the program tag
defines our programs with a name, type, and source file. The source may optionally be embedded in the XML file itself by
including it inside either an XML comment or CDATA block; this is the case with many of the shader files provided in the
Jitter distribution. For a complete reference of XML tags available, please see Appendix D: The JXS File Format.

Ready for Action


Now that all the pieces are in place, lets see our program do its job.
Open the Tutorial patch 43jYourVeryOwnSlab in the Jitter Tutorial folder. Click on the toggle box connected to the
qmetro object.

Read in a movie for each instance of jit.qt.movie, using either those provided in the message box objects or media of
your own choosing.

Load the shader by sending the message read 43j-fourwaymix.jxs to the jit.gl.slab object.

The patch that puts it all together.

You will notice that the jit.gl.slab object has its inputs attribute set to 4. This is necessary to have more than the default 2
inputs, as we want for our 4-way mix shader. We can also find out a bit about our program by sending the message dump
params or dump assembly to see what our code was compiled down to. Lastly, it is worth noting that for optimal
performance when loading and compiling shaders, Jitter keeps a cache of all compiled shaders; it will only recompile the
shader if it detects that the source files have been modified on disk. To flush the cache, you can send jit.gl.slab the message
flush_cache.
Summary
In this tutorial we demonstrated how to build a shader from scratch in GLSL that mixes 4 input sources on the GPU via a
jit.gl.slab object. This was accomplished by writing a fragment program, a vertex program, and wrapping them in a Jitter
XML Shader file so that our shader could be loaded into Jitter with parameters exposed to the user in Max. We also
demonstrated the use of more than 2 inputs for the jit.gl.slab object by using the inputs attribute.

See Also
Name Description
jit.gl.slab Process texture data
jit.gl.videoplane Display video in OpenGL
jit.qt.movie Play or edit a QuickTime movie
Flash Interactivity
Tutorial 44: Flash Interactivity

Apple has, in the intervening time since the initial writing of this tutorial, essentially removed support for Flash media
from QuickTime. As such, the information below should be regarded as obsolete and unsupported. Users wishing to
work with Flash media in Max might look at the jweb object, or 3rd party interface objects such as FLOSC.

Macromedia's Flash file format has been a highly successful and widely used means for creating and distributing interactive
contentparticularly over the Internet. Since the introduction of Jitter, users have been able to take advantage of
QuickTime's ability to read Flash media within the jit.qt.movie object, although the amount of control available was limited
to basic temporal and spatial manipulation. In this chapter, we'll explore some of the possibilities available to users of
Macromedia's Flash environment.

A Little Background
Flash was introduced in 1996 as a vector-based animation development tool, with output files that were optimized for
internet-based distribution (that means small!). Over the years, the basic toolset has expanded mightily, gradually
encompassing functionality familiar to users of Macromedia's other popular animation package, Director. This expansion
included object-based interactivity andin the last several versionsa fully featured scripting language called ActionScript,
which is based on JavaScript. The Flash file format has remained extremely compact and has generated such broad interest
that other software manufacturers have provided support. This is particularly due to the fact that the format specification
itself is open.

Jitter's support for Flash falls into two basic categories: on-screen interactivity and script interactivity. On-screen
interactivity refers to things like button-clicks, mouse movements and keyboard eventsthe kinds of interactions that we're
familiar with from using Flash in web browsers. Script interactivity is the ability to learn and change the properties of
ActionScript objects and variables. Working with ActionScript properties from Max provides a powerful means for
developers of Flash and Max content to link the two environments.

Clicks and Pops


Using the on-screen Flash interactivity features of Jitter doesn't require any knowledge of Flash or the underlying
programming inside of a Flash document.

Open the tutorial patch 44jFlashInteractivity in the Jitter Tutorials folder.


In fact, there should be no unfamiliar objects in this patchall of Jitter's Flash functionality is bundled inside the
jit.qt.movie object. With the help of the additional objects in the patch, we are able to route mouse and keyboard data to a
Flash movie.

Click the message box labeled read 44jBasic.swf. Click the toggle box labeled Display connected to the metro object at
the top of the patch. You should hear some soothing music and see an introductory screen in the jit.pwindow object.
The pinnacle of interface design: the introductory screen of 44jBasic.swf.

Take a few moments to become familiar with the Flash movie by clicking on the interface in the jit.pwindow object. There
are opportunities to select and enter text, to rollover and click on buttons and to hear some excellent sounds.

Pretty great Flash movie, right? So, let's understand how we're interacting with it. Since the movie isn't being played in a
special window that knows the type of media being displayed (like with Apple's QuickTime Player, which can automatically
pass events from the user interface to the movie), we have to manually pass events to the jit.qt.movie object, which passes
them along to the movie. Luckily, Max and Jitter already contain objects that can sense things like mouse position and
keyboard events, so most of our work has already been done for us.

We're using the mouse and mouseidle notification messages of the jit.pwindow object to find out where the mouse is
relative to the object's area. By default, the jit.pwindow object outputs a mouse message every time the mouse is clicked
over the object. We've also told the object to report idle mouse movements by sending it the idlemouse 1 message (when we
save the patch, this idlemouse preference is saved). This causes the mouseidle message to be output whenever the mouse
enters the screen region of the jit.pwindow object. The jit.window object outputs similar information, or we could also use
Max's mousestate object if we wanted to.
The jit.qt.movie object understands the message mouse in exactly the same format output by the jit.pwindow object to
simulate mouse movement or clicks over a Flash movie. Since jit.qt.movie doesn't understand the mouseidle message, we
have to change all of the messages beginning with the word mouseidle to begin with the word mouse, which we're doing
with the route and prepend objects. The newly formatted message is then sent to the jit.qt.movie object and will trigger the
appropriate interactivity in the Flash movie.

Similarly, to handle keyboard events, we can use Max's key object to acquire the necessary information, which we pass along
to the jit.qt.movie object as a keypress message (the three arguments for the keypress message match exactly with the
three numbers output from the key object).

From the key object to a keypress message and beyond.


That's it! On-screen Flash interaction in Jitter is really very simple to set up, and offers access to a large and exciting
selection of interactive media.

Hips to Scripts
If you're a Flash developer (or interested in becoming one), you'll be pleased to know that we can interact directly with
ActionScript inside of Flash movies. We can change variables and otherwise influence object behavior by sending Max
messages to the jit.qt.movie object.
Click the message box labeled read 44jPhysics.swf. If the toggle box labeled Display is turned off, turn it back on in
order to see the output of the Flash movie.

This movie is a simple physical simulator. By clicking and "throwing" the grey ball, we can see that the ball behaves similarly
to real thrown objects in the world. It travels through the air and, depending on how hard it is thrown, bounces off of walls,
losing a little bit of energy as it does, until it comes to rest on the ground. This behavior has been coded into the Flash movie
using Macromedia's scripting language, ActionScript.

An excerpt from the ActionScript code used in our physics simulator.

If you're familiar with Max's JavaScript implementation (or JavaScript in general), ActionScript should look familiar. In fact,
ActionScript is JavaScript, albeit with some extra Flash-specific Objects and functions (just like Max's implementation is
standard JavaScript, which contains specific Objects and functions that are only relevant to Max).

There are now two versions of ActionScript, called ActionScript 1.0 and ActionScript 2.0. At this time, QuickTime (and
Jitter) only supports ActionScript 1.0 features in Flash files saved with Flash Player 5 compatibility. This means that
some of Flash's newer features (Flash MX and later) are not currently available for Jitter users.

Our Flash document (the 44jPhysics.fla file used to generate our Flash movie) defines some global ActionScript variables.
Taking a look at the Actions for our Frame, we see:

// factor to multiply our energy by, when we hit a wall


var loss = 0.6;
// factor to divide our velocity by, as we travel through the air
var airfriction = 2.;

We can send the message flash_var to the jit.qt.movie object to modify the values of these variables.
Change the values in the number boxes labeled Loss Factor and Air Friction Divisor and note how the ball's behavior
changes.

We can also query the value of a variable by sending the message getflash_var to the jit.qt.movie object.
Click the message boxes labeled getflash_var airfriction and getflash_var loss and verify that your changes were updated
inside of the Flash movie. The output should be posted in the Max Window.

Although the output appears to be numeric, all output from the getflash_var message is symbolic. If you are working
with numeric data, rather than strings, you will need to use the fromsymbol object to convert the symbols to numbers.
Input can be any type.

So far, we've seen how to set and get global ActionScript variables. But what about nested variables? Examining the
44jPhysics.fla document within the Macromedia Flash application (sold separately), we can see the structure of our movie.

The structure of our Flash movie, and its symbol definitions, as seen in Flash

Our movie is really quite simple1 scene and 1 frame. The frame contains 2 items: some actions (ActionScript code) and a
Movie Clip instance of the symbol Ball_MC, whose instance name is ball. Looking at Ball_MC's symbol definition, we can
see that Ball_MC contains a Button called Ball_Button, which itself contains some actions.

If we want to know the x coordinate of our Movie Clip instance ball, we can use Flash's path syntax: /path/to.variable. In
our case, this is /ball._x, since ball is at the root level of the movie, and _x is the built-in variable describing the x position of
an object on the Flash Stage.

Click on the message box labeled getflash_var /ball._x, getflash_var /ball._y and watch the values in the floating point
number boxes change to reflect the position of the ball. Note the use of the fromsymbol objects to convert the symbolic
Flash output to floating point numbers.

Turn on the toggle box labeled Enable Sound. We're analyzing the x and y positions of the ball to detect when the ball has
hit a wall, and playing a tone in response.

Interestingly, we can't set the coordinates in this direct fashion. We need to have a special variable representing the
built-in variable, which gets checked every frame. See the p more_setting patcher and the source code in the
44jPhysics.fla document for more information on how this is done.

At the time of this writing, there is an additional limitation to getting and setting Flash variables. Variables must be
simplearrays don't work properly. As you design your ActionScript, this should be kept in mind to avoid a lot of
editing later in the process!

Summary
In this tutorial, we learned how to take advantage of Flash interactivity using the jit.qt.movie object's mouse and keypress
messages to simulate mouse-movements and keyboard activity. We also examined the flash_var and getflash_var messages,
which can be used to set and get ActionScript variables and influence the running of scripts within Flash movies.

See Also
Name Description
fromsymbol Convert a symbol into numbers/messages
jit.pwindow Show data in a patcher
jit.qt.movie Play or edit a QuickTime movie
Introduction to using Jitter within JavaScript
Tutorial 45: Introduction to using Jitter within JavaScript
The Max js object, introduced in Max 4.5, allows us to use procedural code written in the JavaScript language within Max. In
addition to implementing the core JavaScript 1.5 language, the Max js object, contains a number of additional objects and
methods specific to Max, e.g. the Patcher object (designed for interfacing with the Max patcher) or the post() method (for
printing messages into the Max window). There are a number of extensions to the js object that allow us to perform Jitter
functions directly from the JavaScript language when working with Jitter. For example, the Jitter extensions to js allow us
to:

Instantiate Jitter objects directly within JavaScript and create function chains of Jitter processes within procedural code.

Create Jitter matrices with JavaScript and access and set the values and parameters of Jitter matrices from within
JavaScript functions.

Use Jitter library operations (e.g. op and functor objects) to do fast matrix operations on Jitter matrices within JavaScript
to create low-level Jitter processing systems.

Receive callbacks from Jitter objects by listening to them and calling functions based on the results (e.g. triggering a new
function whenever a movie loops).

Before beginning this tutorial, you should review the basics of using JavaScript in Max by looking at several tutorials found
in the Max Tutorials and Topics manual: Tutorial 48: Basic Javascript and Tutorial 49: Scripting and Custom Methods in
JavaScript. These tutorials cover the basics of instantiating and controlling a function chain of Jitter objects within js
JavaScript code.

Open the tutorial patch 45jJavaScriptIntro in the Jitter Tutorials folder.


The tutorial patch shows us two columns of Max objects side-by-side. The right column contains a patch that processes a
movie through an effect and displays it. All of this is done using Jitter objects connected within the Max patch between the
qmetro object and the jit.pwindow object. The left column shows the qmetro and jit.pwindow objects, but contains only a
js object loading the JavaScript file 45jWakefilter.js in between. As we will learn, the two sides of the patch do pretty much
the exact same thing. First, well look at the patch on the right side to see whats happening.

Waking Up
On the right side of the patch, click the toggle box labeled Display Processing using Patcher. Click the message box that
reads read countdown.mov, also on the right side.

We use qmetro objects instead of metro objects in our patch because of the potential for scheduler backlog when
working with JavaScript. The normal behavior of the Max js object is for it to create a queue of pending events while it
executes the current one; as a result, a fast metro object will quickly accumulate a large backlog of bang messages for
the js object to deal with. The qmetro object sends bang messages to the back of the low priority queue where they can
be usurped by subsequent messages. See Tutorial 16: Using Named Jitter Matrices for a more in-depth discussion on
this topic.

The movie should appear in the jit.pwindow with a gradually changing colored effect.
A typical Jitter video effect chain.

This side of the patch plays back a QuickTime movie (using a jit.qt.movie object) into an edge detection object
(jit.robcross), which is then multiplied by the output of a named matrix called bob (using jit.op). The matrix output by
jit.op is then processed by a jit.wake object, which applies a temporal feedback and spatial convolution to the matrix, the
parameters of which can be controlled independently for each plane. The output of the jit.wake object is then brightened
slightly (with a jit.brcosa object) and then stored back into our named matrix (bob). The output of our effects chain as seen
in the jit.pwindow is the output of the jit.wake object.

The technique of using named Jitter matrices for feedback is covered in Tutorial 17: Feedback Using Named Matrices.
The jit.robcross object applies the Roberts Cross edge detection algorithm (a similar object that allows us to use two
other algorithms is called jit.sobel). The jit.wake object contains an internal feedback matrix that is used in
conjunction with image convolution to create a variety of motion and spatial blur effects (similar effects could be
constructed using objects such as jit.slide and jit.convolve).

Open the patcher object named random_bleed.


The key to the variation of our processing algorithm is this subpatch, containing twelve random objects that are controlling
different parameters of the jit.wake object in the main processing chain. The output of these random objects is scaled for us
(with scale objects) to convert our integer random numbers (0 to 999) into floating-point values in the range 0 to 0.6.
These values are then smoothed with the two * objects and the + object, implementing a simple one-pole filter:
y n = 0.01xn + 0.99y n-1
These smoothed values then set the attributes of jit.wake that control how much bleed occurs in different directions (up,
down, left, right) in different planes (specified as the color channels red, green, and blue). Youll notice that the smoothing
algorithm is such that the values in all of the number box objects showing the smoothed output tend to hover around 0.3
(or half of 0.6). Our Jitter algorithm exhibits a slowly varying (random) color shift because of the minute differences
between these sets of attributes.

Back in the main tutorial patcher, try changing movies by clicking the message box objects reading read wheel.mov and
read dozer.mov. Compare the effects on these two movies with the effect on the countdown movie. Note that when we
read in new movies, we initialize the bob matrix to contain all values of 255 (effectively clearing it to white).

The Javascript Route


Shut off the qmetro object on the right side of the patch by clicking the toggle box above it. Activate the qmetro object on
the left side of the patch by clicking the toggle box attached to it.
Click the message box that reads read countdown.mov on the left side of the patch.

Look familiar?

The video on the left side of the patch looks strikingly familiar to that displayed on the right side. This is because the js
object on the left side of the patch contains all the objects and instructions necessary to read in our movie and perform the
matrix processing for our effect.

Double-click the js object in our Tutorial patch. A text editor will appear, containing the source code for the js object in the
patch. The code is saved as a file called 45jWakefilter.js in the same folder as the Tutorial patch.

Our JavaScript code contains the familiar comment block at the top, describing the file, followed by a block of global code
(executed when the js object is instantiated) followed by a number of functions weve defined, most of which respond to
various messages sent into the js object from the Max patcher.

Creating Matrices
Look at the code for the global block (i.e. the code before we arrive at the bang() function).

Our code begins with the familiar statement of how many inlets and outlets wed like in our js object:

// inlets and outlets


inlets = 1;
outlets = 1;
Following this, we have a number of statements we may never have seen before:

// Jitter matrices to work with (declared globally)


var mymatrix = new JitterMatrix(4, "char", 320, 240);
var mywakematrix = new JitterMatrix(4, "char", 320, 240);
var myfbmatrix = new JitterMatrix(4, "char", 320, 240);

// initialize feedback matrix to all maximum values


myfbmatrix.setall(255, 255, 255, 255);

This block of code defines that we will be working with a number of Jitter matrices within our js object. The variables
mymatrix, mywakematrix, and myfbmatrix are defined to be instances of the JitterMatrix object, much as we would declare
an Array, Task, or instance of the jsui sketch object. The arguments to our new JitterMatrix objects are exactly the same as
would be used as arguments to a jit.matrix object, i.e. an optional name, a planecount, a type, and a list of values for the
dim.

Its important not to confuse the name attribute of a Jitter matrix with the variable name that represents it inside the
JavaScript code. For example, weve created a JitterMatrix object in our code assigned to the variable mymatrix.
Sending the message jit_matrix mymatrix to a jit.pwindow in our Max patch would not, however, display that matrix.
Our mymatrix object has a name property that is generated automatically if not provided using the same convention
used in other Jitter objects (e.g. uxxxxxxxxx). The distinction is similar to that employed by the JavaScript Global
object used to share data with Max patches.

All three of our JitterMatrix objects are created with the same typology. On the fourth line of this part of our code, we take
the JitterMatrix myfbmatrix and set all its values to 255. The setall() method of the JitterMatrix object does this for us,
much as the setall message to a jit.matrix object would. In fact, all of the messages and attributes used by the jit.matrix
object are exposed as methods and properties of the JitterMatrix object within JavaScript. A few examples:

// set all the values in our matrix to 0:


mymatrix.clear();
// set the variable foo to the value of cell (40,40):
var foo = mymatrix.getcell(40,40);
// set cell (30,20) to the values (255,255,0,0):
mymatrix.setcell2d(30,20,255,255,0,0);

The setcell2d() method allows us to set a value of a single cell in a matrix using an array of values where the first two
arguments are assumed to be the position in the matrix. The cell is then set to the values contained in subsequent
arguments. There are also utility functions for one- and three-dimensional matrices (setcell1d() and setcell3d(),
respectively). For a general purpose solution, we can use the plain setcell() function just as we would in a Max message,
e.g. mymatrix.setcell(20, 30, val, 0, 0, 255, 255).

Creating Objects
Continue perusing the global block. Now that weve created some matrices to work with, we have to create some objects to
manipulate them with.

// Jitter objects to use (also declared globally)


var myqtmovie = new JitterObject("jit.qt.movie", 320, 240);
var myrobcross = new JitterObject("jit.robcross");
var mywake = new JitterObject("jit.wake");
var mybrcosa = new JitterObject("jit.brcosa");

These four lines create instances of the JitterObject objects. We need four of them (myqtmovie, myrobcross, mywake, and
mybrcosa) corresponding to the four equivalent objects on the right side of our Max patch (jit.qt.movie, jit.robcross,
jit.wake, and jit.brcosa). These JitterObject objects behave just as the equivalent Jitter objects would in a Max patcher, as
well see a bit later on. The first argument when we instantiate a JitterObject is the class of Jitter object wed like it to load
(e.g. jit.qt.movie will give us a jit.qt.movie object loaded into JavaScript). Further arguments to the object can be passed
just as they would in Max patchers, so that we can tell our new jit.qt.movie JitterObject to have a dim of 320x240 by
supplying those values as arguments.

Just as we would initialize attributes by typing them into the object box following the objects name (e.g. jit.brcosa
@saturation 1.1), we can use our global JavaScript code to initialize attributes of our the JitterObject objects weve created:

myrobcross.thresh = 0.14; // set edge detection threshold


mywake.rfb = 0.455; // set wake feedback for red channel
mywake.gfb = 0.455; // set wake feedback for green channel
mywake.bfb = 0.455; // set wake feedback for blue channel
mybrcosa.brightness = 1.5; // set brightness for feedback stage

Note that the properties of a JitterObject correspond directly to the attributes used by the Jitter object loaded into it, e.g. a
JitterObject loading a jit.brcosa object will have properties for brightness, contrast, and saturation. In our code above, we
initialize the thresh property of the JitterObject myrobcross to 0.14, mirroring the jit.robcross object on the right side of
our patch. In the same way, we initialize attributes for our mywake and mybrcosa objects as well.

JavaScript Functions calling Jitter Object Methods


Look at the code for the read() function. This function is called when our js object receives the read message.

function read(filename) // read a movie


{
if(arguments.length="=0)" {
// no movie specified, so open a dialog
myqtmovie.read();
}
else { // read the movie specified
myqtmovie.read(filename);
}
// initialize feedback matrix to all maximum values
myfbmatrix.setall(255, 255, 255, 255);
}

Our read() function parses the arguments to the read message sent to our js object. If no arguments appear, it will call the
read() method of our myqtmovie object with no arguments. If an argument is specified, our myqtmovie object will be told to
read that argument as a filename.

Click the message box that labeled read on the left side of the patch. Notice that a dialog box pops up, just as if you had
sent a read message into a jit.qt.movie object in a Max patcher. Cancel the dialog or load in a new movie to see what our
algorithm does to it.
JitterObjects in JavaScript behave just like those in Max patchers

If we wanted to, we could have looked at the Array returned by the read() method to ensure that it didnt fail. For right now,
however, well trust that the arguments to the read message sent to our js object are legitimate filenames of QuickTime
movies in the search path.

After we read in our movie (or instruct our myqtmovie object to open a jit.qt.movie Open Document dialog), we once
again intialize our JitterMatrix myfbmatrix to values of all 255.

The Perform Routine


Just as a typical Jitter processing chain might run from jit.qt.movie to output through a series of Jitter objects in response
to a qmetro, our JavaScript Jitter algorithm performs one loop of its processing algorithm (outputting a single matrix) in
response to a bang from an outside source.

Look at the bang() function in our JavaScript code. Notice that, just as in our Max patcher, each JitterObject gets called in
sequence, processing matrices in turn.

function bang()
// perform one iteration of the playback / processing loop
{
// setup

// calculate bleed coefficients for new matrix:


calccoeffs();

// process
// get new matrix from movie ([jit.qt.movie]):
myqtmovie.matrixcalc(mymatrix, mymatrix);

// perform edge detection ([jit.robcross]):


myrobcross.matrixcalc(mymatrix, mymatrix);

// multiply with previous (brightened) output


mymatrix.op("*", myfbmatrix);

// process wake effect (can't process in place) ([jit.wake]):


mywake.matrixcalc(mymatrix, mywakematrix);

// brighten and copy into feedback matrix ([jit.brcosa]):


mybrcosa.matrixcalc(mywakematrix,myfbmatrix);

// output processed matrix into Max


outlet(0, "jit_matrix", mywakematrix.name);
}

The calccoeffs() function called first in the bang() function sets up the properties of our mywake object (more on this below).
Following this is the processing chain of Jitter objects that take a new matrix from our myqtmovie object and transform it.
The matrixcalc() method of a JitterObject is the equivalent to sending a Jitter object in Max a bang (in the case of Jitter
objects which generate matrices) or a jit_matrix message (in Jitter objects which process or display matrices). The
arguments to the matrixcalc() method are the input matrix followed by the output matrix. Our myqtmovie object has a
redundant argument for its input matrix that is ignored; we simply provide the name of a valid JitterMatrix. If we were
working with a Jitter object that needs more than one input or output (e.g. jit.xfade), we would supply our matrixcalc()
method with Arrays of matrices set inside brackets ([, ]).

The op() method of a JitterMatrix object is the equivalent of running the matrix through a jit.op object, with arguments
corresponding to the op attribute and the scalar (val) or matrix to act as the second operand. In a narrative form, therefore,
the following things are happening in the process section of our bang() function:

Our myqtmovie object generates a new matrix from the current frame of the loaded video file, storing it into the
JitterMatrix mymatrix.

Our myrobcross object takes the mymatrix object and performs an edge detection on it, storing the results back into the
same matrix (more about this below).

We then multiply our mymatrix JitterMatrix with the contents of myfbmatrix using the op() method to mymatrix. This
multiplication is done in place as in the previous step.

We then process the mymatrix JitterMatrix through our mywake object, storing the output in a third JitterMatrix, called
mywakematrix.

Finally, we brighten the JitterMatrix mywakematrix, storing the output in myfbmatrix to be used on the next iteration of
the bang() function. In our JavaScript code, therefore, the matrix myfbmatrix is being used exactly as the named matrix bob
was used in our Max patch.

Technical Note: Depending on the class of Jitter object loaded, a JitterObject may be able to use the same matrix for
both its input and output in its matrixcalc() method. This use of in place processing allows you to conserve processing
time and memory copying data into new intermediary matrices. Whether this works depends entirely on the inner
workings of the Jitter object in question; for example, a jit.brcosa object will behave correctly, whereas a jit.wake
object (because it depends on its previous output matrices for performing feedback) will not. By a similar token, the
op() method to a JitterMatrix object will do its processing in place as well.

Our processed matrix (the output of the mywake object stored in the mywakematrix matrix) is then sent out to the patcher
by using an outlet() function:

outlet(0, "jit_matrix", mywakematrix.name);

We use the name property of our JitterMatrix in this call to send the matrixs name (uxxxxxxxxx) to the receiving object in
the Max patch.
Other Functions
Take a look at the calccoeffs() function in our JavaScript code. This function is called internally by the bang() function
every time it runs.

function calccoeffs() // computes the 12 bleed coefficients for the convolution state of
the [jit.wake] object
{
// red channel
mywake.rupbleed*=0.99;
mywake.rupbleed+=Math.random()*0.006;
mywake.rdownbleed*=0.99;
mywake.rdownbleed+=Math.random()*0.006;
mywake.rleftbleed*=0.99;
mywake.rleftbleed+=Math.random()*0.006;
mywake.rrightbleed*=0.99;
mywake.rrightbleed+=Math.random()*0.006;
// green channel
mywake.gupbleed*=0.99;
mywake.gupbleed+=Math.random()*0.006;
mywake.gdownbleed*=0.99;
mywake.gdownbleed+=Math.random()*0.006;
mywake.gleftbleed*=0.99;
mywake.gleftbleed+=Math.random()*0.006;
mywake.grightbleed*=0.99;
mywake.grightbleed+=Math.random()*0.006;

// blue channel
mywake.bupbleed*=0.99;
mywake.bupbleed+=Math.random()*0.006;
mywake.bdownbleed*=0.99;
mywake.bdownbleed+=Math.random()*0.006;
mywake.bleftbleed*=0.99;
mywake.bleftbleed+=Math.random()*0.006;
mywake.brightbleed*=0.99;
mywake.brightbleed+=Math.random()*0.006;
}
calccoeffs.local = 1; // can't call from the patcher

We see that the calccoeffs() function literally duplicates the functionality of the random_bleed patcher on the right side of
our patch. It sets a variety of properties of the mywake JitterObject, corresponding to the various attributes of the jit.wake
object it contains. Notice that we can use these properties as ordinary variables, getting their values as well as setting them.
This allows us to change their values using in place operators, e.g.:

mywake.rupbleed*=0.99; mywake.rupbleed+=Math.random()*0.006;
This code (replicated twelve times for different properties of the mywake object) uses the current value of the rupbleed
property of mywake as a starting point, multiplies it by 0.99, and adds a small random value (between 0 and 0.006) to it.

Summary
You can use JavaScript code within Max to define procedural systems using Jitter matrices and objects. The JitterMatrix
object within js allows you to create, set, and query attributes of Jitter matrices from within JavaScriptthe setall() method
of JitterMatrix, sets all of its cells to a certain value, for example. You can also apply mathematical operations to a
JitterMatrix in place using the op() method, which contains the complete set of mathematical operators used in the jit.op
object. Jitter objects can be loaded as classes into the JitterObject object. Upon instantiation, a JitterObject acquires
properties and methods equivalent to the Jitter objects messages and attributes. The matrixcalc() method of a JitterObject
performs the equivalent of sending the Jitter object a bang or a jit_matrix message, whichever is relevant for that class of
object. This allows you to port complex function graphs of Jitter processes into JavaScript.

In the next two Tutorials, well look at other ways to use JavaScript to expand the possibilities when working with Jitter.

Code Listing
// 45jWakefilter.js
//
// a video playback processing chain demonstrating the use of
// Jitter objects and matrices within [js].
//
// rld, 6.05
//
// inlets and outlets
inlets = 1;
outlets = 1;

// Jitter matrices to work with (declared globally)


var mymatrix = new JitterMatrix(4, "char", 320, 240);
var mywakematrix = new JitterMatrix(4, "char", 320, 240);
var myfbmatrix = new JitterMatrix(4, "char", 320, 240);

// initialize feedback matrix to all maximum values


myfbmatrix.setall(255, 255, 255, 255);

// Jitter objects to use (also declared globally)


var myqtmovie = new JitterObject("jit.qt.movie", 320, 240);
var myrobcross = new JitterObject("jit.robcross");
var mywake = new JitterObject("jit.wake");
var mybrcosa = new JitterObject("jit.brcosa");

// set some initial attributes for our JitterObjects


myrobcross.thresh = 0.14; // set edge detection threshold
mywake.rfb = 0.455; // set wake feedback for red channel
mywake.gfb = 0.455; // set wake feedback for green channel
mywake.bfb = 0.455; // set wake feedback for blue channel
mybrcosa.brightness = 1.5; // set brightness for feedback stage

function read(filename) // read a movie


{
if(arguments.length="=0)" {
// no movie specified, so open a dialog
myqtmovie.read();
}
else { // read the movie specified
myqtmovie.read(filename);
}
// initialize feedback matrix to all maximum values
myfbmatrix.setall(255, 255, 255, 255);
}

function bang()
// perform one iteration of the playback / processing loop
{
// setup

// calculate bleed coefficients for new matrix:


calccoeffs();

// process

// get new matrix from movie ([jit.qt.movie]):


myqtmovie.matrixcalc(mymatrix, mymatrix);

// perform edge detection ([jit.robcross]):


myrobcross.matrixcalc(mymatrix, mymatrix);

// multiply with previous (brightened) output


mymatrix.op("*", myfbmatrix);
// process wake effect (can't process in place) ([jit.wake]):
mywake.matrixcalc(mymatrix, mywakematrix);

// brighten and copy into feedback matrix ([jit.brcosa]):


mybrcosa.matrixcalc(mywakematrix,myfbmatrix);

// output processed matrix into Max


outlet(0, "jit_matrix", mywakematrix.name);
}

function calccoeffs() // computes the 12 bleed coefficients for the convolution state of
the [jit.wake] object
{
// red channel
mywake.rupbleed*=0.99;
mywake.rupbleed+=Math.random()*0.006;
mywake.rdownbleed*=0.99;
mywake.rdownbleed+=Math.random()*0.006;
mywake.rleftbleed*=0.99;
mywake.rleftbleed+=Math.random()*0.006;
mywake.rrightbleed*=0.99;
mywake.rrightbleed+=Math.random()*0.006;
// green channel
mywake.gupbleed*=0.99;
mywake.gupbleed+=Math.random()*0.006;
mywake.gdownbleed*=0.99;
mywake.gdownbleed+=Math.random()*0.006;
mywake.gleftbleed*=0.99;
mywake.gleftbleed+=Math.random()*0.006;
mywake.grightbleed*=0.99;
mywake.grightbleed+=Math.random()*0.006;
// blue channel
mywake.bupbleed*=0.99;
mywake.bupbleed+=Math.random()*0.006;
mywake.bdownbleed*=0.99;
mywake.bdownbleed+=Math.random()*0.006;
mywake.bleftbleed*=0.99;
mywake.bleftbleed+=Math.random()*0.006;
mywake.brightbleed*=0.99;
mywake.brightbleed+=Math.random()*0.006;
}
calccoeffs.local = 1; // can't call from the patcher

See Also
Name Description
jit.brcosa Adjust image brightness/contrast/saturation
jit.matrix The Jitter Matrix!
jit.op Apply binary or unary operators
jit.pwindow Show data in a patcher
jit.qt.movie Play or edit a QuickTime movie
jit.robcross Robert's Cross edge detection
jit.wake Feedback with convolution stage
js Execute Javascript
qmetro Queue-based metronome
random Generate a random number
Manipulating Matrix Data using JavaScript
Tutorial 46: Manipulating Matrix Data using JavaScript
As we saw in the last tutorial, we can use the Max js object to design a pipeline of Jitter objects within procedural JavaScript
code. The JitterObject and JitterMatrix objects within JavaScript allow us to create new Jitter objects and matrices and work
with them more or less as we would within a Max patcher. In many situations, we need to manipulate data stored in a Jitter
matrix in a manner that would be awkward or difficult to do using a Max patcher. This tutorial looks at a variety of solutions
for how to manipulate matrix data within js using methods and properties of the JitterMatrix object, as well as using the
jit.expr object within JavaScript.

This tutorial assumes youve read through the previous Tutorial 45: Introduction to using Jitter within JavaScript. In
addition, this tutorial works with Jitter OpenGL objects as well as jit.expr, so you may want to review Tutorial 30: Drawing
3D Text, Tutorial 31: Rendering Destinations, and Tutorial 39: Spatial Mapping before we begin.

Open the tutorial patch 46jJavaScriptOperators in the Jitter Tutorials folder.


This tutorial patch uses a js object loading a file called 46jParticles.js. The JavaScript code generates a Jitter matrix in
response to a bang that we then send to the jit.gl.render object in the patcher. The file contains a number of functions to
respond to various settings we can send as messages from our patch.

Our patcher containing the JavaScript file.

Click the toggle box above the qmetro object on the left hand side of the patch. Observe the results in the jit.window
named parts.

Our JavaScript code generates a set of points that represent a simple particle system. A particle system is essentially an
algorithm that operates on a (often very large) number of spatial points called particles. These particles have rules that
determine how they move over time in relation to each other or in relation to other actors within the space. At their basic
level, particles contain only their spatial coordinates. Particle systems may also contain other information sand can be used
to simulate a wide variety of natural processes such as running water or smoke. Particle systems are widely used in
computer simulations of our environment, and as such are a staple technology in many computer-generated imagery (CGI)
applications.
A particle system generated as a Jitter matrix.

The Wide World of Particles


The particle system used in our JavaScript simulation works by generating two sets of random points representing the
positions and velocities of the particles and a number of spatial positions in the 3D space that contain gravity. These gravity
points, called attractors, act upon the particles in each frame to gradually pull particles towards them. As we can see in the
jit.window, the points in our particle system gradually collapse towards one or more points of singularity. Alternately, the
attractor points may be such that the particles oscillate between them, caught in a conflicting gravity field that gradually
stabilizes.

With the patcher as the frontmost window, press the spacebar on your computer keyboard or click on the message box
labeled init attached to the js object. Try this a few times to observe the different behaviors of our particle system.
The init message to our js object reboots the particle system. It randomly scatters the particles and generates new attractor
points.

Press and hold the s key on our computer keyboard, or click the toggle box attached to the message box labeled smear
$1. The particles will now leave trails behind them as they move. Release the s key (or uncheck the toggle box) to return to
a normal visualization.

By observing our particle system over time we can view the trajectories of our points as they collapse towards the attractors.
A variety of behaviors from a simple set of rules.

Click in the jit.window. A set of colored red, green, and blue axes will appear around the world. Rotate the world with your
mouse. Try zooming out (by holding down the ALT/Option key and dragging in the window). Restart the particle system
from different vantage points.

A jit.gl.handle object controls our jit.gl.render object, allowing us to see that our particle system inhabits a three-
dimensional world. By rotating the space around to different perspectives we can see how the attractors pull in particles from
all around them.

Under the Hood


Now that weve seen a good part of the functionality of the patch (well return to it later), lets look at the JavaScript code to
see how the algorithm is constructed.

Double-click the js object in our Tutorial patch. A text editor will appear, containing the source code for the js object in the
patch. The code is saved as a file called 46jParticles.js in the same folder as the Tutorial patch.

Our JavaScript code works by manipulating our particles and attractors as Jitter matrices. The particle system is updated by
a generation every time our js object receives a bang. This is accomplished by performing a series of operations on the data
in the Jitter matrices. We can take advantage of the Jitter architecture to perform mathematical operations on entire
matrices at once since weve encoded our system as matrices. This provides a significant advantage in speed, clarity, and
efficiency over working with our data as individual values that must be adjusted one at a time, in many cases (as we would
were we to encode our particles as an Array, for example).

Our JavaScript code actually contains three ways of updating our particle system from generation to generation, each of
which uses different techniques for manipulating the matrix data representing the particles. We can process the
particle system as a single entity using a series of op() methods to the JitterMatrix object, by using a jit.expr object, or
by iterating through the particle system point-by-point (or cell-by-cell). Well look at each in turn once we investigate
the code common to them all.

Look at the global block of code that begins the JavaScript file.
After the initial comment block and inlet/outlet declarations, we can see a number of variables declared and initialized,
including a few JitterObject and JitterMatrix objects. Tif we examine this code in detail, we can see the outline of how well
perform our particle system.

var PARTICLE_COUNT = 1000; // initial number of particle vertices


var ATTRACTOR_COUNT = 3; // initial number of points of gravity

These two global variables (PARTICLE_COUNT and ATTRACTOR_COUNT) are used to decide how many particles and how
many points of attraction wed like to work with in our simulation. These will determine the dim of the Jitter matrices
containing the particle and attractor information.

// create a [jit.noise] object for particle and velocity generation


var noisegen = new JitterObject("jit.noise");
noisegen.dim = PARTICLE_COUNT;
noisegen.planecount = 3;
noisegen.type = "float32";

// create a [jit.noise] object for attractor generation


var attgen = new JitterObject("jit.noise");
attgen.dim = ATTRACTOR_COUNT;
attgen.planecount = 3;
attgen.type = "float32";

Our particle systems are generated randomly by the init() function, which we will investigate presently. The jit.noise objects
created here as JitterObject objects will perform that function for us, by generating one-dimensional matrices of float32
values of a size (dim) corresponding to the number of particles and attractors specified for our system. The matrices
generated by our jit.noise objects have a planecount of 3, corresponding to x, y, and z spatial data.

// create two [jit.expr] objects for the bang_expr() function


// first expression: sum all the planes in the input matrix
var myexpr = new JitterObject("jit.expr");
myexpr.expr = "in[0].p[0]+in[0].p[1]+in[0].p[2]";
// second expression: evaluate a+((b-c)*d/e)
var myexpr2 = new JitterObject("jit.expr");
myexpr2.expr = "in[0]+((in[1]-in[2])*in[3]/in[4])";

One of the ways we will update our particle system is to use two jit.expr objects within our JavaScript code. This part of the
code creates the JitterObject objects and defines the mathematical expression to be used by them (the expr attribute). Well
step through this when we investigate the code that uses them later on.

// create the Jitter matrices we need to store our data


// matrix of x,y,z particle vertices
var particlemat = new JitterMatrix(3, "float32", PARTICLE_COUNT);
// matrix of x,y,z particle velocities
var velomat = new JitterMatrix(3, "float32", PARTICLE_COUNT);
// matrix of x,y,z points of attraction (gravity centers)
var attmat = new JitterMatrix(3, "float32", ATTRACTOR_COUNT);
// matrix for aggregate distances
var distmat = new JitterMatrix(3, "float32", PARTICLE_COUNT);
// temporary matrix for the bang_op() function
var tempmat = new JitterMatrix(3, "float32", PARTICLE_COUNT);
// temporary summing matrix for the bang_op() function
var summat = new JitterMatrix(1, "float32", PARTICLE_COUNT);
// another temporary summing matrix for the bang_op() function
var summat2 = new JitterMatrix(1, "float32", PARTICLE_COUNT);
// a scalar matrix to store the current gravity point
var scalarmat = new JitterMatrix(3, "float32", PARTICLE_COUNT);
// a scalar matrix to store acceleration (expr_op() function only)
var amat = new JitterMatrix(1, "float32", PARTICLE_COUNT);
Our algorithm calls for a number of JitterMatrix objects to store information about our particle system and to be used as
intermediate storage during the processing of each generation of the system. The first three matrices (bound to the variables
particlemat, velomat, and attmat) store the x,y,z positions of our particles, the x,y,z velocities of our particles, and the x,y,z
positions of our attractors, respectively. The other six matrices are used in computing each generation of the system.

var a = 0.001; // acceleration factor


var d = 0.01; // decay factor

These two variables control two important aspects of the behavior of our particle system: the variable a controls how rapidly
the particles accelerate toward an attractor, while the variable d controls how much the particles current velocity decays
with each generation. This second variable influences how easy it is for a particle to change direction and be drawn to other
attractors.

var perform_mode=""op";" // default perform function


var draw_primitive = "points"; // default drawing primitive

These final variables define which of the three techniques well use to process our particle system (the perform_mode) and
the way in which our jit.gl.render object visualizes the particle matrix once our JavaScript code sends it out to the Max
patcher (the draw_primitive).

The Initialization Phase


The first step in creating a particle system is to generate an initial state for the particles and any factors that will act upon
them (in our case, the attractor points). For example, were we to attempt to simulate a waterfall, we would start all our
particles at the top of the space, with a fixed gravity field at the bottom of the space acting upon the particles with each
generation. Our system is slightly less ambitious in terms of real-world accuracythe particles and attractors will simply be
in random positions throughout the 3D scene.

Look at the code for the loadbang() and init() functions in the JavaScript code.

function loadbang() // execute this code when our Max patch opens
{
init(); // initialize our matrices
post("particles initialized.\n");
}

function init()
// initialization routine... call at load, as well as
// when we change the number of particles or attractors
{
// generate a matrix of random particles spread between -1 and 1
noisegen.matrixcalc(particlemat, particlemat);
particlemat.op("*", 2.0);
particlemat.op("-", 1.0);
// generate a matrix of random velocities spread between -1 and 1
noisegen.matrixcalc(velomat, velomat);
velomat.op("*", 2.0);
velomat.op("-", 1.0);
// generate a matrix of random attractors spread between -1 and 1
attgen.matrixcalc(attmat, attmat);
attmat.op("*", 2.0);
attmat.op("-", 1.0);
}

The loadbang() function in a js object runs whenever the Max patcher containing the js file is loaded. This happens after the
object is instantiated with the rest of the patch, and is triggered at the same time as messages triggered by loadbang and
loadmess objects in a Max patch would be. Our loadbang() function simply calls the init() function and then prints a
friendly message to the Max window telling us that all is well.

The loadbang() function of JavaScript code only executes when the patcher containing the js object is opened. This
function does not execute when you change and recompile the JavaScript code.

Our init() function runs when we open our patch as well as whenever we call it from our Max patcher (through the message
box triggered by the spacebar). The init() function also gets called whenever we change the number of attractors and
particles in our simulation. The matrixcalc() method of jit.noise fills the output matrix (the second argument to the method)
with random values between 0 and 1. This is the same as sending a bang to a jit.noise object in a patcher. In our init()
function we fill three matrices with random values in 3 planes. These matrices represent the initial position of our particles
(particlemat,) the initial velocity of our particles (velomat,) and the position of our attractors (attmat). Using the op()
method to our JitterMatrix objects, we then scale these random values to be between 1 and 1. We do this by multiplying
the matrix values by 2 and then subtracting 1.

Now that we have our initial state set up for our particle system, we need to look at how we process the particles with each
generation. This is accomplished through one of three different methods in our JavaScript code determined by the
perform_mode variable.

In the Tutorial patcher, restart the particle system and switch the umenu object labeled Perform routine from op to
expr. The particle system should continue to behave exactly as before. Switch the umenu again to iter. The particle
system will still run, but very slowly (note the frame rate in the jit.fpsgui object attached to the jit.gl.render object in the
lower left part of the patch). Switch the umenu back to op.
The umenu changes the value of the perform_mode variable via the mode() function in our JavaScript code. We will look at
later in this Tutorial, but its important to note that one of the methods used (iter) runs much more slowly than the other
two. This is largely due to the technique used to update the particle system. Well look at why this is when we investigate the
function that performs that task.

Look at the bang() function in the JavaScript code.

function bang() // perform one iteration of our particle system


{
switch(perform_mode) { // choose from the following...
case "op": // use Jitter matrix operators
bang_op();
break;
case "expr": // use [jit.expr] for the bulk of the algorithm
bang_expr();
break;
case "iter": // iterate cell-by-cell through the matrices
bang_iter();
break;
default: // use bang_op() as our default
bang_op();
break;
}
// output our new matrix of particle vertices
// with the current drawing primitive
outlet(0, "jit_matrix", particlemat.name, draw_primitive);
}

Our bang() function uses a JavaScript switch() statement to decide what function to call from within it to do the actual
processing of our particle system. Depending on the perform_mode we choose in the Max patcher, we select from one of
three different functions (bang_op(), bang_expr(), or bang_iter()). Assuming all goes well, we then output the message
jit_matrix, followed by the name of our particlemat matrix (which contains the current coordinates of the simulations
particles), followed by the name of our OpenGL draw_primitive, back into Max.

In the grand tradition of Choose Your Own Adventure and Lets Make a Deal, well now investigate the three different
perform routines represented by the different functions mentioned above.

Door #1: The op() route


Look at the JavaScript source for the bang_op() function.

Our bang_op() function updates our particle system by using, whenever possible, the op() method to the JitterMatrix object
to mathematically alter the contents of matrices all at once. Whenever possible, we do this processing in place to limit the
number of separate Jitter matrices we need to get through the algorithm. We perform the bulk of the processing multiple
times within a for() loop, once for each attractor in our particle system. Once this loop completes, we get an updated version
of the velocity matrix (velomat), which we then add to the particle matrix (particlemat) to define the new positions of the
particles.

In a nutshell, we do the following:

function bang_op() // create our particle matrix using Matrix operators


{
for(var i = 0; i < ATTRACTOR_COUNT; i++)
// do one iteration per gravity point
{

We perform the code until the closing brace (}) once for every attractor, setting the attractor were currently working on to
the variable i.

// create a scalar matrix out of the current attractor:


scalarmat.setall(attmat.getcell(i));

The getcell() method of a JitterMatrix object returns the values of the numbers in the cell specified as its argument. The
setall() method sets all the cells of a matrix to a value (or array of values). These methods work the same as the
corresponding messages to the jit.matrix object in a Max patcher. This line tells our js object to copy the current attractors
coordinates out of the attractor matrix (attmat) and set every single cell in the JitterMatrix scalarmat to those values. The
scalarmat matrix has the same dim as the particlemat matrix (equal to the number of particles in our system). This allows
us to use it as a scalar operand in our op() methods.

// subtract our particle positions from the current attractor


// and store in a temporary matrix (x,y,z):
tempmat.op("-", scalarmat, particlemat);

This code subtracts our particle positions (particlemat) from the position of the attractor were currently working with
(scalarmat). The result is then stored in a temporary matrix with the same dim as two used in the op() function. This matrix
represents the distances from each particle to the current attractor.

// square to create a cartesian distance matrix (x*x, y*y, z*z):


distmat.op("*", tempmat, tempmat);

This code multiplies the tempmat matrix by itself, as a simple way of squaring it. The result is then stored in the distmat
matrix.

// sum the planes of the distance matrix (x*x+y*y+z*z)


summat.planemap = 0;
summat.frommatrix(distmat);
summat2.planemap = 1;
summat2.frommatrix(distmat);
summat.op("+", summat, summat2);
summat2.planemap = 2;
summat2.frommatrix(distmat);
summat.op("+", summat, summat2);

In this block of code, we take the separate planes of the distmat matrix and add them together into a single-plane matrix
called summat. In order to do this, we use the planemap property of JitterMatrix to specify which plane of the source matrix
to use when copying from using the frommatrix() method. To sum everything we need a second temporary matrix
(summat2) to help with the operation. First we copy plane 0 of distmat (the squared x distances) into z distances) into
summat2. We then add summat and summat2 again, keeping in mind that summat at this point already contains the sum
of the first two planes of distmat. The result of this second sum is stored back into summat, which now contains the sum of
all three planes of distmat.
// scale our distances by the acceleration value:
tempmat.op("*", a);
// divide our distances by the sum of the distances
// to derive gravity for this frame:
tempmat.op("/", summat);
// add to the current velocity bearings to get the
// amount of motion for this frame:
velomat.op("+", tempmat);
}

This is the last block of code in our per-attractor loop. We multiply the tempmat matrix (which contains the distances of our
particles from the current attractor) by the value stored in the variable a, representing acceleration. We then divide that
result by the summat matrix (the sum of the squared distances), and add those results to the current velocities of each
particle as stored in the velomat matrix. The result of the addition is stored in velomat.

This entire process is repeated again for each attractor. As a result, the velomat matrix is added to each time based on how
far our particles are from each attractor. By the time the loop finishes (when i reaches the last attractor index), velomat
contains a matrix of velocities corresponding to the aggregate pull of all our attractors on all our particles.

// offset our current positions by the amount of motion:


particlemat.op("+", velomat);
// reduce our velocities by the decay factor for the next frame:
velomat.op("*", d);
}

Finally, we add these velocities to our matrix of particles (particlemat + velomat). Our particle matrix is now updated to a
new set of particle positions. We then decay the velocity matrix by the amount stored in the variable d, so that the simulation
retains a remnant of this generations velocity for the next generation of the particle system.

The use of a cascading series of op() methods to perform our algorithm on entire matrices gives us a big advantage in terms
for speed, as Jitter can perform a simple mathematical operation on a large set of data very quickly. However, there are a
few points (particularly in the generation of the summing matrix summat) where the code may have seemed more awkward
than necessary. We can use jit.expr to define a more complex mathematical expression to perform much of this work in a
single operation.

Door #2: The expr() route


Back in the global block of our JavaScript file, revisit the code that instantiates the jit.expr objects.

// create two [jit.expr] objects for the bang_expr() function

// first expression: sum all the planes in the input matrix


var myexpr = new JitterObject("jit.expr");
myexpr.expr = "in[0].p[0]+in[0].p[1]+in[0].p[2]";
// second expression: evaluate a+((b-c)*d/e)
var myexpr2 = new JitterObject("jit.expr");
myexpr2.expr = "in[0]+((in[1]-in[2])*in[3]/in[4])";

At the beginning of our JavaScript code we created two JitterObject objects (myexpr and myexpr2) that instantiated jit.expr
objects. The expression for the first object takes a single matrix (in[0]) and sums its planes (the .p[n] notation refers to the
data stored in plane n of that matrix). The second expression takes five matrices (in[0] in[4]) and adds the first matrix (A)
to the result of the second subtracted from the third (B-C) multiplied by a fourth (D) and divided by a fifth (E). Our myexpr2
JitterObject therefore evaluates the expression:

A+((B-C)*D/E)

Look at the code for the bang_expr() function. Compare it to what weve used in the bang_op() function.

The basic outline of our bang_expr() function is equivalent to the bang_op() function, i.e. we iterate through a loop based on
the number of attractors in our simulation, eventually ending up with an aggregate velocity matrix (velomat) that we than
use to offset our particle matrix (particlemat). The key difference lies in where we insert the calls to jit.expr:
function bang_expr() // create our particle matrix using [jit.expr]
{
// create a scalar matrix out of our acceleration value:
amat.setall(a);

The above line fills every cell in the amat matrix with the value of the variable a (the acceleration factor). This allows us to
use it as an operand in one of the jit.expr expressions later on.

for(var i = 0; i < ATTRACTOR_COUNT; i++)


// do one iteration per gravity point
{
// create a scalar matrix out of the current attractor:
scalarmat.setall(attmat.getcell(i));
// subtract our particle positions from the current attractor
// and store in a temporary matrix (x,y,z):
tempmat.op("-", scalarmat, particlemat);
// square to create a cartesian distance matrix (x*x, y*y, z*z):
distmat.op("*", tempmat, tempmat);

This is all the same as in bang_op(). We derive a squared distance matrix based on the difference between the current
attractor and our particle positions.

// sum the planes of the distance matrix (x*x+y*y+z*z) :


// "in[0].p[0]+in[0].p[1]+in[0].p[2]" :
myexpr.matrixcalc(distmat, summat);

Instead of summing the distmat matrix plane-by-plane using op() and frommatrix() methods, we simply evaluate our first
mathematical expression using distmat as a 3-plane input matrix and summat as a 1-plane output matrix.

// derive amount of motion for this frame :


// "in[0]+((in[1]-in[2])*in[3]/in[4])" :
myexpr2.matrixcalc([velomat,scalarmat,particlemat,amat,summat],velomat);

Similarly, at the end of our attractor loop we can derive the velocity matrix velomat in one compound expression based on
the previous velocity matrix (velomat), the scalar matrix containing the current attractor point (scalarmat), the current
particle positions (particlemat), the scalar matrix containing the acceleration (amat), and the matrix containing the distance
sums (summat). This is much simpler (and a cleaner read) than using a whole sequence of op() functions working with
intermediary matrices. Note that we use brackets ([ and ]) to establish an array of input matrices in the matrixcalc() method
to the myexpr2 object.

// offset our current positions by the amount of motion:


particlemat.op("+", velomat);
// reduce our velocities by the decay factor for the next frame:
velomat.op("*", d);
}

This is the same as in bang_op(). We generate the new particle positions and decay the new velocities for use as initial
velocities in the next generation of the system.

Door #3: Cell-by-cell


Look at the code for the bang_iter() function.

The bang_iter() function works in a different way from the other two perform routines were using in our JavaScript code.
Rather than working on the matrices as single entities, we work on everything on a cell-by-cell basis, iterating through not
only the matrix of attractor positions (attmat), but also through the matrices of particles and velocities. We do this through a
pair of nested for() loops, temporarily storing each cell value in different Array objects. We use the getcell() and setcell1d()
methods to the JitterMatrix object to retrieve and store values from these Arrays.
function bang_iter() // create our particle matrix cell-by-cell
{
var p_array = new Array(3); // array for a single particle
var v_array = new Array(3); // array for a single velocity
var a_array = new Array(3); // array for a single attractor

for(var j = 0; j < PARTICLE_COUNT; j++)


// do one iteration per particle
{
// fill an array with the current particle:
p_array = particlemat.getcell(j);
// fill an array with the current particle's velocity:
v_array = velomat.getcell(j);

for(var i = 0; i < ATTRACTOR_COUNT; i++)


// do one iteration per gravity point
{
// fill an array with the current attractor:
a_array = attmat.getcell(i);

// find the distance from this particle to the


// current attractor:
var distsum = (a_array[0]-p_array[0])*(a_array[0]-p_array[0]);
distsum+= (a_array[1]-p_array[1])*(a_array[1]-p_array[1]);
distsum+= (a_array[2]-p_array[2])*(a_array[2]-p_array[2]);

// derive the amount of motion for this frame:


v_array[0]+= (a_array[0]-p_array[0])*a/distsum; // x
v_array[1]+= (a_array[1]-p_array[1])*a/distsum; // y
v_array[2]+= (a_array[2]-p_array[2])*a/distsum; // z
}

// offset our current positions by the amount of motion


p_array[0]+=v_array[0]; // x
p_array[1]+=v_array[1]; // y
p_array[2]+=v_array[2]; // z

// reduce our velocities by the decay factor for the next frame:
v_array[0]*=d; // x
v_array[1]*=d; // y
v_array[2]*=d; // z

// set the position for this particle in the Jitter matrix:


particlemat.setcell1d(j, p_array[0],p_array[1],p_array[2]);
// set the velocity for this particle in the Jitter matrix:
velomat.setcell1d(j, v_array[0],v_array[1],v_array[2]);
}
}

Note that by updating our particle system bit-by-bit (and using intermediary Array objects to store data for each cell) were
essentially replicating the same operation, as many times as there are particles in our system! While this may not be
noticeably inefficient with a small number of particles, once you begin to work with thousands of points it will become
noticeably slower.

Other functions
Back in the Max patcher, change the number box objects attached to the message boxes labeled particles $1, attractors
$1, accel $1, and decay $1. Try setting the number of particles to very large and very small numbers. Try to work out how
the accel and decay attributes alter the responsiveness of the system. Look at the code for these functions in the JavaScript
file.

The bulk of these functions simply change variables, sometimes scaling them first (e.g. accel() and decay() simply change the
values of a and d, respectively). Similarly, the mode() function changes the value of the perform_mode variable to a string
that we use to decide the perform routine:
function mode(v) // change perform mode
{
perform_mode = v;
}

The particles() and attractors() functions, however, need to not only change the value of a variable (PARTICLE_COUNT and
ATTRACTOR_COUNT, respectively), but they need to change the dim of the matrices that depend on those values as well as
reboot the particle simulation (by calling the init() function).

function particles(v) // change the number of particles we're working with


{
PARTICLE_COUNT = v;

// resize matrices
noisegen.dim = PARTICLE_COUNT;
particlemat.dim = PARTICLE_COUNT;
velomat.dim = PARTICLE_COUNT;
distmat.dim = PARTICLE_COUNT;
attmat.dim = PARTICLE_COUNT;
tempmat.dim = PARTICLE_COUNT;
summat.dim = PARTICLE_COUNT;
summat2.dim = PARTICLE_COUNT;
scalarmat.dim = PARTICLE_COUNT;
amat.dim = PARTICLE_COUNT;

init(); // re-initialize particle system


}

function attractors(v)
// change the number of gravity points we're working with
{
ATTRACTOR_COUNT = v;

// resize attractor matrix


attgen.dim = ATTRACTOR_COUNT;

init(); // re-initialize particle system


}

In the Max patcher, change the umenu object labeled Drawing primitive. Try different settings and notice how it changes
the way the particle system is drawn. The primitive() function in our JavaScript code changes the value of the variable
draw_primitive.

Our particle system is visualized by sending the matrix of particle positions (referred to as particlemat in our JavaScript
code) to the jit.gl.render object. The matrix contains 3 planes of float32 data, which jit.gl.render interprets as x,y,z vertices
in a geometry. The drawing primitive, which is a symbol appended to the jit_matrix uxxxxxxxxx message sent from the js
object to the jit.gl.render object, defines the way in which our OpenGL drawing context visualizes the data.
For more information on the specifics of these drawing primitives and the OpenGL matrix format, consult Appendix B: The
OpenGL Matrix Format or the OpenGL Redbook.
Different ways of visualizing our particles using different drawing primitives.

Look at the JavaScript code for the smear() function. This is the function that allows us to leave trails when we hold down
the s key on our keyboard (which triggers the toggle box attached to the smear $1 message box).

function smear(v) // turn on drawing smear by zeroing the alpha on the renderer's erase
color
{
if(v) {
// smear on (alpha="0):"
outlet(0, "erase_color", 1., 1., 1., 0.);
}
else {
// smear off (alpha="0.1):"
outlet(0, "erase_color", 1., 1., 1., 0.1);
}
}

Sending a smear message to our js object causes our JavaScript code to send an erase_color message to our jit.gl.render
object. If the argument to smear is 1, we lower the alpha of the erase_color to 0. This has the result of the drawing context
doing nothing in response to the erase message triggered by the qmetro in our patch. A smear value of 1 sets the
jit.gl.render objects erase_color attribute back to an alpha of 0.1, which makes the renderer erase 10% of the image in
response to the erase message. This causes a small amount of trailing which aids in the visualization of the particle
movement.

Play around with the patch some more, looking at the different ways we can generate and visualize our particles. A wide
variety of interesting systems can be created simply by passing unadorned x,y,z values to the jit.gl.render object as 3-plane
matrices.

Summary
JavaScript can be a powerful language to use when designing algorithms that manipulate matrix data in Jitter. The ability to
perform mathematical operations directly on matrices using a variety of techniques (op() methods, jit.expr objects, and cell-
by-cell iteration) within procedural code lets you take advantage of Jitter as a tool to process large sets of data at once.

In the next tutorial, well look at ways to trigger callback functions in JavaScript based on the actions of JitterObject objects
themselves.

Code Listing

// 46jParticles.js
//
// a 3-D particle generator with simple gravity simulation
// demonstrating different techniques for mathematical
// matrix manipulation using Jitter objects in [js].
//
// rld, 7.05
//

inlets = 1;
outlets = 1;

var PARTICLE_COUNT = 1000; // initial number of particle vertices


var ATTRACTOR_COUNT = 3; // initial number of points of gravity

// create a [jit.noise] object for particle and velocity generation


var noisegen = new JitterObject("jit.noise");
noisegen.dim = PARTICLE_COUNT;
noisegen.planecount = 3;
noisegen.type = "float32";

// create a [jit.noise] object for attractor generation


var attgen = new JitterObject("jit.noise");
attgen.dim = ATTRACTOR_COUNT;
attgen.planecount = 3;
attgen.type = "float32";

// create two [jit.expr] objects for the bang_expr() function

// first expression: sum all the planes in the input matrix


var myexpr = new JitterObject("jit.expr");
myexpr.expr = "in[0].p[0]+in[0].p[1]+in[0].p[2]";
// second expression: evaluate a+((b-c)*d/e)
var myexpr2 = new JitterObject("jit.expr");
myexpr2.expr = "in[0]+((in[1]-in[2])*in[3]/in[4])";

// create the Jitter matrices we need to store our data

// matrix of x,y,z particle vertices


var particlemat = new JitterMatrix(3, "float32", PARTICLE_COUNT);
// matrix of x,y,z particle velocities
var velomat = new JitterMatrix(3, "float32", PARTICLE_COUNT);
// matrix of x,y,z points of attraction (gravity centers)
var attmat = new JitterMatrix(3, "float32", ATTRACTOR_COUNT);
// matrix for aggregate distances
var distmat = new JitterMatrix(3, "float32", PARTICLE_COUNT);
// temporary matrix for the bang_op() function
var tempmat = new JitterMatrix(3, "float32", PARTICLE_COUNT);
// temporary summing matrix for the bang_op() function
var summat = new JitterMatrix(1, "float32", PARTICLE_COUNT);
// another temporary summing matrix for the bang_op() function
var summat2 = new JitterMatrix(1, "float32", PARTICLE_COUNT);
// a scalar matrix to store the current gravity point
var scalarmat = new JitterMatrix(3, "float32", PARTICLE_COUNT);
// a scalar matrix to store acceleration (expr_op() function only)
var amat = new JitterMatrix(1, "float32", PARTICLE_COUNT);

var a = 0.001; // acceleration factor


var d = 0.01; // decay factor

var perform_mode=""op";" // default perform function


var draw_primitive = "points"; // default drawing primitive

function loadbang() // execute this code when our Max patch opens
{
init(); // initialize our matrices
post("particles initialized.\n");
}

function init()
// initialization routine... call at load, as well as
// when we change the number of particles or attractors
{
// generate a matrix of random particles spread between -1 and 1
noisegen.matrixcalc(particlemat, particlemat);
particlemat.op("*", 2.0);
particlemat.op("-", 1.0);
// generate a matrix of random velocities spread between -1 and 1
noisegen.matrixcalc(velomat, velomat);
velomat.op("*", 2.0);
velomat.op("-", 1.0);
// generate a matrix of random attractors spread between -1 and 1
attgen.matrixcalc(attmat, attmat);
attmat.op("*", 2.0);
attmat.op("-", 1.0);
}

function bang() // perform one iteration of our particle system


{
switch(perform_mode) { // choose from the following...
case "op": // use Jitter matrix operators
bang_op();
break;
case "expr": // use [jit.expr] for the bulk of the algorithm
bang_expr();
break;
case "iter": // iterate cell-by-cell through the matrices
bang_iter();
break;
default: // use bang_op() as our default
bang_op();
break;
}

// output our new matrix of particle vertices


// with the current drawing primitive
outlet(0, "jit_matrix", particlemat.name, draw_primitive);

function bang_op() // create our particle matrix using Matrix operators


{
for(var i = 0; i < ATTRACTOR_COUNT; i++)
// do one iteration per gravity point
{
// create a scalar matrix out of the current attractor:
scalarmat.setall(attmat.getcell(i));

// subtract our particle positions from the current attractor


// and store in a temporary matrix (x,y,z):
tempmat.op("-", scalarmat, particlemat);

// square to create a cartesian distance matrix (x*x, y*y, z*z):


distmat.op("*", tempmat, tempmat);

// sum the planes of the distance matrix (x*x+y*y+z*z)


summat.planemap = 0;
summat.frommatrix(distmat);
summat2.planemap = 1;
summat.frommatrix(distmat);
summat.op("+", summat, summat2);
summat2.planemap = 2;
summat2.frommatrix(distmat);
summat.op("+", summat, summat2);

// scale our distances by the acceleration value:


tempmat.op("*", a);
// divide our distances by the sum of the distances
// to derive gravity for this frame:
tempmat.op("/", summat);
// add to the current velocity bearings to get the
// amount of motion for this frame:
velomat.op("+", tempmat);
}

// offset our current positions by the amount of motion:


particlemat.op("+", velomat);
// reduce our velocities by the decay factor for the next frame:
velomat.op("*", d);
}

function bang_expr() // create our particle matrix using [jit.expr]


{
// create a scalar matrix out of our acceleration value:
amat.setall(a);

for(var i = 0; i < ATTRACTOR_COUNT; i++)


// do one iteration per gravity point
{
// create a scalar matrix out of the current attractor:
scalarmat.setall(attmat.getcell(i));
// subtract our particle positions from the current attractor
// and store in a temporary matrix (x,y,z):
tempmat.op("-", scalarmat, particlemat);
// square to create a cartesian distance matrix (x*x, y*y, z*z):
distmat.op("*", tempmat, tempmat);

// sum the planes of the distance matrix (x*x+y*y+z*z) :


// "in[0].p[0]+in[0].p[1]+in[0].p[2]" :
myexpr.matrixcalc(distmat, summat);

// derive amount of motion for this frame :


// "in[0]+((in[1]-in[2])*in[3]/in[4])" :
myexpr2.matrixcalc([velomat,scalarmat,particlemat,amat,summat],
velomat);

// offset our current positions by the amount of motion:


particlemat.op("+", velomat);
// reduce our velocities by the decay factor for the next frame:
velomat.op("*", d);
}

function bang_iter() // create our particle matrix cell-by-cell


{
var p_array = new Array(3); // array for a single particle
var v_array = new Array(3); // array for a single velocity
var a_array = new Array(3); // array for a single attractor

for(var j = 0; j < PARTICLE_COUNT; j++)


// do one iteration per particle
{
// fill an array with the current particle:
p_array = particlemat.getcell(j);
// fill an array with the current particle's velocity:
v_array = velomat.getcell(j);

for(var i = 0; i < ATTRACTOR_COUNT; i++)


// do one iteration per gravity point
{
// fill an array with the current attractor:
a_array = attmat.getcell(i);

// find the distance from this particle to the


// current attractor:
var distsum = (a_array[0]-p_array[0])*(a_array[0]-p_array[0]);
distsum+= (a_array[1]-p_array[1])*(a_array[1]-p_array[1]);
distsum+= (a_array[2]-p_array[2])*(a_array[2]-p_array[2]);

// derive the amount of motion for this frame:


v_array[0]+= (a_array[0]-p_array[0])*a/distsum; // x
v_array[1]+= (a_array[1]-p_array[1])*a/distsum; // y
v_array[2]+= (a_array[2]-p_array[2])*a/distsum; // z
}

// offset our current positions by the amount of motion


p_array[0]+=v_array[0]; // x
p_array[1]+=v_array[1]; // y
p_array[2]+=v_array[2]; // z

// reduce our velocities by the decay factor for the next frame:
v_array[0]*=d; // x
v_array[1]*=d; // y
v_array[2]*=d; // z

// set the position for this particle in the Jitter matrix:


particlemat.setcell1d(j, p_array[0],p_array[1],p_array[2]);
// set the velocity for this particle in the Jitter matrix:
velomat.setcell1d(j, v_array[0],v_array[1],v_array[2]);
}
}

function particles(v) // change the number of particles we're working with


{
PARTICLE_COUNT = v;

// resize matrices
noisegen.dim = PARTICLE_COUNT;
particlemat.dim = PARTICLE_COUNT;
velomat.dim = PARTICLE_COUNT;
distmat.dim = PARTICLE_COUNT;
attmat.dim = PARTICLE_COUNT;
tempmat.dim = PARTICLE_COUNT;
summat.dim = PARTICLE_COUNT;
summat2.dim = PARTICLE_COUNT;
scalarmat.dim = PARTICLE_COUNT;
amat.dim = PARTICLE_COUNT;
init(); // re-initialize particle system
}

function attractors(v)
// change the number of gravity points we're working with
{
ATTRACTOR_COUNT = v;

// resize attractor matrix


attgen.dim = ATTRACTOR_COUNT;

init(); // re-initialize particle system


}

function accel(v) // set acceleration


{
a = v*0.001;
}

function decay(v) // set decay


{
d = v*0.001;
}

function mode(v) // change perform mode


{
perform_mode = v;
}

function primitive(v) // change OpenGL drawing primitive


{
draw_primitive = v;
}

function smear(v) // turn on drawing smear by zeroing the alpha on the renderer's erase
color
{
if(v) {
// smear on (alpha="0):"
outlet(0, "erase_color", 1., 1., 1., 0.);
}
else {
// smear off (alpha="0.1):"
outlet(0, "erase_color", 1., 1., 1., 0.1);
}
}

function bang() // perform one iteration of our particle system


{
switch(perform_mode) { // choose from the following...
case "op": // use Jitter matrix operators
bang_op();
break;
case "expr": // use [jit.expr] for the bulk of the algorithm
bang_expr();
break;
case "iter": // iterate cell-by-cell through the matrices
bang_iter();
break;
default: // use bang_op() as our default
bang_op();
break;
}
// output our new matrix of particle vertices with the current drawing primitive
outlet(0, "jit_matrix", particlemat.name, draw_primitive);

function bang_op() // create our particle matrix using Matrix operators


{
for(var i = 0; i < ATTRACTOR_COUNT; i++) // do one iteration per gravity point
{
scalarmat.setall(attmat.getcell(i)); // create a scalar matrix out of the current
attractor

tempmat.op("-", scalarmat, particlemat); // subtract our particle positions from the


current attractor and store in a temporary matrix (x,y,z)

distmat.op("*", tempmat, tempmat); // square to create our cartesian distance matrix


(x*x, y*y, z*z)

// sum the planes of the distance matrix (x*x+y*y+z*z)


summat.planemap = 0;
summat.frommatrix(distmat);
summat2.planemap = 1;
summat.frommatrix(distmat);
summat.op("+", summat, summat2);
summat2.planemap = 2;
summat2.frommatrix(distmat);
summat.op("+", summat, summat2);

tempmat.op("*", a); // scale our distances by the acceleration value


tempmat.op("/", summat); // divide our distances by the sum of the distances to derive
gravity for this frame
velomat.op("+", tempmat); // add to the current velocity bearings to get the amount of
motion for this frame
}

particlemat.op("+", velomat); // offset our current positions by the amount of motion


velomat.op("*", d); // reduce our velocities by the decay factor for the next frame
}

function bang_expr() // create our particle matrix using [jit.expr]


{
amat.setall(a); // create a scalar matrix out of our acceleration value

for(var i = 0; i < ATTRACTOR_COUNT; i++) // do one iteration per gravity point


{
scalarmat.setall(attmat.getcell(i)); // create a scalar matrix out of the current
attractor

tempmat.op("-", scalarmat, particlemat); // subtract our particle positions from the


current attractor and store in a temporary matrix (x,y,z)

distmat.op("*", tempmat, tempmat); // square to create our cartesian distance matrix


(x*x, y*y, z*z)

myexpr.matrixcalc(distmat, summat); // sum the planes of the distance matrix


(x*x+y*y+z*z) : "in[0].p[0]+in[0].p[1]+in[0].p[2]"

myexpr2.matrixcalc([velomat,scalarmat,particlemat,amat,summat], velomat); // derive


amount of motion for this frame : "in[0]+((in[1]-in[2])*in[3]/in[4])"
}

particlemat.op("+", velomat); // offset our current positions by the amount of motion


velomat.op("*", d); // reduce our velocities by the decay factor for the next frame
}

function bang_iter() // create our particle matrix cell-by-cell


{
var p_array = new Array(3); // create an array for a single particle (x,y,z)
var v_array = new Array(3); // create an array for a single velocity (x,y,z)
var a_array = new Array(3); // create an array for a single attractor (x,y,z)

for(var j = 0; j < PARTICLE_COUNT; j++) // do one iteration per particle


{
p_array = particlemat.getcell(j); // fill an array with the current particle
v_array = velomat.getcell(j); // fill an array with the current particle's velocity

for(var i = 0; i < ATTRACTOR_COUNT; i++) // do one iteration per gravity point


{
a_array = attmat.getcell(i); // fill an array with the current attractor

// find the distance from this particle to the current attractor


var distsum = (a_array[0]-p_array[0])*(a_array[0]-p_array[0]);
distsum+= (a_array[1]-p_array[1])*(a_array[1]-p_array[1]);
distsum+= (a_array[2]-p_array[2])*(a_array[2]-p_array[2]);

v_array[0]+= (a_array[0]-p_array[0])*a/distsum; // derive the amount of motion for


this frame (x)
v_array[1]+= (a_array[1]-p_array[1])*a/distsum; // derive the amount of motion for
this frame (y)
v_array[2]+= (a_array[2]-p_array[2])*a/distsum; // derive the amount of motion for
this frame (z)
}

p_array[0]+=v_array[0]; // offset our current positions by the amount of motion (x)


p_array[1]+=v_array[1]; // offset our current positions by the amount of motion (y)
p_array[2]+=v_array[2]; // offset our current positions by the amount of motion (z)

v_array[0]*=d; // reduce our velocities by the decay factor for the next frame (x)
v_array[1]*=d; // reduce our velocities by the decay factor for the next frame (y)
v_array[2]*=d; // reduce our velocities by the decay factor for the next frame (z)

particlemat.setcell1d(j, p_array[0],p_array[1],p_array[2]); // set the position for this


particle in the Jitter matrix
velomat.setcell1d(j, v_array[0],v_array[1],v_array[2]); // set the velocity for this
particle in the Jitter matrix
}
}

function particles(v) // change the number of particles we're working with


{
PARTICLE_COUNT = v;

// resize matrices
noisegen.dim = PARTICLE_COUNT;
particlemat.dim = PARTICLE_COUNT;
velomat.dim = PARTICLE_COUNT;
distmat.dim = PARTICLE_COUNT;
attmat.dim = PARTICLE_COUNT;
tempmat.dim = PARTICLE_COUNT;
summat.dim = PARTICLE_COUNT;
summat2.dim = PARTICLE_COUNT;
scalarmat.dim = PARTICLE_COUNT;
amat.dim = PARTICLE_COUNT;

init(); // re-initialize particle system


}
function attractors(v) // change the number of gravity points we're working with
{
ATTRACTOR_COUNT = v;

// resize attractor matrix


attgen.dim = ATTRACTOR_COUNT;

init(); // re-initialize particle system


}

function accel(v) // set acceleration


{
a = v*0.001;
}

function decay(v) // set decay


{
d = v*0.001;
}

function mode(v) // change perform mode


{
perform_mode = v;
}

function primitive(v) // change OpenGL drawing primitive


{
draw_primitive = v;
}
function smear(v) // turn on drawing smear by zeroing the alpha on the renderer's erase
color
{
if(v) {
outlet(0, "erase_color", 1., 1., 1., 0.); // smear on (alpha="0)"
}
else {
outlet(0, "erase_color", 1., 1., 1., 0.1); // smear off (alpha="0.1)"
}
}

See Also
Name Description
jit.expr Evaluate an expression to fill a matrix
jit.gl.handle Use mouse movement to control position/rotation
jit.gl.render Render Jitter OpenGL objects
jit.window Display data in a window
js Execute Javascript
qmetro Queue-based metronome
Using Jitter Object Callbacks in JavaScript
Tutorial 47: Using Jitter Object Callbacks in JavaScript
In the last two tutorials, weve looked at some of the possibilities and advantages of using Jitter objects and matrices within
JavaScript code. In this tutorial well encapsulate an entire Jitter OpenGL patch inside of JavaScript, using many of the
techniques weve already seen. Most importantly, however, well learn how to listen to the output of Jitter objects that have
been encapsulated in JavaScript in order to design functions that respond interactively to these objects.

A number of Jitter objects (such as jit.qt.movie, jit.pwindow, and jit.window) output messages from their status (right-
hand) outlets in response to processes initiated by the user in a Max patcher. Fore example, when you read a movie file into
jit.qt.movie, the object outputs the message read followed by the movies filename and a status number out its status outlet.
Similarly, the jit.pwindow and jit.window objects can respond to mouse events in their windows by sending messages out
their status outlet. Because Jitter objects instantiated within JavaScript have no inlets and outlets per se, we need to
explicitly create an object (called a JitterListener) to catch those messages and call a function (called a callback function) in
response to them.

This Tutorial assumes youve looked at the earlier JavaScript tutorials, as well as the first OpenGL tutorial Tutorial 30:
Drawing 3D Text.

Open the tutorial patch 47jJitterListener in the Jitter Tutorials folder.


The first thing we notice about this tutorial patch is that there is very little in it, in terms of Max objects. Virtually all the
work done in the patcher is accomplished inside the js object in the patch.

Our Tutorial patcher: not much to look at.

Click on the toggle box labeled Display. The qmetro object will begin to send bang messages into the js object, and the
jit.window object should fill with a number of shapes (one large sphere and a few dozen small spheres) on a black
background.

Our js object contains a complete set of Jitter objects performing an OpenGL rendering (including a jit.window object).
Move your mouse over the jit.window. The large sphere will glue to your mouse, following you along in the window. As
the large sphere touches the smaller spheres, it will push them along as if they were solid objects colliding. Try to get a feel
for moving the smaller spheres around with the larger one.

Our js file not only draws our OpenGL scene, but also handles interactive events from the mouse. This is done through a
listening and callback mechanism (called a JitterListener) that well learn about in the JavaScript code.
Pushing the spheres around.

Creating OpenGL objects in JavaScript


Double-click the js object in our Tutorial patch. A text editor will appear that contains the source code for the js object in
the patch. The code is saved as a file called 47jMarbles.js in the same folder as the Tutorial patch. Look at the global code
block at the top of the file.

Our JavaScript code creates all the JitterObject objects we need to render our scene: a jit.window object to display the
drawing context, a jit.gl.render object to perform the rendering, and a number of jit.gl.gridshape objects to draw and
animate the spheres in the scene. These objects are instantiated in the global block of code at the beginning of the JavaScript
file.

var OBJECT_COUNT = 32; // number of little spheres

This line declares a variable (OBJECT_COUNT) that determines the number of smaller spheres in our scene.

// create a [jit.window] object for our display


// (this is the object we'll "listen" to):
var mywindow = new JitterObject("jit.window","ListenWindow");
// turn off depth testing... we're using blending instead:
mywindow.depthbuffer = 0;
// turn ON idlemousing... we want to listen for it:
mywindow.idlemouse = 1;

Next, we create a jit.window object to display everything. Well refer to it in our JavaScript code by the variable mywindow.
Just as in a Max patch, the jit.window needs a name (ListenWindow) that must match the OpenGL drawing context were
using. Weve turned off the depthbuffer and turned on the idlemouse attribute, which allows the jit.window object to track
mouse events in the window regardless of whether weve clicked our mouse down or not.

// create a [jit.gl.render] object for drawing into our window:


var myrender = new JitterObject("jit.gl.render","ListenWindow");
// use a 2-dimensional projection:
myrender.ortho = 2;
// set background to black with full erase opacity (no trails):
myrender.erase_color = [0,0,0,1];

Our jit.gl.render object (assigned to the variable myrender) defines a drawing context called ListenWindow. The
jit.window object (above) and the jit.gl.gridshape objects (below) share this name. Weve decided to use an orthographic
projection (by setting the ortho attribute to 2). This means that the z axis of our drawing context is ignored in terms of
sizing objects based on their distance from the virtual camera. This essentially creates a 2-dimensional rendering of our
scene. Weve set the background to black (with a full erase between successive drawing) by setting our erase_color to 0 0 0
1.

// create a [jit.gl.gridshape] object for use to control with the mouse


var mywidget = new JitterObject("jit.gl.gridshape","ListenWindow");
mywidget.shape = "sphere";
mywidget.lighting_enable = 1;
mywidget.smooth_shading = 1;
mywidget.scale = [0.1,0.1,0.1];
mywidget.color = [1,1,1,0.5] ;
mywidget.blend_enable = 1;
mywidget.position = [0,0]; // no z necessary in orthographic projection

The first jit.gl.gridshape object we create (assigned to the variable mywidget) corresponds to the large sphere moved by our
mouse in the jit.window. After creating it, we set all the relevant attributes we want the sphere to have, just as we would in a
Max patcher. Note that in setting the position attribute we only use two arguments (x and y). In an orthographic projection
the z axis is irrelevant to how the shapes are drawn.

// create an array of [jit.gl.gridshape] objects


// randomly arrayed across the window
var mysphere = new Array(OBJECT_COUNT);

Rather than naming our smaller spheres individually, were treating them as an Array (called mysphere). Each element in
this array will then be a separate jit.gl.gridshape object that we can access by array notation (e.g. mysphere[5] will be the
sixth sphere, counting up from 0).

// initialize our little spheres with random colors and positions (x,y)
for(var i="0;i<OBJECT_COUNT;i++)" {
mysphere[i] = new JitterObject("jit.gl.gridshape","ListenWindow");
mysphere[i].shape = "sphere";
mysphere[i].lighting_enable = 1;
mysphere[i].smooth_shading = 1;
mysphere[i].scale = [0.05,0.05,0.05];
mysphere[i].color = [Math.random(),Math.random(),Math.random(),0.5] ;
mysphere[i].position = [Math.random()*2.-1, Math.random()*2.-1];
mysphere[i].blend_enable = 1;
}

This code actually creates the individual jit.gl.gridshape objects as individual JitterObjects that are members of the Array
mysphere. We use a JavaScript for() loop to set the initial attributes of all these objects in one block of code. We give them
random initial color and position attributes, scattering them over the screen and coloring them all differently.

// create a JitterListener for our [jit.window] object


var mylistener = new JitterListener(mywindow.getregisteredname(), thecallback);

Finally, we create a variable called mylistener that we assign to be a JitterListener object. JitterListener objects take two
arguments: the object that they listen to, and the function that will be called when the object triggers an event. Our
JitterListener object is set to listen to our jit.window object (mywindow). The getregisteredname() property of a JitterObject
object returns the name by which that object can be accessed by the JitterListener (in the case of jit.window objects, this
will be the same as name of the drawing context). Whenever our jit.window object generates an event, a function called
thecallback() will be triggered in our JavaScript code. Now that weve instantiated a JitterListener, we can (in most cases)
leave it alone and simply deal with the mechanics of the callback function it triggers in response to an event from the object
it listens to.

Back in the Tutorial patcher, click the message box labeled randomize or hit the spacebar on your computer keyboard.
The small spheres should scatter and change colors. Look at the code for the randomize() function in our js file.

function randomize() // reorient the little spheres


{
for(var i="0;i<32;i++)" {
mysphere[i].color = [Math.random(),Math.random(),Math.random(),0.5];
mysphere[i].position = [Math.random()*2.-1, Math.random()*2.-1];
}
}
Our randomize() function takes our little spheres and scatters them randomly, changing their colors. This allows us to
basically restart our simulation whenever we like.

The callback function


The jit.window object responds to a variety of mouse events. When the idlemouse attribute is set to 1 (as it is in our code)
the jit.window object outputs mouse information (the mouseidle message) when you drag the pointer over the window. It
also tells us when the pointer has left the window area (the mouseidleout message). Regardless of the setting of the
idlemouse attribute, the jit.window object also responds to mouse clicks inside the window (the mouse message).
In the Tutorial patcher, move the pointer into the jit.window and click the mouse. The white sphere will turn into a green
torus. Release the mouse and the torus will turn into a red sphere. Moving the pointer will turn the sphere white again.

How our sphere responds to mouse click events (mouse down and mouse up).

Look at the code for the function called thecallback() in our JavaScript code. This code executes whenever our
JitterListener object receives an event from our jit.window object.

function thecallback(event)
// callback function to handle events triggered by mousing
// in our [jit.window]
{
var x,y,button; // some local variables

The event constructor stores the message sent by the jit.window object to the JitterListener object in our patch. We also
declare a few local variables (x, y, and button) to store information about the pointer derived from the event messages
arguments.

We then use JavaScript if() statements based on the eventname property of the event that triggered the callback function.
The eventname property will contain the name of the message (mouse, mouseidle, etc.) that triggered the function.

if (event.eventname="="mouse")" {
// we're entering, dragging within, or leaving a "mouse click" event

This part of the code handles a mouse click event (a click down, dragging of the mouse, and the release of a click).

// arguments are (x,y,button,cmd,shift,capslock,option,ctrl)...


// we only care about the first three
x = event.args[0];
y = event.args[1];
button = event.args[2];

The first three arguments to the mouse event contain the position of the mouse (x and y) and a flag telling us whether the
mouse button is down (1) or up (0). We store these settings into local variables (x, y, and button) for use later on.
if (button) // we're clicked down
{
mywidget.color = [0,1,0,1]; // color our control object green
mywidget.shape = "torus"; // change it to a donut shape
}
else // we've just unclicked
{
mywidget.color = [1,0,0,1]; // color our object red
mywidget.shape = "sphere"; // change back to a sphere
}
}

If our button is down, we turn our jit.gl.gridshape object mywidget from a white sphere into a green torus. When we
release the mouse, we turn it into a red sphere.

else if (event.eventname="="mouseidle")" {
// we're mousing over the window with the mouse up
x = event.args[0];
y = event.args[1];
mywidget.color = [1,1,1,1] ; // color our object white
}

This code executes whenever we drag our pointer across the jit.window object without clicking the pointer. All we do here is
store the variables x and y based on the pointer position. We also turn our jit.gl.gridshape object (mywidget) white, in case
the previous callback had turned it a different color.

else if (event.eventname="="mouseidleout")" {
// we're no longer mousing over the window
x = event.args[0];
y = event.args[1];
mywidget.color = [1,1,1,0.5] ; // make our object translucent
}

When our pointer leaves the jit.window, the eventname property of our callback will be mouseidleout. We treat this the
same as the mouseidle event. If we wanted to, we could treat it differently (e.g. make the white sphere disappear, or
randomize the spheres).

// move our control object to the drawing context's


// equivalent of where our mouse event occurred:
mywidget.position = myrender.screentoworld(x,y);

Finally, we update the position of the jit.gl.gridshape object controlled by our mouse by updating the position attribute of
the JitterObject object mywidget. Because our drawing context works in OpenGL world coordinates (where the default
center of the space is (0, 0) and positions are expressed in decimal values), we need to convert our x and y values into
numbers that make sense for our drawing context. The screentoworld() method to a jit.gl.render object will convert those
values from pixel coordinates on the display to world coordinates for the rendering.

}
// don't allow this function to be called from Max
thecallback.local = 1;

Because our thecallback() function is intended to be executed by our JitterListener object, we set its local property to 1 to
prevent it from being executed directly by a Max message sent to the js object.

Drawing the scene


Now that weve seen how to respond to mouse events and update our mywidget objects position, color, and shape
accordingly, we need to look at how we perform the actual rendering of our scene in response to a bang message from the
qmetro object in our Max patcher. The bang() function in our JavaScript code handles the drawing as well as the animation
of the little spheres in response to the new position of our large sphere.

Look at the code for the bang() function.

The majority of our bang() function iterates through the positions of all the little spheres and compares them to the position
of the large one. If the distance between them is small enough that the spheres would overlap when drawn, we move the
little sphere away the minimum amount necessary to have the spheres touch. This type of processing is known as collision
detection and is a ubiquitous technique in the field of computer animation.

function bang()
// main drawing loop... figure out which little spheres to move
// and drive the renderer
{
// collision detection block. we need to iterate through
// the little spheres and check their distance from the control
// object. if we're touching we move the little sphere away
// along the correct angle of contact.
for(var i = 0;i<OBJECT_COUNT;i++) {

We enter a JavaScript for() loop to check the position of our large sphere against every small sphere, one at a time.

// cartesian distance along the x and y axis


var distx = mywidget.position[0]-mysphere[i].position[0];
var disty = mywidget.position[1]-mysphere[i].position[1];

// polar distance between the two objects


var r = Math.sqrt(distx*distx+disty*disty);
// angle of little sphere around control object
var theta = Math.atan2(disty,distx);

By subtracting the x and y positions of the two spheres (large and small) from one another, we get their Cartesian distance.
We can convert this to polar (absolute) distance by applying the Pythagorean theorem to derive the hypotenuse (stored in
the variable r). We then derive the angle of the small sphere around the large one by taking the arctangent of the rise (x)
over the run (y).

// check for collision...


if(r<0.15)
// control object is size 0.1, little spheres are 0.05,
// so less than 0.15 and it's a hit...
{

Because our large sphere has a scale attribute of 0.1 0.1 0.1 and our small spheres have scale attributes of 0.05 0.05
0.05, we can infer that the objects are overlapping if the distance between them is less than 0.15. This triggers a block of
code that deals with the collision.

// convert polar->cartesian to figure out x and y displacement


var movex = (0.15-r)*Math.cos(theta);
var movey = (0.15-r)*Math.sin(theta);

// offset the little sphere to the new position,


// which should be just beyond touching at the
// angle of contact we had before. the result
// should look like we've "pushed" it along...
mysphere[i].position = [mysphere[i].position[0]-movex, mysphere[i].position[1]-movey];
}

}
We use the polar distance and angle, combined with the minimum allowable distance between the objects (0.15), to derive
how far we need to nudge the little sphere along the x and y axes to stop it from overlapping the large sphere. We figure
out these values by converting the polar coordinates back into Cartesian values stored in the variables movex and movey. We
then subtract these two variables values from the current position of the small sphere, pushing it out of the way.

// rendering block...
myrender.erase(); // erase the drawing context
myrender.drawclients(); // draw the client objects
myrender.swap(); // swap in the new drawing
}

This last block of code does the actual rendering. Just as you would when working with Jitter OpenGL objects in a Max
patcher, you send an erase message to the jit.gl.render object (myrender). The drawclients() method to jit.gl.render
collects all the relevant information from the OpenGL objects attached to our drawing context and draws them; any OpenGL
objects with an automatic attribute set to 0 will have to be drawn manually here. The swap() method then replaces the old
rendering with the new one in the jit.window object, showing us the updated scene. The drawclients() and swap() method
are combined into one operation when you send a bang message to a jit.gl.render object in a Max patcher.
Back in the Tutorial patcher, click the toggle box attached to the message box labeled fullscreen $1 (or hit the escape
key on your computer keyboard). The jit.window object will fill the screen. Notice that the coordinate conversion that allows
you to move the large sphere around the screen with the mouse still works fine. You can take the jit.window object out of
fullscreen mode by pressing the escape key on your keyboard. In the JavaScript code, look at the fullscreen() function:

function fullscreen(v)
// function to send the [jit.window] into fullscreen mode
{
mywindow.fullscreen = v;
}

The fullscreen() attribute of a jit.window JitterObject object behaves just as the fullscreen message sent to a jit.window
object in a Max patcher.

Summary
An entire OpenGL Jitter patch can be encapsulated in JavaScript by instantiating jit.gl.render, jit.window, and other
OpenGL objects within procedural code written for the js object. These objects have all their messages and attributes exposed
as corresponding methods and properties. You can use a JitterListener object to respond to events triggered by a Jitter object
within JavaScript. The JitterListener then executes a callback function, passing the calling message to it as its argument.
This allows you to write JavaScript functions to respond to mouse interactivity in a jit.window object, file reading in a
jit.qt.movie object, and other situations where you would want to respond to an event triggered by a message sent by a
Jitter object out its status outlet in a Max patcher.

Code Listing

// 47jMarbles.js
//
// Demonstrates how to set up a JitterListener object to listen
// to the output of a Jitter object instantiated within [js].
//
// rld, 7.05
//

var OBJECT_COUNT = 32; // number of little spheres

// create a [jit.window] object for our display


// (this is the object we'll "listen" to):
var mywindow = new JitterObject("jit.window","ListenWindow");
// turn off depth testing... we're using blending instead:
mywindow.depthbuffer = 0;
// turn ON idlemousing... we want to listen for it:
mywindow.idlemouse = 1;

// create a [jit.gl.render] object for drawing into our window:


var myrender = new JitterObject("jit.gl.render","ListenWindow");
// use a 2-dimensional projection:
myrender.ortho = 2;
// set background to black with full erase opacity (no trails):
myrender.erase_color = [0,0,0,1];

// create a [jit.gl.gridshape] object for use to control with the mouse


var mywidget = new JitterObject("jit.gl.gridshape","ListenWindow");
mywidget.shape = "sphere";
mywidget.lighting_enable = 1;
mywidget.smooth_shading = 1;
mywidget.scale = [0.1,0.1,0.1];
mywidget.color = [1,1,1,0.5] ;
mywidget.blend_enable = 1;
mywidget.position = [0,0]; // no z necessary in orthographic projection

// create an array of [jit.gl.gridshape] objects randomly arrayed across the window


var mysphere = new Array(OBJECT_COUNT);

// initialize our little spheres with random colors and positions (x,y)
for(var i="0;i<OBJECT_COUNT;i++)" {
mysphere[i] = new JitterObject("jit.gl.gridshape","ListenWindow");
mysphere[i].shape = "sphere";
mysphere[i].lighting_enable = 1;
mysphere[i].smooth_shading = 1;
mysphere[i].scale = [0.05,0.05,0.05];
mysphere[i].color = [Math.random(),Math.random(),Math.random(),0.5] ;
mysphere[i].position = [Math.random()*2.-1, Math.random()*2.-1];
mysphere[i].blend_enable = 1;
}

// create a JitterListener for our [jit.window] object


var mylistener = new JitterListener(mywindow.getregisteredname(), thecallback);

function randomize() // reorient the little spheres


{
for(var i="0;i<32;i++)" {
mysphere[i].color = [Math.random(),Math.random(),Math.random(),0.5] ;
mysphere[i].position = [Math.random()*2.-1, Math.random()*2.-1];
}
}

function thecallback(event)
// callback function to handle events triggered by mousing
// in our [jit.window]
{
var x,y,button; // some local variables

if (event.eventname="="mouse")" {
// we're entering, dragging within, or leaving a "mouse click" event

// arguments are (x,y,button,cmd,shift,capslock,option,ctrl)...


// we only care about the first three
x = event.args[0];
y = event.args[1];
button = event.args[2];
if (button) // we're clicked down
{
mywidget.color = [0,1,0,1]; // color our control object green
mywidget.shape = "torus"; // change it to a donut shape
}
else // we've just unclicked
{
mywidget.color = [1,0,0,1]; // color our object red
mywidget.shape = "sphere"; // change back to a sphere
}
}
else if (event.eventname="="mouseidle")" {
// we're mousing over the window with the mouse up
x = event.args[0];
y = event.args[1];
mywidget.color = [1,1,1,1] ; // color our object white
}
else if (event.eventname="="mouseidleout")" {
// we're no longer mousing over the window
x = event.args[0];
y = event.args[1];
mywidget.color = [1,1,1,0.5] ; // make our object translucent
}

// move our control object to the drawing context's


// equivalent of where our mouse event occurred:
mywidget.position = myrender.screentoworld(x,y);
}
// don't allow this function to be called from Max
thecallback.local = 1;

function bang()
// main drawing loop... figure out which little spheres to move
// and drive the renderer
{
// collision detection block. we need to iterate through
// the little spheres and check their distance from the control
// object. if we're touching we move the little sphere away
// along the correct angle of contact.
for(var i = 0;i<OBJECT_COUNT;i++) {
// cartesian distance along the x and y axis
var distx = mywidget.position[0]-mysphere[i].position[0];
var disty = mywidget.position[1]-mysphere[i].position[1];

// polar distance between the two objects


var r = Math.sqrt(distx*distx+disty*disty);
// angle of little sphere around control object
var theta = Math.atan2(disty,distx);

// check for collision...


if(r<0.15)
// control object is size 0.1, little spheres are 0.05,
// so less than 0.15 and it's a hit...
{
// convert polar->cartesian to figure out x and y displacement
var movex = (0.15-r)*Math.cos(theta);
var movey = (0.15-r)*Math.sin(theta);

// offset the little sphere to the new position,


// which should be just beyond touching at the
// angle of contact we had before. the result
// should look like we've "pushed" it along...
mysphere[i].position = [mysphere[i].position[0]-movex, mysphere[i].position[1]-movey];

}
}

// rendering block...
myrender.erase(); // erase the drawing context
myrender.drawclients(); // draw the client objects
myrender.swap(); // swap in the new drawing
}
function fullscreen(v)
// function to send the [jit.window] into fullscreen mode
{
mywindow.fullscreen = v;
}

See Also
Name Description
jit.gl.gridshape Generate simple geometric shapes as a grid
jit.gl.render Render Jitter OpenGL objects
jit.window Display data in a window
js Execute Javascript
Frames of MSP signals
Tutorial 48: Frames of MSP signals
In Tutorial 27: Using MSP Audio in a Jitter Matrix we learned how to use the jit.poke~ object to copy an MSP audio signal
sample-by-sample into a Jitter matrix. This tutorial introduces jit.catch~, another object that moves data from the signal to
the matrix domain. Well see how to use the jit.graph objects to visualize audio and other one-dimensional data, and how
jit.catch~ can be used in a frame-based analysis context. Well also meet thejit.release~ object, which moves data from
matrices to the signal domain, and see how we can use Jitter objects to process and synthesize sound.
Open the tutorial.

The patch is divided into several smaller subpatches. In the upper left the audio patcher contains a network labeled Sine
wave madness where some cycle~ objects modulate each other. Playback of an audio file is also possible through the
sfplay~ object in the upper-right hand corner of the subpatch.

Inside the Sine wave madness.

Basic Viz
Click the message box labeled dsp start to begin processing audio vectors.

Open the patcher named basic visualization. Click on the toggle box connected to the qmetro object.

Capturing and outputting the audio signals as Jitter matrices.

In the basic visualization patcher the two signals from the audio patcher are input into a jit.catch~ object. The basic
function of the jit.catch~ object is to move signal data into the domain of Jitter matrices. The object supports the
synchronous capture of multiple signals; the objects first argument sets the number of signal inputs; a separate inlet is
created for each. The data from different signals is multiplexed into different planes of a float32 Jitter matrix. In the
example in this subpatch, two signals are being captured. As a result, our output matrices will have two planes.

The jit.catch~ object can operate in several different ways, according to the mode attribute. When the mode attribute is set
to 0, the object simply outputs all the signal data that has been collected since the last bang was received. For example, if
1024 samples have been received since the last time the object received a bang, a one-dimensional 1024 cell float32 matrix
would be output.

The objects mode 1 causes jit.catch~ to output whatever fits in a multiple of a fixed frame size, the length of which can be
set with the framesize attribute. The data is arranged in a two dimensional matrix with a width equal to the framesize. For
instance, if the framesize were 100 and the same 1024 samples were internally cached waiting to be output, in mode 1 a
bang would cause a 100x10 matrix to be output, and the 24 remaining samples would stay in the cache until the next
bang. These 24 samples would be at the beginning of the next output frame as more signal data is received.

When working in mode 2, the object outputs the most recent data of framesize length. Using the example above (with a
framesize of 100 and 1024 samples captured since our last output), in mode 2 our jit.catch~ object would output the last
100 samples received.

In our basic visualization subpatch, our jit.catch~ object is set to use mode 3, which causes it to act similarly to an
oscilloscope in trigger mode. The object monitors the input data for values that cross a threshold value set by the trigthresh
attribute. This mode is most useful when looking at periodic waveforms, as we are in this example.

Note that mode 0 and mode 1 of the jit.catch~ object attempt to output every signal value received exactly once,
whereas mode 2 and mode 3 do not. Furthermore, the matrices output in mode 0 and mode 1 will be variable in
size, whereas those output in mode 2 and mode 3 will always have the same dimensionality. For all modes, the
jit.catch~ object must maintain a pool of memory to hold the received signal values while they are waiting to be
output. By default the object will cache 100 milliseconds of data, but this size can be increased by sending the object a
bufsize message with an argument of the desired number of milliseconds. In mode 0 and mode 1, when more data is
input than can be internally stored, the next bang will not output a matrix but instead will cause a buffer overrun
message to be output from the dump (right-hand) outlet of the object.

Our basic visualization of the audio data.

Since the two signals are multiplexed across different planes of the output matrices, we use the jit.unpack object to access
the signals independently in the Jitter domain. In this example, each of the resulting single-plane matrices is sent to a
jit.graph object. The jit.graph object takes one-dimensional data and expands it into a two-dimensional plot suitable for
visualization. The low and high range of the plot can be set with the rangehi and rangelo attributes, respectively. By default
the graph range is from -1.0 to 1.0.

These two jit.graph objects have been instantiated with a number of attribute arguments. First, the out_name attribute has
been specified so that both objects render into a matrix named jane. Second, the right-hand jit.graph object (which will
execute first) has its clearit attribute set to 1, whereas the left-hand jit.graph object has its clearit attribute set to 0. As you
might expect, if the clearit attribute is set to 1 the matrix will be cleared before rendering the graph into it; otherwise the
jit.graph object simply renders its graph on top of whatever is already in the matrix. To visualize two or more channels in a
single matrix, then, we need to have the first jit.graph object clear the matrix (clearit 1); the rest of the jit.graph objects
should have their clearit attribute set to 0.

The jit.graph objects height attribute specifies how many pixels high the rendered matrix should be. A width attribute is
not necessary because the output matrix has the same width as the input matrix. The frgb attribute controls the color of the
rendered line as four integer values representing the desired alpha, red, green, and blue values of the line. Finally, the mode
attribute of jit.graph allows four different rendering systems: mode 0 renders each cell as a point; mode 1 connects the
points into a line; mode 2 shades the area between each point and the zero-axis; and the bipolar mode 3 mirrors the
shaded area about the zero-axis.

Frames
Turn off the qmetro (by un-checking the toggle box) and close the basic visualization subpatch. Open the patcher
named frame-based analysis and click the toggle box inside to activate the qmetro object.

Performing a frame-based analysis of our audio.

The frame-based analysis subpatch shows an example of how one might use the jit.catch~ objects ability to throw out all
but the most recent data. The single-plane output of jit.catch~ is being sent to a jit.op object which is multiplying it by itself,
squaring each element of the input matrix. This is being sent to a jit.3m object, and the mean value of the matrix is then
sent out the objects middle outlet to a sqrt object. The result is that were calculating the root mean square (RMS) value of
the signal a standard way to measure signal strength. Using this value as the argument to the brightness attribute of a
jit.brcosa object, our subpatch maps the amplitude of the audio signal to brightness of a video image.

Our frame-based analysis technique gives a good estimate of the average amplitude of the audio signal over the period of
time immediately before the jit.catch~ object received its most recent bang. The peakamp~ object, which upon receiving a
bang outputs the highest signal value reached since the last bang, can also be used to estimate the amplitude of an audio
signal, but it has a couple of disadvantages compared to the jit.catch~ technique examines only the final 512 samples,
thereby striking a balance between accuracy and efficiency. The effect that this savings makes is amplified in situations
where the analysis itself is more expensive, for example when performing an FFT analysis on the frame.

Turn off the qmetro and close the frame-based analysis subpatch. Open the patcher named audio again and enter a 0
into the number box connected to the *~ objects at the bottom of the patch; the generated signals will no longer being sent
to your speakers. Close the audio subpatch and open the patcher named processing audio with jitter objects.

Using Jitter objects to process audio data, transforming the results back into signals.
The jit.release~ object is the reverse of jit.catch~: multi-plane matrices are input into the object which then outputs
multiple signals, one for each plane of the incoming matrix. The jit.release~ objects latency attribute controls how much
matrix data should be buffered before the data is output as signals. Given a Jitter network that is supplying a jit.release~
object with data, the longer the latency the lower the probability that the buffer will underflow that is, the event-driven
Jitter network will not be able to supply enough data for the signal vectors that the jit.release~ object must create at a
constant (signal-driven) rate.

Click on the toggle box into the subpatch to start the qmetro object. You should begin to hear our sine waves mixed with
white noise (supplied by the noise~ object). Change the value in the number box attached to the message box labeled val
$1. Note the effect on the amplitude of the sounds coming from the patch.

The combination of jit.catch~ and jit.release~ allows processing of audio to be accomplished using Jitter objects. In this
simple example a jit.op object sits between the jit.catch~ and jit.release~ objects, effectively multiplying all three channels
of audio by the same gain. For a more involved example of using jit.catch~ and jit.release~ for the processing of audio, look
at the jit.forbidden-planet example, which does frame-based FFT processing in Jitter.

Varispeed
Stop the qmetro and close the subpatch. Open the patcher named interpolation release~.

The jit.release~ object can operate in one of two modes: in the standard mode 0 it expects that it will be supplied directly
with samples at the audio rate that is, for CD-quality audio the object will on average receive 44,100 float32 elements
every second and it will place those samples directly into the signals. In mode 1, however, the object will interpolate in its
internal buffer based on how many samples it has stored. If the playback time of samples stored is less than the length of the
latency attribute, jit.release~ will play through the samples more slowly. If the object stops receiving data altogether,
playback will slide to a stop in a manner analogous to hitting a turntable platters stop button. On the other hand, if there are
more samples than needed in the internal buffer, jit.release~ will play through the samples more quickly.
One can use this feature to generate sound directly from an event-driven network. The interpolating release~ subpatch
shows a way for us to do this. The data that drives the jit.release~ object in this subpatcher receives data from a jit.buffer~
object, which allows us to extract data from audio samples in matrix form using messages to the MSP buffer~ object. The
jit.buffer~ object is essentially a Jitter wrapper around a regular buffer~ object; jit.buffer~ will accept every message that
buffer~ accepts, allows the getting and setting of buffer~ data in matrix form, and also provides some efficient functions for
visualizing waveform data in two dimensions, which we use in this patch in the jit.pwindow object at right. At loadbang
time this jit.buffer~ object loaded the data in the sound file talk.aiff.
Turn on the toggle box connected to the qmetro object in the subpatch. Play with the number boxes labeled period and
length ratio and the slider object labeled start.
Playing back interpolated audio data from a sound file in Jitter.

The rate of the qmetro determines how often data from the jit.buffer~ object is sent down towards the jit.release~ object.
The construction at the top maintains a ratio between the period and the number of samples that are output from
jit.buffer~. Experimenting with the start point, the length ratio, and the output period will give you a sense of the types of
sounds that are possible in this mode of jit.release~.

Summary
In this Tutorial we were introduced to jit.catch~, jit.graph, jit.release~, and jit.buffer~ as objects for storing, visualizing,
outputting, and reading MSP signal data as Jitter matrices. The jit.catch~ and jit.release~ objects allow us to transform
MSP signals into Jitter matrices at an event rate, and vice versa. The jit.graph object provides a number of ways to visualize
single-dimension matrix data in a two-dimensional plot, making it ideal for the visualization of audio data. The jit.buffer~
object acts in a similar manner to the MSP buffer~ object, allowing us to load audio data directly into a Jitter matrix from a
sound file.

See Also
Name Description
jit.3m Report min/mean/max values
jit.brcosa Adjust image brightness/contrast/saturation
jit.buffer~ Access an MSP buffer~ in matrix form
jit.catch~ Transform signal data into matrices
jit.graph Perform floating-point data visualization
jit.op Apply binary or unary operators
jit.qt.movie Play or edit a QuickTime movie
jit.release~ Transforms matrix data into signals
Colorspaces
Tutorial 49: Colorspaces
In order to generate and display matrices of video data in Jitter, we make some assumptions about how the digital image is
represented. For many typical uses (as covered by earlier tutorials) we encode color images into 4-plane matrices of type
char. These planes represent the alpha, red, green, and blue color channels of each cell in that matrix. This type of color
representation (ARGB) is useful as it closely matches both the way we see color (through color receptors in our eyes tuned to
red, green, and blue) and the way computer monitors, projectors, and televisions display it. Tutorial 5: ARGB Color
examines the rationale behind this system and explains how you typically manipulate this data.

Its important to note, however, that ARGB is not the only way to represent color information in a digital form. This tutorial
examines one of several different ways of representing color image information in Jitter matrices, along with a discussion of
several alternatives available to us for different uses. Along the way well look at a simple, efficient way to texture video onto
an OpenGL plane to take advantage of hardware accelerated post-processing of the video image.

Software Requirement: In order to use the uyvy colormode in Jitter under QuickTime version 6.5 and earlier, your
media needs to be compressed with a codec that uses a YUV colorspace (discussed in depth below). QuickTime media
compressed with codecs using an RGB colorspace (e.g. PICT files or Planar RGB video files) cannot be decompressed
by jit.qt.movie in the uyvy colormode used in this Tutorial. QuickTime version 7 and later will allow you to work in
the uyvy colormode regardless of the colorspace in which your media is encoded.

Open the tutorial patch 49jColorspaces in the Jitter Tutorials folder.


At first glance, this patch looks very similar to the one we used in Tutorial 12: Color Lookup Tables. It reads a file into a
jit.qt.movie object, sending the matrices out into a jit.charmap object, where we can alter the color mapping of the different
planes in an arbitrary manner by creating a matrix (themap) that serves as a color lookup table. The processed matrix is
then displayed.

Click the message box labeled read colorwheel.jpg. Click the toggle labeled Display connected the qmetro object at the
top of the patch. You should see the colorwheel appear both in the jit.pwindow and in the window created by the jit.window
object.

Though it isnt immediately obvious (yet), the image matrix in our patch is being generated and manipulated according to a
different system of color than the ARGB mapping were accustomed to. The jit.qt.movie object in this patch is transmitting
matrices using a colormode called uyvy. This means that are image processing chain is working with data in a different
colorspace than we usually work in, called YUV 4:2:2. In addition to transmitting color according to a different coordinate
system than we usually use (YUV instead of ARGB), this mode of transmission uses a technique called chroma subsampling
to reduce (by half!) the amount of data transmitted for an image of a given size.

Color Lookup with a Twist


Try manipulating the multislider objects at the right of the patch. Notice that they have an effect on how color is mapped
in the image. You may get the sense that the three multislider objects correspond to the mapping of green, red, and blue in
the matrix, respectively. Try zeroing the leftmost (black-on-white) multislider (i.e. set all of its values to 0). Notice that the
image disappears. Click on the button labeled normal to put everything back. Try zeroing the other two multisliders in
turn, then setting them to straight horizontal lines across the middle of their range.
Manipulating the color.

The YUV colorspace is a luminance/chrominance color systemit separates the luminosity of a given color from the
chromatic information used to determine its hue. It stores the luminosity of a given pixel in a luminance channel (Y). The U
channel is then created by subtracting the Y from the amount of blue in the color image. The V channel is created by
subtracting the Y from the amount of red in the color image. The U and V channels (representing chrominance) are then
scaled by different factors. As a result, low values of U and V will expose shades of green, while a constant medium value of
both will give a grayscale image. One can convert color values from RGB to YUV using the following formula:

Y = 0.299R + 0.587G + 0.114B

U = 0.492(B - Y)

V = 0.877(R - Y)

Note that the U and V components in this color space are usually signed (i.e. they can be negative numbers if the luminosity
exceeds the blue or red amount, as it does with hues such as orange, green, and cyan). Jitter matrices store unsigned char
data, so the U and V values are represented in the range of 0-255, with 128 as the center point of the chromatic space.

The YUV color space with a constant midrange Y value.

The specific implementation of the YUV colorspace used in our Tutorial patch is called YUV 4:2:2. Jitter objects that need to
interpret matrix data as video (e.g. jit.qt.movie, jit.pwindow, etc.) can generate and display this colorspace when their
colormode attribute is set to uyvy. This colormode uses something called chroma subsampling to store two adjacent color
pixels into a single cell (referred to as a macro-pixel). Because our eyes are more attuned to fine gradations in luminosity
than in color, this is an efficient way to perform data reduction on an image, in effect cutting in half the amount of
information needed to convey the color with reasonable accuracy. In this system, each cell in a Jitter matrix contains four
planes that represent two horizontally adjacent pixels: plane 0 contains the U value for both pixels; plane 1 contains the Y
value for the first pixel; plane 2 contains the V value for both pixels; plane 3 contains the Y value for the second pixel. The
ordering of the planes (uyvy) means that we can alter the luminosity of the image by adjusting planes 1 and 3 (for
alternating pixel columns), but we can change the chrominance of pixels only in pairs (by adjusting planes 0 and 2).
Historical Note: Luminance-chrominance color encoding (where the luminosity of the image is transmitted separately
from the hue or chrominance of the image) has its roots in the history of color television broadcasting. When color TVs
were introduced in the United States in 1953, it was necessary to provide a means for television consumers with
monochrome (black-and-white) TV sets to still be able to watch the programming. As a result, it was decided to simply
add color information (in the form of a subcarrier) to the original broadcast signal, which already contained the
luminosity of the image as grayscale. The result was called YIQ (for luminosity-intermodulation-quadrature), and is the
colorspace used in broadcast NTSC color television. The equivalent on PAL television systems is the YUV colorspace
under discussion here.

The following illustration shows how the conversion from ARGB to UYVY is handled in Jitter. Our jit.qt.movie object
performs this translation for us when necessary (see the box below), but the jit.argb2uyvy and jit.uyvy2argb objects will
convert any matrix between colorspaces. Note that the alpha channel is lost in the conversion and that chromatic
information is averaged across pairs of horizontal cells in the ARGB original, creating a slight loss in color information.

Because the UYVY color system uses a macro-pixel, each cell in the matrix actually represents two horizontally adjacent
pixels in the image; for example, a 320x240 pixel image becomes a 160x240 cell matrix when output as UYVY. When
processing these matrices, its important to keep that in mind, as Jitter objects that process matrices based on spatial
information (e.g. those that do scaling, rotation, convolution, etc.) will treat these pairs of pixels as a single unit. When
working with these types of processes it may be easier to work in a colormode that uses a full resolution pixel, e.g.
ARGB or AYUV (a full-resolution YUV colorspace also supported by Jitter).

(note that a new, empty alpha channel is also created).

A 4x4 grid of random values converted from ARGB to UYVY and back again.

Many commercial video codecs use YUV 4:2:2 (or similar chroma subsampling systems such as 4:1:1 and 4:2:0) as
their native video format. As a result, jit.qt.movie can decompress these files faster in the uyvy colormode than when
outputting matrices in the normal ARGB format. The matrices thus generated are also half the size, giving a
performance increase to any Jitter patches that can take advantage of this system. Codecs such as Photo-JPEG,
DVCPRO, and NTSC DV all use some form of subsampled YUV codec as their native color format.

With this in mind, we can understand the processing going on in our patch. The jit.qt.movie sends matrices in the uyvy 4-
plane char format to the jit.charmap, which processes the data and sends it onwards. The jit.fpsgui tells us that the dim of
the matrices being sent to it are 160x240, which makes sense now that we understand the macro-pixel data reduction that
accompanies the switch in colormode. In addition, we can now see why the matrix themap has one jit.fill object feeding
both planes 1 and 3; these correspond to the two Y values in the macro-pixel, which we want to share the same lookup
table.

Color tinting and saturation


Set the multislider objects to their normal curve by clicking the button object labeled normal. Above the patcher objects
labeled brco, adjust the number box controlling the contrast for the Y channel until it reads -1.
Inverted Y color table.

Because the luminosity is separate from the chrominance in our new colorspace, it is a simple matter to invert the brightness
of pixels without affecting their hue. This would be a more involved procedure if working in ARGB.

Normalize the multislider objects again, and adjust the number box objects for the U and V channels contrast. Try setting
them both to -1, then to 0. Normalize their contrast settings and set the brightness values both to -1.

Different U and V settings.

By inverting the U and V channels color lookup, we perform a 180-degree hue rotation on the image. Setting both of these
channels to a constant value desaturates the image so that it appears at a constant chroma, or hue, according to the
Cartesian space shown earlier in this tutorial. Values of 0 will desaturate the image to greyscale; values of -1 will make the
entire image appear green.

Do some freehand drawing in the multislider objects. Try to get a feel for how different ranges of the char range results in
different effects on different channels.

In addition to YUV 4:2:2 (colormode uyvy) and ARGB (colormode argb, the default for most objects), Jitter objects
exist that generate matrices in a number of other colorspaces. Examples include grgb (a chroma subsampled RGB
colorspace similar to uyvy), ayuv (a full-resolution YUV colorspace with an alpha channel), luma (a 1-plane char
grayscale format), and ahsl (alpha, hue, saturation, luminosity). Conversion objects are typically named jit.x2y, e.g.
jit.argb2uyvy. In addition, the jit.colorspace object supports translation to and from a variety of 4-plane char
colorspaces (including approximations of floating-point colorspaces such as L*a*b*). A good place to begin for more
information on colorspaces (and the numerical representation of color in general) is the Wikipedia article on the
subject:

Videoplane
Notice that the output of the jit.pwindow in our patch doesnt go directly to a jit.window object. Instead, it goes to an
object called jit.gl.videoplane. Click on the message box labeled read track1.mov. The processed image should switch to a
movie. Normalize the color lookup tables on the right by clicking the button labeled normal.
The jit.gl.videoplane object textures the Jitter matrix sent into its inlet onto a plane in an OpenGL drawing context. Our
drawing context (colorspace) is being driven by the jit.gl.render object at the top of the patch, and is viewable through the
jit.window objects window. If you need to review the basics of OpenGL rendering in Jitter, a look at Tutorial 30: Drawing
3D text will fill you in on the basics of creating a rendering system. One thing of note is that the ortho attribute of
jit.gl.render, when set to 2, renders our scene in an orthographic projection (i.e. there is no sense of depth). Also note that
the jit.gl.videoplane object, not the jit.window, needs to be told to interpret texture matrices as uyvy through its
colormode attribute. In our patch we really arent using OpenGL for 3D modeling; but we are taking advantage of some
features of hardware accelerated texture mapping.

Click on the message box containing the text dim 16 16 (next to the jit.pwindow object).
Notice that the jit.pwindow object shows a massively downsampled and pixelated image (Its actually processed as an 8x16
matrix since were still in uyvy mode). The jit.window object, however, shows an image where the pixels are smoothly
interpolated into one another (the effect is similar to upsampling in a jit.matrix object with the interp attribute set to 1).

Hardware interpolation of a small matrix applied as a texture.

This interpolation is occurring on the hardware Graphics Processing Unit (GPU), and is one of the many advantages to using
OpenGL to display video, as it causes no performance penalty on the main CPU of our computer.

Click on the message box containing the text dim 320 240. This will set the size of the matrices back to the normal
resolution weve been using: 320x240 pixels, output as 160x240 cells per matrix because of the colormode. One the right of
the patch, click on the toggle attached to the message box labeled fullscreen $1 (alternately, hit the ESC key on your
keyboard).

When you send a jit.window object into fullscreen mode, the jit.gl.videoplane upsamples the texture even further, giving
you the smoothest possible interpolation for your display.

Hit the ESC key to trigger the toggle again, taking the jit.window out of fullscreen.

Videoplane Post-Processing
Adjust the red, green, and blue number box objects attached to the pak object connected to the jit.gl.videoplane object.
Note than even though the applied texture is mapped in YUV colorspace, the jit.gl.videoplane responds to color attributes
in floating-point RGBA. Manipulate the number box labeled rotate.
Some examples of GPU processing on a videoplane.

We can see that the color and rotate attributes (as well as scale, blend_enable, etc.) of most OpenGL objects also apply to
jit.gl.videoplane. As a result, jit.gl.videoplane is an incredibly useful object for video processing, as it allows us to apply
processing to the image directly on the GPU.

Summary
The jit.qt.movie object can output matrices in a number of colorspaces beyond ARGB. The YUV 4:2:2 colorspace can be
used by setting the colormode attribute of the objects that support it (jit.qt.movie, jit.pwindow and jit.window) to uyvy.
The uyvy colormode has the advantage of using a macro-pixel chroma subsampling to cut the data rate in half, allowing for
matrices to be processed faster in the Jitter matrix processing chain. Since the data output in this colorspace is still 4 planes
of char information, standard objects such as jit.charmap can be used to manipulate the matrix, albeit with different
results.

The jit.gl.videoplane object accepts matrices (including uyvy matrices) as textures that are then mapped onto a plane in the
OpenGL drawing context named by the object. GPU accelerated processing of the image can therefore be done directly on
the plane, including color tinting, blending, spatial transformation, etc. In Tutorial 52: Shaders well look at ways to apply
entire processing algorithms to objects in the drawing context, further expanding the possibilities of using the GPU for
processing in Jitter.

See Also
Name Description
jit.argb2uyvy Convert ARGB to UYVY
jit.charmap Map 256-point input to output
jit.fill Fill a matrix with a list
jit.gencoord Evaluate a procedural basis function graph
jit.gl.render Render Jitter OpenGL objects
jit.gl.videoplane Display video in OpenGL
jit.matrix The Jitter Matrix!
jit.noise Generate white noise
jit.pwindow Show data in a patcher
jit.qt.movie Play or edit a QuickTime movie
jit.uyvy2argb Converts UYVY to ARGB
multislider Display data as sliders or a scrolling display
Procedural Texturing & Modeling
Tutorial 50: Procedural Texturing & Modeling
In this Tutorial we will be examining different operations that can be used to construct a procedural model of a texture or
some form of geometric data.

Procedural techniques are a powerful way of defining some aspect of a computer-generated model through algorithms
and/or mathematical functions. In contrast to using pre-existing data such as a static images or photographs, procedural
models can generate visual complexity of arbitrary resolution and infinite variation. In conjunction with parametric controls,
such models can be used to build a flexible interface for controlling complex behaviors and capturing a special effect.

Jitter provides a comprehensive set of basis functions and generators that are exposed through the jit.bfg object. Each
function performs a point-wise operation in n-dimensional space whose evaluation is independent of neighboring results.
This means that these operations can be performed on any number of dimensions, across any coordinate, without any need
of referencing existing calculations. In addition, since they all share a common interface, these objects can be combined
together and evaluated in a function graph by cross-referencing several jit.bfg objects.
There are several categories of functions, each of which are characterized by a different intended use. These categories
include fractal, noise, filter, transfer, and distance operations. Functions contained in these folders can be passed by name
to jit.bfg either fully qualified (category.classname) or relaxed (classname).
Before looking at these categories in detail, we'll first explore the general interface of jit.bfg and show how to create different
types of procedural functions and fill a jit.matrix with our results.

jit.bfg
Open the tutorial.

Once the patch loads, take a look at the different objects being used. Notice that we have a metro object attached to the
jit.bfg object. Once activated, a bang message will notify jit.bfg to evaluate and output a Jitter matrix just like most other
Jitter objects. In this example, jit.bfg has been setup to generate a single plane matrix of type float32 and size 128x128.
Click on the toggle box connected to the metro object to begin sending bang messages to jit.bfg.

Notice that the jit.pwindow object remains solid black in color! Since jit.bfg has not been told what basis function evaluate,
jit.bfg is not outputting a matrix and jit.pwindow remains unchanged.

Select the noise.cell basis function from the list in the umenu object.
An evaluated basis function.

Now that jit.bfg has been given a function to evaluate, we can see the results of its calculation in jit.pwindow. Internally,
jit.bfg is generating a series of Cartesian coordinates that it passes to the indicated basis function during its evaluation.

If we wanted to, we could adjust these coordinates and have jit.bfg perform the evaluation over a different domain.

Change the value of the number box connected to the scale message box.

Notice that the results of jit.bfg change as we adjust the domain.

Select the distance.euclidean basis function from the list in the umenu object.

Again change the value of the number box connected to the scale message box.

Notice that positive values in the scale number box have little effect on the results being shown in jit.pwindow, whereas
negative values flip the image components from white to black. What is going on? Distance should always be positive and
increase outward from the origin, right?

jit.normalize
The output of jit.bfg goes into a jit.normalize object connected to the jit.pwindow. This object will examine an incoming
matrix and scale the minimum and maximum values into a normalized range of 0-1.

When we changed the scale values being sent to jit.bfg for evaluating the distance.euclidean function from positive to
negative, the highest and lowest values that were being outputted from jit.bfg switched as we crossed over the origin. Since
jit.normalize always scales the input matrix maximum to 1 and the minimum to 0, our colors flipped.

Since the output range of jit.bfg may yield extremely large results, especially when evaluating unbounded functions such as
fractals, we need to normalize our output in order to map the results for display.

Basis Categories
Now that we are familiar with the basic interface for setting up jit.bfg and specifying a basis function to evaluate, let's
examine the contents of each function category.

Distance Functions
The functions in the distance category each define a unique metric for determining the positional difference from a given
point to the global origin.

Descriptions of each of these functions are provided in the following list.

chebychev: Absolute maximum difference between two points.

euclidean: True straight line distance in Euclidean space.

euclidean.squared: Squared Euclidean distance.

manhattan: Rectilinear distance measured along axes at right angles.


manhattan.radial: Manhattan distance with radius fall-off control.

minkovsky: Exponentially controlled distance.

The noise.voronoi object requires one of thesedistance objects to be specified as part of its evaluation.

Filter Functions
The filter category contains signal processing filters which can be used to perform image sampling and reconstruction or to
create pre-computed kernels for a general convolution.

Descriptions of each of these functions are provided in the following list.

box: Sums all samples in the filter area with equal weight.
gaussian: Weights samples in the filter area using a bell curve.

lanczossinc: Weights samples using a steep windowed sinc curve.

mitchell: Weights samples using a controllable cubic polynomial.


disk: Sums all samples inside the filter's radius with equal weight.

sinc: Weights samples using an un-windowed sinc curve.

catmullrom: Weights samples using a Catmull-Rom cubic polynomial.


bessel: Weights samples with a linear phase response.

triangle: Weights samples in the filter area using a pyramid.

These objects are used as parameters to both the noise.value.convolution and the noise.sparse.convolution objects,
which expect to be given a filter object as part of their evaluation.

Transfer Functions
Functions that map input to a different output are contained in the transfer category. Most of these functions operate only
on a single dimension within the unit interval 0-1.

A brief description of these functions is contained in the list below.

step: Always 1 if given value is less than threshold.


smoothstep: Step function with cubic smoothing at boundaries.

bias: Polynomial similar to gamma but remapped to unit interval.

cubic: Generic 3 rd order polynomial with controllable coefficients.


saw: Periodic triangle pulse train.

quintic: Generic 5th order polynomial with controllable coefficients.

gain: S-Shaped polynomial evaluated inside unit interval. Note: the default settings will result in a linear curve instead of
the descriptive S-curve shape.
pulse: Periodic step function.

smoothpulse: Periodic step function with cubic smoothing at boundaries.

sine: Periodic sinusoidal curve.


linear: Linear function across unit interval.

solarize: Scales given value if threshold is exceeded.

These transfer functions can be used inside of several of the noise objects to change their smoothing function and/or alter
their output.

Noise Functions
Deterministic stochastic patterns (aka pseudo-random coherent noise functions) are the cornerstone of nearly every
procedural model. They allow a controllable amount of complexity to be created by adding visual detail.

A brief description of these functions is contained in the list below.

cellnoise: Coherent blocky noise.

checker: Periodic checker squares.


value.cubicspline: Polynomial smoothed pseudo-random values.

value.convolution: Convolution filtered pseudo-random values.

sparse.convolution: Convolution filtered pseudo-random feature points.

gradient: Directionally weighted polynomially interpolated values.


simplex: Simplex weighted pseudo-random values.

voronoi: Distance weighted pseudo-random feature points.

distorted: Domain distorted combinational noise.


All of these functions are generators with the exception of the noise.distorted object, which is a binary operator and uses
two existing functions for its evaluation.

Fractal Functions
Fractals provide a specialized form of generation by combining multiple scales or octaves of another basis function. This
process forms the characteristic self-similarity exhibited by all fractals.

A brief description of these functions is contained in the list below.

mono: Additive fractal with global simularity across scales.

multi: Multiplicative fractal with varying simularity across scales.

multi.hybrid: A hybrid additive and multiplicative fractal.


multi.hetero: Heterogenous multiplicative fractal.

multi.ridged: Multiplicative fractal with sharp ridges.

turbulence: Additive mono-fractal with sharp ridges.


Other Attributes & Messages
Select the noise.checker basis function from the umenu object.

Notice that in addition to the scale message that we used previously, we can also transform the evaluation coordinates
through rotation, translation (via offset) and by adjusting their origin.

Change the 1 st and 2 nd number boxes connected to origin to change the x and y origin.
Change the 1 st and 2 nd number boxes connected to offset to change the x and y offset position.

Change the 1 st number box connected to rotation to change our rotation angle about the x axis.

Notice the effect of the transform. Also notice the drop in performance when a rotation is performed we will always get
better frame rates if the rotation attribute is left at 0 for each matrix dimension.

Technical Detail: In addition to the internal coordinate generation already described, jit.bfg also accepts an input
matrix of coordinates to evaluate (XYZ map to planes 0-2, and the input matrix must be the same dim as the jit.bfg
output matrix).

Change the 1 st number box connected to rotation to 0 to disable rotation.


Click the toggle box connected to autocenter to enable automatic centering.

If the autocenter attribute is set to 1, the current matrix dim sizes will be used to place the origin in the center of the
output matrix, overriding any values already set for the origin.

Click the toggle box connected to autocenter again to disable automatic centering.
Select the noise.gradient basis function from the umenu object.

Click the dim 128 128 1 message box.

As mentioned previously, all of the basis functions that Jitter provides can be evaluated over any number of dimensions.
This message has changed our output matrix to be a 3D matrix, and has correspondingly set the evaluation to be performed
in 3-dimensional space. Since our display is still a 2D screen, we only need to evaluate a single slice in 3D, and thus our 3 rd
dim is set to 1.

Change the 3 rd number box connected to offset to change the z evaluation position.
Notice how our results change. We are now traversing along the z-axis as if we were moving forward/backwards through a
volume aligned with the screen.

Select float64 from the umenu connected to the precision message.


The precision message can be used to change the jit.bfg objects internal evaluation precision. This may be desirable if we
need more or less accurate results without changing the output matrix type.

Change the 3 rd number box connected to offset to change the z evaluation position.
Notice how the higher precision affects the frame rate reported by the jit.fpsgui object. We should be careful to only use
float64 precision when needed.

Select float32 from the umenu connected to the precision message.

Change the planecount for jit.bfg from 1 to 3 to enable RGB output.

In addition to n-dimensional evaluation, jit.bfg can generate up to 32 planes per dimension. Each plane is offset by a
pseudo-random fractional amount controlled by the align attribute.

Change the number box connected to align for jit.bfg.


Notice how the planes separate and become more visible as the align amount gets larger.

To see more specific examples for different combinations of basis functions, open the help patch for the jit.bfg object and
look in the subpatchers for each category of function..

Technical Detail: The output of jit.bfg can actually be used as an input to another jit.bfg to perform domain distortion,
similar to the way noise.distorted operates. Check out the example patch in jit-examples/other/jit.bfg.distorter.pat.

Summary
The jit.bfg object gives us access to a library of procedural basis functions and generators that we can use to define a
procedural model for creating textures and modifying geometry. Internally jit.bfg generates Cartesian coordinates along a
grid. These coordinates can be transformed using the corresponding origin, offset, and rotation attributes, or overridden
altogether via an input matrix containing evaluation coordinates.

See Also
Name Description
jit.bfg Evaluate a procedural basis function graph
jit.matrix The Jitter Matrix!
jit.normalize Normalizes a matrix.
jit.pwindow Show data in a patcher
umenu Create and fill a pop-up menu
Jitter Java
Tutorial 51: Jitter Java
This tutorial assumes that the reader is familiar with the process of programming mxj Java classes. The details for how this
is done are contained in the Writing Max Externals in Java document.

In this Tutorial well outline how mxj classes can operate directly on the cells of an input matrix. We also will see how to
create classes in the Java programming language that internally load Jitter objects and define and execute a processing
network. Finally, we will learn how to design hardware-accelerated user interface elements by attaching a listener to a
drawing context and polling a window for mouse events.

The Jitter Java API centers around the JitterObject class, which provides a way for mxj classes to instantiate Jitter objects.
The following line of code creates a jit.op Jitter object.

JitterObject jo = new JitterObject(jit.op);

We can send messages to objects in our Java code by using JitterObjects call() or send() methods. For instance, we might set
the operator in the above instance of jit.op as follows:

jo.send(op, +);

We could alternatively set this attribute using the setAttr() method:

jo.setAttr(op,+);

The JitterMatrix class extends JitterObject after all, jit.matrix is a Jitter Object. Since jit.matrix is such a common
object it is handy to have convenience methods dedicated to its creation and destruction. For instance, the below line of code
creates a new 4-plane JitterMatrix of type char and dimensions 320 by 240.

JitterMatrix jm = new JitterMatrix(4, char, 320, 240);

We can also create a JitterMatrix object by specifying the matrix name:

JitterMatrix jm = new JitterMatrix(Stanley);

If a jit.matrix object named Stanley already exists, this Java peer JitterMatrix object will refer to it. In this case a new
jit.matrix object is not created.

Conveniences are nice, but the primary reason the JitterMatrix class exists is to provide native methods to access the data in
the matrix cells. Well see an example of this in action when we open the tutorial patch.

Accessing an Input Matrix


Open the tutorial patch 51jJava in the Jitter Tutorials folder. Double-click on the matrix info subpatcher. Click on the
button object and look at the output in the Max window.
Information about our matrix printed in the Max window.

In this subpatcher, clicking on the button object causes the jit.noise object to send a 4 plane 64 by 48 float32 matrix into
an mxj object with the j51matrixinfoexample class loaded. This Java class sends some basic information about the input
matrix out its outlet. Lets examine the code for the class:

import com.cycling74.max.*;

import com.cycling74.jitter.*;

public class j51matrixinfoexample extends MaxObject {

public void jit_matrix(String s)

JitterMatrix jm = new JitterMatrix(s);

outlet(0,"name", jm.getName());

outlet(0,"planecount", jm.getPlanecount());

outlet(0,"type", jm.getType());

outlet(0,"dim", jm.getDim());

The class consists of a single jit_matrix method. Of course since matrices are passed between Jitter objects as named
references, we think of a matrix being input as just a simple two element list, and this is how mxj sees it. The argument of
the jit_matrix message is of course the matrix name, so the first thing our method does is create a new JitterMatrix object
with the name of the input matrix as the constructors only argument. The JitterMatrix object that is created will have that
named jit.matrix object as its peer. The next four lines of code simply output the results of some basic queries that can be
made using the methods of the JitterMatrix class.

Operating on a Matrix
Close the matrix info subpatcher. Open the striper subpatcher.

The striper subpatcher gives us an example of a class that operates on the data of an input matrix. Note that there are two
classes set up to be used, with a Ggate object allowing us to switch between them; we will be comparing two different ways of
performing the same operation to see which is more efficient.

Click on the toggle box to start the qmetro object.

A striping effect on a Jitter matrix.

These classes stripe an input matrix by iterating across each row of the matrix and overwriting the values of some of the
cells. Which cells are written to depends on the values of the on and off attributes: if the on attribute has value v and off has
value w, the algorithm will overwrite v cells, then not write to w cells, and so on as it iterates row-wise through the matrix.

Here is the code for j51matrixstriperA:

import com.cycling74.max.*;

import com.cycling74.jitter.*;

public class j51matrixstriperA extends MaxObject {

JitterMatrix jm = new JitterMatrix();

int frgb[] = new int[] {255, 255, 255, 255};

int on = 2, off = 1;

j51matrixstriperA()

declareAttribute("frgb");

declareAttribute("on");
declareAttribute("off");

//note that this method assumes a 2D char matrix!

public void jit_matrix(String s)

jm.frommatrix(s);

int dim[] = jm.getDim();

int count = 0;

boolean notoff = true;

for (int i="0;i<dim[1];i++)"

for(int j="0;j<dim[0];j++)"

if (notoff)

jm.setcell2d(j, i, frgb);

if ((notoff &&(++count > on))

||(!notoff&&(++count > off)))

count = 0;

notoff = !notoff;

outlet(0, "jit_matrix", jm.getName());

In the jit_matrix method we use the getDim() method to find out the dimensions of our matrix and store them in the int
array dim, which we then use as the terminal conditions in the for() loops of our iterative procedure. The setcell2d method
allows us to directly set the value of any cell in the matrix. When we are finished processing, we send a jit_matrix message
out with the name of our JitterMatrix as the argument.

Toggle the Ggate object back and forth. Which class is faster?
The only difference between j51matrixstriperA and j51matrixstriperB is the jit_matrix method. Here is j51matrixstriperBs
jit_matrix method:

//note that this method assumes a 2D char matrix!

public void jit_matrix(String s)

jm.frommatrix(s);

int dim[] = jm.getDim();


int count = 0;

int planecount = jm.getPlanecount();

int offset[] = new int[]{0,0};

boolean notoff = true;

int row[] = new int[dim[0]*planecount];

for (int i="0;i<dim[1];i++)"

offset[1] = i;

jm.copyVectorToArray(0, offset, row,

dim[0]*planecount, 0);

for(int j="0;j<dim[0];j++)"

if (notoff)

for (int k="0;k<planecount;k++)"

row[j*planecount+k] = frgb[k];

if ((notoff &&(++count > on))

||(!notoff&&(++count > off)))

count = 0;

notoff = !notoff;

jm.copyArrayToVector(0, offset, row,

dim[0]*planecount, 0);

outlet(0, "jit_matrix", jm.getName());

Rather than set values in the matrix one cell at a time, the jit_matrix method of j51matrixstriperB grabs an entire row from
the matrix using JitterMatrixs copyVectorToArray method, overwrites the appropriate values in the row, then writes the row
back to the matrix using JitterMatrixs copyArrayToVector method. As you may have noticed, this version of the class is
significantly faster than the version that sets cells in the matrix one-by-one. This is an excellent demonstration of the
following very important thing to keep in mind: it is very expensive to cross the C/Java boundary. The version of this object
that uses setcell must go back and forth across the C/Java boundary once for every cell in the matrix. The latter version goes
back and forth just twice per row. If you have tried both versions of the object out, the savings are evident.

The copyVectorToArray and copyArrayToVector methods are overloaded with signatures that cover all the relevant data
types. As you can see from a careful examination of the above code, these methods provide and expect the Java arrays with
the planar data multiplexed so that all of a cells data is presented contiguously. There are also copyVectorToArrayPlanar and
copyArrayToVectorPlanar methods for moving a single planes data into Java.

When using mxj classes to process matrices in Jitter there is no built-in usurp functionality, so it is important to
always drive the object network using a qmetro object, or some other construction that defers events to prevent
backlog.

Copying Input Data


In the above examples may also have noted the different way that we internally use our JitterMatrix. Whereas in the matrix
info example we created a new JitterMatrix every time an input matrix was received, this time we cache one instance of
JitterMatrix and copy the input data into it every time using the frommatrix method. Why do we do this?

Stop the qmetro and close the striper subpatch. Open the why copy? subpatch. Turn on the qmetro.

Why copy?

The trigger object in this subpatch sends the output of the jit.noise object first into an instance of the mxj class
j51whycopy:

import com.cycling74.max.*;

import com.cycling74.jitter.*;

public class j51whycopy extends MaxObject {

JitterMatrix jm = new JitterMatrix();

boolean copy = false;

j51whycopy()

declareAttribute("copy");

public void jit_matrix(String inname)

//under normal circumstances

//we would only create this matrix once

jm = new JitterMatrix();

if (copy)

jm.frommatrix(inname);
}

else //!copy

jm = new JitterMatrix(inname);

zero(jm);

outlet(0, "jit_matrix", jm.getName());

//note that this method assumes the matrix is of type char

private void zero(JitterMatrix m)

int z[] = new int[m.getPlanecount()];

for (int i="0;i<m.getPlanecount();i++)"

z[i] = 0;

m.setall(z);

The copy attribute flips the jit_matrix method between two different modes: if copy is true, the data from the input matrix
is copied into our internal JitterMatrix using the frommatrix method. If copy is not true, the JitterMatrix jm is created with
the input matrix as its peer. In both cases our JitterMatrix is zeroed using the setall method, and then output.

Turn the copy attribute on and off with the toggle box. What happens in the left jit.pwindow?
When the copy attribute is off and we create a new JitterMatrix associated with the input name we operate directly on the
data of that matrix. Therefore we may be altering the contents of the matrix before other objects have had a chance to see it.
In this example patch, when the copy attribute is true the left jit.pwindow correctly shows the matrix produced by jit.noise.
When the copy attribute is false both jit.pwindow objects are black because our mxj class alters the matrixs data directly.
Therefore if we are operating on a matrix, we should make sure to copy the input data into an internal cache as we do here
with frommatrix.

Object Composition
In this section well examine the use of multiple JitterObjects within a single Java class.

Toggle the qmetro off and close the subpatcher window. Open the composition subpatcher. Toggle the qmetro on.

A Jitter processing chain executing within Java.


Lets examine the code for the j51composition class:

import com.cycling74.max.*;

import com.cycling74.jitter.*;

public class j51composition extends MaxObject {

JitterMatrix jm = new JitterMatrix();

JitterMatrix temp = new JitterMatrix();

JitterObject brcosa;

JitterObject sobel;

boolean brcosafirst = false;

j51composition() {

declareAttribute("brcosafirst");

brcosa = new JitterObject("jit.brcosa");

brcosa.setAttr("brightness", 2.0f);

sobel = new JitterObject("jit.sobel");

sobel.setAttr("thresh", 0.5f);

public void jit_matrix(String mname)

jm.frommatrix(mname);

temp.setinfo(jm);

if (brcosafirst)

brcosa.matrixcalc(jm, temp);

sobel.matrixcalc(temp, jm);

else

sobel.matrixcalc(jm, temp);

brcosa.matrixcalc(temp, jm);

outlet(0, "jit_matrix", jm.getName());

public void notifyDeleted()

{
brcosa.freePeer();

sobel.freePeer();

Two JitterObjects are created in the classs constructor: brcosa controls a peer jit.brcosa object, and sobel controls a peer
jit.sobel object. The jit_matrix method copies the data from the input matrix to jm, and then sets the dimensions,
planecount and type of the temp matrix to that of jm with the setinfo method. After this the two JitterObjects can be used
to process the data in either order: if the attribute brcosafirst is true, the brcosa operates first and then sobel, and of course
vice versa is brcosafirst is false. We operate on the data in a matrix by calling a JitterObjects matrixcalc method. The two
arguments are input and output matrices it is also possible to use arrays of input and output matrices if the peer Jitter
object supports multiple matrix inputs or outputs. This simple example shows how it is possible to define a varying network
of Jitter objects within a Java class.

Toggle the brcosafirst attribute on and off to see the difference in the resulting image.

Finally, note that when the mxj object is deleted and the notifyDeleted method is called, the peer Jitter objects are freed by
calling the freePeer() method for every JitterObject weve instantiated. If freePeer() is not called the C object peers will
persist until the Java memory manager garbage collects, and this could take a while.

Listening
Toggle the qmetro off and close the subpatch. Open the cubiccurver subpatch. Turn on the toggle box labeled verbose,
move the mouse in the jit.pwindow object and observe the results in the Max window.

This section assumes youve looked at Tutorial 47: Using Jitter Object Callbacks in JavaScript, which covers object
callbacks in Javascript. The Jitter Java API provides the same mechanism for listening to events generated by named Jitter
objects. In this subpatcher we use this mechanism to track mouse movement within a named jit.pwindow. Lets examine the
source code for the j51pwindowlistener class:

import com.cycling74.max.*;

import com.cycling74.jitter.*;

public class j51pwindowlistener extends MaxObject

implements JitterNotifiable

JitterListener listener;

boolean verbose = false;

j51pwindowlistener()

declareIO(1,2);

declareAttribute("verbose");

public void name(String s)

listener = new JitterListener(s,this);

public void notify(JitterEvent e)

//this gets the name of the listening context

String subjectname = e.getSubjectName();

//this gets the type of event...mouse, mouseidle, etc.

String eventname = e.getEventName();

//this gets the arguments of the event

Atom args[] = e.getArgs();

if (verbose)

outlet(1,subjectname);

outlet(1,eventname,args);

if ((eventname.equals("mouse"))

||(eventname.equals("mouseidle")))

{
int xy[] = new int[] {args[0].toInt(),

args[1].toInt()};

//output the x and y coordinates of the mouse

outlet(0, xy);

The first thing to notice is that the class implements an interface called JitterNotifiable. This simple interface ensures that
the class has a notify method which will be called when an event is heard. Notice that the notify method takes a JitterEvent
as an argument. The notify method in this class illustrates the methods of these JitterEvents that well use to extract the
pertinent data: getSubjectName returns the name of the listening context, which is useful if were listening in more than one
place; getEventName returns the name of the event that has been heard; and getArgs returns the arguments that detail the
parameters of the event. With the verbose attribute enabled, this classs notify method outputs these data out the second
outlet and a print object sends it to the Max window.
The notify method continues by testing the value of eventname for equality with either mouseidle (for normal mouse
movement) or mouse (for movement with the button down). If either of these Strings is a match, the first two arguments,
which represent the x and y position of the mouse in the window, are output as a list.

The last thing to note about this class is that before any listening can happen the listener must be created with an existing
context. In this case that happens when an instance of the class receives a name message. Unlocking the patch will show you
how the jit.pwindow object is given a name first; the name message is then sent to the instance of j51pwindowlistener.
The rest of the patch uses the jitcubiccurve example class to render a cubic curve the follows the mouse around. The control
points for the cubic curve are calculated using the j51fracdistancer class, whose code you may want to read through to see if
youve understood the material in this lesson:

import com.cycling74.max.*;

import com.cycling74.jitter.*;

import java.util.*;

public class j51fracdistancer extends MaxObject{

JitterMatrix ctlmatrix =

new JitterMatrix(1, "float32", 8);

float ctldata[] = new float[8];

int offset[] = new int[] {0};

float frac = 0.5f;

float noise = 0.5f;

Random r = new Random();

j51fracdistancer() {

declareAttribute("frac");

declareAttribute("noise");

//new x,y input

public void list(int args[])


{

if (args.length != 2) return;

float x = (float)args[0];

float y = (float)args[1];

for (int i="0;i<4;i++)"

ctldata[i*2] += (x-ctldata[i*2]) * frac +

((float)r.nextGaussian()*noise);

ctldata[i*2+1] += (y-ctldata[i*2+1]) * frac +

((float)r.nextGaussian()*noise);

ctlmatrix.copyArrayToVector(0,offset, ctldata, 8, 0);

outlet(0, "jit_matrix", ctlmatrix.getName());

public void jit_matrix(String mname)

JitterMatrix jm = new JitterMatrix(mname);

if (jm.getDim()[0] != 8) return;

if (jm.getPlanecount() != 1) return;

if (!jm.getType().equals("float32")) return;

ctlmatrix.frommatrix(mname);

ctlmatrix.copyVectorToArray(0, offset, ctldata, 8, 0);

Summary
In this tutorial weve introduced the JitterObject, JitterMatrix, and JitterListener classes, and weve seen how to use them to
put together mxj classes that operate directly on data, use composition of existing Jitter objects to define graphs of
processing, and how to listen to Jitter objects for events in a way that can facilitate the building of user interface
components, among other things.

See Also
Name Description
jit.matrix The Jitter Matrix!
jit.noise Generate white noise
jit.op Apply binary or unary operators
jit.qt.movie Play or edit a QuickTime movie
mxj Execute Java in Max
Jitter Networking
Tutorial 52: Jitter Networking
The jit.net.send object allows us to send uncompressed matrices over the Internet to a jit.net.recv object in a Max patch on
a different computer.

In the Jitter Tutorials folder, open the tutorial patches 52jNetworkSend and 52jNetworkRecv. If you like, you can open
these on different computers.

The jit.net.send and jit.net.recv objects communicate using the TCP protocol. A discussion of the different types of
network transmission protocols is beyond the scope of this Tutorial; its important to note, however, that TCP is a
connection-oriented protocol. Before anything can be sent or received the pair of objects must make a connection to one
another. Both objects report any change in their connection status out the dump outlet with a connected message, followed
by an argument of 1 when connected or 0 when disconnected.

A patch to send Jitter matrices over a computer network using TCP.

To form a connection, the jit.net.recv and jit.net.send objects must be set to listen to the same port. We can set the port
attribute to any positive integer value, but some of the lower numbers are reserved for commonly used network services such
as FTP, web browsing, etc. A port in the range above 1024 and below 10000 will probably be safe. If no port is specified, the
default for both objects is 7474.

In addition to port number, the jit.net.send object must know the IP address of the computer running the Max patch
containing the jit.net.recv object wed like to send to. A computer may have more than one IP address the wireless
interface and Ethernet port will have different addresses, for example and, by default, the jit.net.recv object will listen to
all of them for a connection request from a jit.net.send suitor. It is possible to specify which interface to use by sending the
object an ip message with the specific IP address of the desired interface as an argument.

If we open the sending and receiving patches on the same computer, the objects may immediately form a connection. The
toggle boxes connected to the route objects in each patch will be checked if this is the case. By default the jit.net.send
objects ip attribute is set to 127.0.0.1, which is the local loopback address. The jit.net.recv object is listening to all
addresses by default, including the local loopback, so a connection should be made if the two patches are on the same
computer. If youre running the patches on different computers, you can use the mxj net.local object to figure out what IP
address the jit.net.send object should be trying to connect with. Note that one can specify an IP address with the ip
attribute, or alternatively one can specify a hostname with the host attribute and jit.net.send will attempt to use the
Domain Name Service (DNS) to resolve the hostname to an IP address.
A patch to receive and display Jitter matrices sent over a computer network.

If you cant get your objects to connect to one another, and youre sure youve got the IP address and port correct, make
sure a software firewall on any computer isnt preventing communication on the port weve selected (7474 in these
tutorial patches). On a computer running Windows XP, the controls for the software firewall can be found in the
Control Panel:Windows Firewall:Advanced tab, where double clicking any of the network connections will bring up an
Advanced Settings window that allows you to define new services. On an OS X machine the controls for the software
firewall can be found in System Preferences:Sharing:Firewall, where you can click on the New button to specify a
port to open. If you are connecting two computers together through one or more routers, its possible that they have
filters in place that are rejecting the packets.

Turn on the toggle box connected to the qmetro in the 52jNetworkSend.pat patch.
In the sending patch, a jit.qt.movie object is sending matrices to a jit.net.send object. Note that the qmetro driving the
movie playback triggers the movie frame and then sends the jit.net.send object a getlatency message. This causes a one-
way latency estimate to be output from the dump outlet. We can use this estimate of the transmission latency to synchronize
events on the two computers, for instance by delaying the processing or display of a matrix on a local computer by the
amount of the estimate, at which point the receiving computer should be ready to process the matrix it has received.

Latency is influenced by two factors: the direct transmission time between the two computers, and the amount of data
being sent. The more data that is sent, the longer the time it takes to move all the data across the network. Obviously
the speed of the computers network interface and all routing hardware is key in this respect the transmission can
only be as fast as the weakest link in the chain. One technique we might consider using to reduce latency is to transmit
matrices using either of the grgb or uyvy compressed color spaces that are discussed in Tutorial 49.

In addition to sending matrices, any normal Max message input into the right inlet of jit.net.send will come out the middle
outlet of the connected jit.net.recv object. The input order of messages and matrices will be preserved in the receiving patch.
In this example, the patcher named dim changes contains a slower qmetro that changes the dimensionality of the movie
every half second. These new dimensions are input into the right inlet of the jit.net.send object. When the two integers
come out the second outlet of the jit.net.recv object they are used as the arguments of the size message to resize the
jit.pwindow object.

The matrices in this tutorial patch are of type char, but jit.net.send and jit.net.recv can handle matrices of any type. For an
example that uses float32 matrices, please refer to audio-over-network in the jit-examples/audio folder.

Summary
Using the jit.net.send and jit.net.recv objects, you can send uncompressed Jitter matrices to another computer running
Max. You specify a port for the two machines to communicate on, as well as an ip address for the sending machine to use
when connecting to the receiving machine.

See Also
Name Description
jit.net.recv Receive matrices from a jit.net.send object via TCP/IP
jit.net.send Send matrices to a jit.net.recv object via TCP/IP
jit.qt.movie Play or edit a QuickTime movie
Jitter Networking (part 2)
Tutorial 53: Jitter Networking (part 2)
Broadcasting
In addition to sending matrix data over networks, we can also create RTSP streams in Jitter, using the objects jit.broadcast
and jit.qt.broadcast. The jit.qt.broadcast object is only available on computers running the Mac OS, and is described at
the end of this chapter. The jit.broadcast object is cross-platform. Both objects function more or less the same way, though,
and users of jit.qt.broadcast should follow the entire chapter.
RTSP stands for Real-Time Streaming Protocol, and is a popular network streaming standard, supported by many media
players such as the QuickTime Player and VLC (you can learn more about VLC, a free, open-source, cross-platform player, at
http://www.videolan.org/vlc/). These media players are RTSP clients. Our Max objects are RTSP servers, and they
properly format, in some cases compress, packetize and broadcast data for RTSP streaming. Using these objects, you don't
need any external server everything is done for you, all inside of Jitter!

Mainstream
Before we get started, you'll want to make sure that your network is properly configured. Ensure that you have a network
interface active and a valid IP address. On Windows, this is particularly important, or our streaming experiments won't work.

Even if you are not connected to a network on Windows, you'll need to have at least one active network interface, as far
as the OS is concerned. This might mean logging/dialing into the Internet, or attaching a powered-on router to your
Ethernet port, even if you have no other computers to share withbasically, anything which causes Windows to detect
that you're using the networkso that it assigns your computer an IP address.

Open the tutorial.

Click on the message box labeled read dishes.mov and turn on the toggle box labeled Start Movie to begin movie
playback. You should see the movie playing in the jit.pwindow object.
Before we begin the actual broadcast, we should consider a few things.

First, what will the dimensions of our broadcast stream be? The two arguments in the jit.broadcast object's box determine
the size of the compressed, streamed image. To change this size, the size attribute is used. In our case, we will stream at
160x120 pixels.

Second, what streaming video codec are we going to use? The jit.broadcast object supports 3 different onesMPEG-4,
H.263 and JPEG. Incoming Jitter frames will be automatically compressed into the chosen format before streaming.

Using the umenu object, choose your desired streaming codec from the 3 available.

By default, the object uses the MPEG-4 codec, but the choice is yours. Certain codecs may be easier for some clients to
receive. For instance, at the time of this writing, QuickTime Player is much better at receiving MPEG-4 video than
VLC.

Third, are we streaming to a single computer (known as a unicast) or should our stream be made available to any client who
accesses the URL of our stream (known as a multicast)? By default, the jit.broadcast object uses multicast streaming,
although this can be changed using the unicast attribute.

Click on the message box labeled getvip and note the output in the Max Window. When multicasting, the jit.broadcast
object automatically generates a valid multicast IP address. Click on the toggle labeled Enable Unicast and click the
message box labeled getvip again, noting the output in the Max Window. The IP address changed to 127.0.0.1 (this
address is also known as localhost, and means "myself"using this IP address, the computer would broadcast to itself).
Using the vip attribute, we could now manually set the IP address of the (single) client computer (you can't change the vip
attribute when multicasting, since it's generated automatically). For the purposes of this tutorial, we're going to stick to
multicasting, but it's important to note that both methods are available.

There are a number of additional parameters which we can set to control the broadcast, such as port numbers, time-to-live
(TTL), codec quality and keyframe-generation, and so on. By default, those values are all set to perfectly functional defaults,
and there's no need to change them for this Tutorial.
Finally, what should we name our stream? The jit.broadcast object produces a URL for client computers to access, in the
form rtsp://192.168.2.2:8554/jitStream. The IP address and port numbers are generated for us, but we could change the
last part to our liking. For instance, we could name our RTSP stream someDishes.

Click on the message box labeled streamname someDishes. This will customize our stream's name.
Click on the message box labeled start to begin streaming. When streaming has successfully begun, the message start,
followed by a 1, then the RTSP URL (e.g. start 1 rtsp://192.168.2.2:8554/someDishes) should appear in the Max
Window. This last part is the address that client computers should connect to, in order to receive your stream.

Router Users: Note that if your computer is behind a router providing a local IP address (using NAT, for instance), the
RTSP URL will refer to your local IP address, not your "real" IP address (WAN address), as would be accessed from
computers outside of your local network. To learn your WAN address, you can point your web browser to
http://checkip.dyndns.org/ (merely one example from many similar websites). You'll substitute this address for the
numerical portion of the RTSP URL before the colon. In the example above, the WAN address would take the place of
192.168.2.2.

Most routers have built-in firewalls. In order to properly stream from Jitter, be aware that the RTSP port (the portion
of the RTSP URL after the colon, but before the forward-slash; here, 8554) will have to be unblocked, and any network
traffic to that port must be directed to your computer. Consult the manual of your router if you are unsure how to do
this.

If you have a 2nd computer on your network, use a web browser or media player on that computer (such as QuickTime
Player or VLC) to connect to the URL printed in the Max Window. Or call a friend and ask them to try it over the Internet.
Or, if you have neither a 2nd computer nor available friends, you can fire up a copy of a web browser or media player on the
same machine Jitter is running on to see your stream.

If it didn't work, check the IP address in the RTSP URL. If the address is 0.0.0.0, this means you've got a network
configuration problem on your server machine. Click the message box labeled stop, make sure that you're connected
to a network and click the message box labeled start again.

When you've confirmed that it's all working, click the message box labeled stop. You might want to try some more
broadcasting using different codecs and compare image quality and performance.

File Streaming
Using the jit.broadcast object, we can also stream pre-compressed Hinted Movie files as created by QuickTime. The
jit.qt.movie object can export Hinted Movie files, so let's use it to export and hint our dishes.mov file, preparing it for
broadcast.

Hinted Movie files contain extra information about the contents of the movie tracks, providing "hints" to a streaming
server about codecs and quality, so that the server only has to worry about packetizing and broadcasting the data. In
the case of jit.broadcast, since the object needn't compress incoming frames, streaming a Hinted Movie might offer a
modest performance improvement, depending on your media.

We first need to tell the jit.broadcast object that we want to stream a movie file, rather than incoming matrix data. This is
accomplished by setting the object's mode attribute.

Turn on the toggle labeled Matrix / File to set the jit.broadcast object's mode attribute to 1file broadcast mode.
We use the export message to jit.qt.movie to create a Hinted Movie. You may want to refer to Tutorial 20: Importing and
Exporting Single Matrices if you want to refresh your memory about movie exporting.

Click on the message box labeled export fulldialog. This brings up the Export dialog box for the movie loaded into
jit.qt.movie (in our case, dishes.mov).
The QuickTime export dialog box on Mac OS X.

Chose Movie to QuickTime Movie from the pop-up menu labeled Export, beneath the file browser section of the dialog
box. Although there is a selection called Movie to Hinted Movie, it doesn't recompress a movie's media, which we want to
do.

Click the button labeled Options... to open the Movie Settings dialog box.
The Movie Settings dialog box on Mac OS X.

Make sure that the Video check box has been checked and click on the button labeled Settings... just beneath it to open the
Standard Video Compression Settings dialog box. Choose MPEG-4 Video from the pop-up menu labeled Compression Type
and then click OK to return to the Movie Settings dialog box. Make sure that the check box labeled Prepare for Internet
Streaming is checked, and that Hinted Streaming is selected in the pop-up menu directly beneath. Click OK when you're
done, to return to the Export dialog box.

Choose a location to save your Hinted Movie and a name, and click the Save button to write the movie to a file on your
hard disk.

Good work! We're almost ready to stream the movie. In the case of a Hinted Movie, the vcodec attribute (or related
information such as the spatialquality, temporalquality or kframe attributes) to jit.broadcast has no effectall of that
information is already provided by the movie itself. All we need to do is tell the jit.broadcast object which movie to stream.
Click the message box labeled movie to bring up a standard file dialog box, navigate to the location of your newly saved
Hinted Movie and open it. A message should be posted to the Max Window with the filename of your movie followed by the
number 1, indicating that the movie was read successfully.

Press the message box labeled start to begin broadcasting. Just like before, a message with the RTSP URL will be output
from the object's dump outlet and posted to the Max Window. Verify with a media player or web browser that the movie is
streaming.

When you're done, click the message box labeled stop to stop the broadcast.

Using the jit.qt.broadcast object (Mac OS X only)


In most respects, the jit.qt.broadcast object functions identically to its companion jit.broadcast object. There are a few
significant differences between the 2 objects, though:

The jit.qt.broadcast object uses Session Description Protocol (SDP) files, instead of an "automatic" session
announcement, when making a stream available.

The jit.qt.broadcast object can stream several more codecs than the jit.broadcast object.
The jit.qt.broadcast object can stream audio and/or video from Hinted Movie files, not just video.

The jit.qt.broadcast object can stream audio and/or video from an attached camera.

The interested learner can consult the on-line Reference and help patch for the jit.qt.broadcast object to learn about
streaming from a camera. For this tutorial, we're simply going to go through the process of generating an SDP file and
starting a video-only broadcast based on incoming Jitter matrices.

Session Description Protocol files simply provide some basic data to RTSP clients about how many tracks are being
streamed, some information about how they are encoded, and where in the network or internet the client should look for the
actual streaming data (the SDP file needn't be located at the source of the data). The jit.qt.broadcast object automatically
generates these files, based on how the broadcast's codec, size, etc. have been set in the object. By making this file available
to RTSP clientsemailing the file to friends, posting a link to the file on a web site, etc.you can publicize your stream.

If the tutorial patch 53jBroadcasting.pat is still open, close it now. Then open the tutorial patch 53jQTBroadcasting from
the Jitter Tutorials folder. As you can see, the patches look very similar. Just as in the previous patch, the 2 arguments to our
broadcast object determine the dimensions of the broadcast stream.

Click on the message box labeled read dishes.mov and turn on the toggle labeled Start Movie to begin movie playback.
You should see the movie playing in the jit.pwindow object.
If you like, make a selection from the umenu labeled Codec. The default video codec, H.263, should be already selected.
Note that we have access to all of the standard video codecs available in QuickTime.

Some codecs are much better suited for streaming than others. H.261, H.263, MPEG-4 and Photo-JPEG are reasonably
common. Other codecs can be used, but may not offer acceptable image quality or performance, streamed over a
network.

Click on the message box labeled write. A standard file dialog box will open, where you can choose the name and location
for the SDP file that describes your broadcast stream. Click OK to save the file.

The SDP file is now configured for your broadcast, as it is currently set up. If you make any changesa change from
multicast to unicast, or to a new codecyou will need to write a new SDP file.

Click on the message box labeled start to begin streaming.

If you have a 2nd computer on your network, use a web browser or media player on that computer (such as QuickTime
Player or VLC) to open the SDP file (you will need to transfer the file to the other machine somehow). Or email the SDP file
to a friend and ask them to try it over the Internet. Or, if you have neither a 2nd computer nor available friends, you can
open the file in a local web browser or media player and try it out yourself.

Click on the message box labeled stop to end the broadcast.

Summary
In this chapter, we learned how to use the jit.broadcast and jit.qt.broadcast objects to serve RTSP (Real-Time Streaming
Protocol) streams directly out of Jitter, using different codecs and different methods of session announcement. We also
learned how to export Hinted Movies from the jit.qt.movie object.

See Also
Name Description
jit.broadcast Broadcast video using RTSP
jit.qt.broadcast Broadcast video using RTSP (Macintosh only)
jit.qt.movie Play or edit a QuickTime movie
QuickTime Confidential
Appendix A: QuickTime Confidential
Structure of QuickTime movies
When you imagine a QuickTime movie, chances are good that you think of something similar to film: a single series of
frames arranged linearly in time, with or without sound.

In fact, the structure of QuickTime movies is far more similar to the model you may be familiar with from MIDI and audio
sequencers.

QuickTime movies are containers for tracks. Each track contains a particular type of mediasuch as audio or videoand
defines the spatial and/or temporal boundaries of that media. For instance, a QuickTime movie might be 320x240 in size,
and 3 minutes in length, while one of its video tracks is 80x60 in size, and only 30 seconds long. QuickTime movies are never
longer than the end of their longest track.

Each track in a QuickTime movie might be of a different typevideo, audio, sprites, MIDI (QuickTime calls these music
tracks), and VR Panoramas are some of the available typesand might start at a different point within the movie. You can
have several tracks of identical types in a single movie as well. Tracks are independentthey can be turned on and off
individually, and they can all be of different lengths.

The QuickTime music track is a container for a Standard MIDI File. Using the QuickTime Settings Control Panel, you
can set the output for these tracks. By default, QuickTime uses the QuickTime Music Synthesizer, which is a General
MIDI software synthesizer built into QuickTime. If you have Open Music System (OMS) installed, you can have
QuickTime send music tracks out via OMS to a hardware synthesizer. Or, by using the Inter-Application
Communication bus (IAC), you can send them right back into Max!

The visual priority of tracks is determined by the tracks visibility layer. Track layers are numbered from 32768 to 32767.
Tracks with low visibility layer values will be displayed in front of tracks with high visibility layer values. Audio tracks will
automatically mix, regardless of their layer value.

The jit.qt.movie object offers a number of track-centered functions. A brief list of some useful messages follows:
General Track Editing
addtrack: create a new track
deletetrack: delete a track
gettrackinfo: displays several pieces of track information (index, name, type, enabled status, visibility layer)
gettrackoffset: displays a tracks temporal offset (set using the trackoffset message)
gettrackduration: displays a tracks duration (set using the trackduration message)
gettrackdim: displays a tracks spatial dimensions (set using the trackname message)
gettracktype: displays a tracks type (type cannot be setuse addtrack to create a new track)
gettracklayer: display a tracks visibility layer (set using the tracklayer message)
gettrackcodec: display a tracks codec (codec cannot be set)
gettrackenabled: displays a tracks enabled status (set using the trackenabled message)
getgmode: displays a tracks drawing modethe manner in which it interacts with other tracks (set using the gmode
message)

Important: Track edits of any sort, including adding or deleting tracks, will not be automatically saved with a movie
when it is closed. Use the savemovie, savemovieas or savemoviecopy messages to permanently save your changes,
or set the jit.qt.movie objects autosave attribute to 1 (on).

QuickTime VR
vrpan: set the pan for a VR movie
vrtilt: set the tilt for a VR movie
vrfov: set the field of view for a VR movie
vrnode: set the current node for a multi-node VR movie (use the getvrnodelist message to enumerate available nodes)
QuickTime Effect (see Tutorial 24: QuickTime Effects for more information)
addfxtrack: create a QuickTime Effects track set (1 to 3 actual tracks), by importing a .qfx file
deletefxtrack: delete any and all QuickTime Effects tracks created by the addfxtrack message

Background Color
addbgtrack: create a background color track
deletebgtrack: delete a background color track created by Jitter.

Time in QuickTime
Unlike most hardware-based media, QuickTime does not use a frame-based time system. Instead, QuickTime uses a system
based on timescale and time values. Timescale is an integer value that indicates how many time values make up one second
of a movie. By default, a new QuickTime movie has a timescale of 600meaning that there are 600 time values per second.

Frame rate is determined by the concept of interesting timetimes where the movie changes. If a movie changes every 40
time values, then it has an effective frame rate of 15 frames per second (since 600 divided by 40 equals 15). When Jitter
determines how many frames are in a movie with the getframecount message, it scans the movie for interesting times, and
reports their number. The frame and jump messages move the play head between different points of interesting time.

For more information on the relationship between timescale and frame rate, refer to Tutorial 4: Controlling Movie
Playback.

In Jitter, recording operations permit you to specify a frame rate, and Jitter takes care of the calculations for you as it
constructs a new movie. Editing operations, in contrast, use time values to determine their range of effect.

Optimizing Movies for Playback in Jitter


Although Jitter will gladly play any movie you throw at it, there are some guidelines you can follow to improve performance.
Sadly, there is no precise recipe for perfectionperformance in a real-time application such as Jitter is the result of the
interaction between a movies track codecs (which affect data bandwidth and processor load), movie dimensions, frame rate
and, to some extent, the complexity of the media being processed.

Codecs
Visual media, in particular, contain large amounts of data that must be read from disk and processed by your computer
before they can be displayed. Codecs, or compressor/ decompressors, are used to encode and decode data. When encoding,
the goal is generally to thin out the data so that less information has to be read from disk when the movie plays back.
Reading data from disk is a major source of overhead when playing movies.

If you have enough RAM, you can use the loadram message to jit.qt.movie to copy a movies (compressed) media to
RAM. Since accessing RAM is significantly faster than accessing a hard disk, movie playback will generally improve,
although the jit.qt.movie object still has to decompress each frame as the movie plays. To buffer decompressed matrix
data to RAM, use the jit.matrixset object.

When decoding, the goal is to return the data to its pre-encoded state as quickly as possible. Codecs, by and large, are lossy,
which means that some data is lost in the process. As users, our goal is to figure out which codec offers the greatest quality at
the greatest speed for our particular application.

To determine a QuickTime movies track codecs, use the gettrackcodec message to jit.qt.movie.

Audio Codecs
Codecs are available for both video and audio tracks. For online distribution, you might want to use an MPEG 2 Level 3
(.mp3) or QDesign audio codec to create smaller files. In Jitter, however, if you are playing movies with video and audio
tracks, youll achieve the best results with uncompressed audio (PCM audio) simply because there will be no audio codec
decompression overhead.

Technical Note: .mp3 files can be read byjit.qt.movie as audio-only movies (they are compressed with the MPEG 2
Layer 3 codec). Although you cant process the audio data with any other Jitter objects besides the jit.qt.movie object,
you can use the jit.qt.movies soc attribute to send the audio to MSP via the spigot~ object (see Tutorial 27: Using
MSP Audio in a Jitter Matrix for more information).
Video codecs
Video codecs may be handled in hardwareyou may have a special video card that provides hardware compression and
decompression of a particular codec, like MPEG or Motion-JPEGor more typically in software. In Jitter, hardware codec
support is only relevant to video output components. Movie playback will always use a software codec, with the important
exception of the jit.qt.movie objects direct to video output component feature (see Tutorial 22: Video Output Components
and the Object Reference entry for the jit.qt.movie object for more information).

Technical Note: Video cards that provide hardware support of codecs usually only support them for onscreen
decompression of media. Since Jitter generally decompresses media into an offscreen buffer (with the exception noted
above), software codecs are used.

Video codecs generally use one or both of the following schemes: spatial and temporal compression.

Spatial compression is probably familiar to you from the world of still images. JPEG, PNG and PICT files each use types of
spatial compression. Spatial compression schemes search a single image frame for patterns and repetitions that can be
described in a simpler fashion. Most also simplify images to ensure that they contain these patterns. Nevertheless, more
complex images are harder to compress, and will generally result in larger files. Spatial compression does not take time into
accountit simply compresses each frame according to its encoding algorithm.

Temporal compression is unique to the world of moving images, since it operates by creating a description of change
between consecutive frames. In general, temporal compression does not fully describe every frame. Instead, a temporally
compressed movie contains two types of frames: keyframes, which are fully described frames (usually spatially compressed,
as well), and regular frames, which are described by their change from the previous keyframe.

For applications where a movie will be played from start to finish, temporal compression is quite useful. Codecs like
Sorenson use temporal compression to create extremely small files that are ideal for web playback. However, temporal
compression is not a good choice if you need to play your movie backwards, since the order of the keyframes is vital to
properly describing the sequence of images. If we play a temporally compressed movie backwards, the change descriptions
will be processed before the keyframe that describes the initial state of the frame! Additionally, the Sorenson codec is quite
processor-intensive to decompress. Playback of a Sorenson-compressed movie will be slower than playback of a movie
compressed using a lighter method.

For Jitter playback, we recommend using a video codec without temporal compression, such a Photo-JPEG or Motion-JPEG
(Photo- and Motion-JPEG compression use the same compression method, but Motion-JPEG is optimized for special
hardware support [see note above]). At high quality settings, JPEG compression offers a nice compromise between file size
and image quality. Its also relatively simple to decode, so your processor can be put to better use than decompressing video.

If image quality is of principle importance, the Animation codec looks better than Photo-JPEG, but creates much larger files.

Different versions of QuickTime support different audio and video codecs. For instance, QuickTime 5 doesnt support the
MPEG-4 codec, although QuickTime 6 does. You should experiment with different codec settings to find the best match for
your particular use of Jitter.

Movie Dimensions and Frame Rate


Compared to codec, movie dimensions and frame rate are more straightforward factors in Jitter performance. Simply put, a
bigger image frame or a higher frame rate indicates that Jitter has more data to process each second.

A 640x480 movie produces 1,228,800 individual values per frame for Jitter to process (640 times 480 times 4 (separate
values for alpha, red, green and blue channels). A 320x240 movie produces a mere 307,200 individual values per frame, one
quarter the size of the larger movie. Where possible, we recommend using smaller movies if you intend to use Jitter for
processing. On most machines, 320x240 movies will give fine performance.

If you are working with DV media, your movies are recorded at 29.97 frames per second (in NTSC) or 25 frames per second
(in PAL). Even using a 320x240 movie, Jitter has to process 9,206,784 values per second in NTSC and 7,680,000 values per
second in PAL. Thinning this data, by reducing the frame rate to 15 or 20 frames per second, will improve performance
significantly if you are using Jitter for processing. On most machines, 15 fps is a good choice.

Our Favorite Setting


Weve found that, for most movies, the following parameters yield consistently good results:
320x240 frame size
15 frames per second

Video tracks: Photo-JPEG codec, using a medium to high spatial quality setting

Audio tracks: no compression

Summary
QuickTime movies can contain many tracks of different typesaudio, video, QuickTime VR and text, to name a few. In
Jitter, we can both get and set basic information about these tracksincluding their temporal offset, spatial dimensions,
duration, visibility layer and graphic transfer modeusing the jit.qt.movie objects track messages.
QuickTimes time model is somewhat different from the standard frame-based model, relying on a timescale value to
determine the number of time values in a second of QuickTime media. The jit.qt.movie object allows for playback
navigation using both frame and timescale models. All editing functions in the jit.qt.movie object use the timescale model to
determine the extent of their effect.

Determining the ideal settings for a movie used in Jitter is an inexact science. Actual performance depends on a number of
factors, including codec, dimensions, frame rate and media complexity. For best results on current hardware, we recommend
using 320x240, 15 fps, Photo-JPEG compressed movies
The OpenGL Matrix Format
Appendix B: The OpenGL Matrix Format
Matrices, Video and OpenGL
OpenGL is a standard which specifies a virtual machine for turning lists of numbers into 2D images. The lists may contain
the 3D locations of vertices to connect with lines or polygons. They can also contain other data such as coordinates for
texture mapping, normals for lighting, colors and edge flags.

Jitter treats video as a type of data which can be processed in its general matrix system. When manipulating video data in
Jitter, each cell of a matrix represents one pixel. The four planes of the matrix store the A, R, G and B components of that
pixel. This is Jitter's convention for storing video.

Jitter also has a convention, used by all the objects in the GL group, for storing OpenGL-compatible image descriptions in a
matrix. Like video data, these descriptions can be read, processed, and output by various objects. This document specifies
Jitters convention for storing OpenGL data in matrices and the syntax of messages to the jit.gl.render object containing
these matrices.

When You Need This Reference


Objects in the GL group send out matrices in the format described here when they have their matrixoutput attributes set to
1. In order to process these geometries through your own patches, you will need to know this format. If you want to make
geometries directly using the jit.op object and other matrix operators, you will also need to know the format. But if Jitters
GL objects are flexible enough for your drawing needs, you can continue to let these objects draw behind the scenes
without any knowledge of the OpenGL matrix format.

GL Matrix Reference
Message Format
OpenGL data can be passed to the jit.gl.render object in Max messages of the forms
jit_matrix [geometry matrix]

jit_matrix [geometry matrix] [draw primitive]

and

jit_matrix [geometry matrix] [connections matrix] [draw primitive].

Draw Primitive
The draw primitive specifies how to draw the connections between vertices in the geometry matrix. When a draw primitive is
not passed to the jit.gl.render object along with the geometry matrix, the current primitive of the jit.gl.render object is
used. The current primitive can be changed by sending a message containing just the primitive. When a draw primitive
accompanies the geometry matrix, it is used only to draw the given geometry and the current primitive is unchanged.

The draw primitive can be one of the following symbols:

points Draws each vertex as a single point.

lines Connects eavery other pair of vertices with a line. Given a geometry matrix with vertices A, B, C and D, it draws line
segments AB and CD.

line_strip Connects each pair of vertices with a line. Given a geometry matrix with vertices A, B, C and D, it draws line
segments AB, BC and CD.

line_loop Like line_strip but a line segment is drawn connecting the last vertex in the matrix back to the first one.

triangles Draws unconnected triangles. Given vertices A B C D E F, draws triangles ABC and DEF.

tri_strip Draws a strip of connected triangles. Given vertices A B C D E F, draws triangles ABC, CBD, CDE and EDF. Note
the order of the vertices, which is swapped so that all the triangles face the same way (see Tutorial 33: Polygon Modes,
Colors and Blending).

tri_fan Draws a fan of triangles. Given vertices A B C D E F, draws triangles ABC, ACD, ADE and AEF.

quads Draws unconnected quadrilaterals. Given vertices A B C D E F G H, draws quadrilaterals ABCD and EFGH.
quad_strip Draws connected quadrilaterals. Given vertices A B C D E F, draws quadrilateral ABCD and CDFE.

polygon Draws a single polygon using all the vertices in the matrix. If the polygon is not simple and convex, the results are
undefined.

tri_grid If the geometry matrix has two dimensions, triangles are drawn which link each vertex to its neighbors in the matrix
to form a surface.

quad_grid If the geometry matrix has two dimensions, quadrilaterals are drawn which link each vertex to its neighbors in
the matrix to form a surface.

The Connections Matrix


A connections matrix must be one-dimensional and contain either long or char data. If present, it specifies the order in
which to connect the vertices in the geometry matrix. By leaving the geometry matrix constant and changing the connections
matrix which indexes into it, a changing set of connections between the same vertices can be drawn.

The Geometry Matrix


Geometry matrices must contain data in long, float32, or float64 format, float32 being the most common choice. Float64
has more precision than is normally needed for rendering to the screen. The long data type restricts values to integers, which
is generally not desired when specifying coordinates.

Each cell of the matrix represents one vertex. The image is rendered by drawing connections between vertices, either along
the rows or the columns of the matrix. A one cell wide matrix will be connected along columns (its only column). A one cell
high matrix will be connected along rows. If the matrix is more than one cell in both width and height, the geom_rows
attribute of the jit.gl.render object determines whether rows or columns will be followed. If the tri_grid or quad_grid
primitives are specified, both the rows and the columns of the matrix are always connected.

Matrices with anywhere from two to 13 planes can be used. Planes 13 and up are reserved for later use and will currently be
ignored. Each plane represents a different value in one of five groups: vertices, texture coordinates, normals, vertex color and
edges. If enough planes are present to specify a given group, that group is used in rendering the matrix. To be used, each
group must be totally present, with the exception of vertices. If only x and y values for vertices are present, the z coordinate
of all vertices is set to 0, and an 2D image on the xy plane results.

plane 0: x coordinate of vertex

plane 1: y coordinate of vertex

plane 2: z coordinate of vertex

plane 3: s coordinate of texture at vertex, if textured

plane 4: t coordinate of texture at vertex, if textured

plane 5: x component of lighting normal at vertex

plane 6: y component of lighting normal at vertex

plane 7: z component of lighting normal at vertex

plane 8: red component of vertex color

plane 9: green component of vertex color

plane 10: blue component of vertex color

plane 11: alpha component of vertex color

plane 12: edge flag for connection to next vertex: if < 0, no line is drawn.
The JXS File Format
Appendix C: The JXS File Format
The Jitter Shader Description File
Jitter provides a means of encapsulating shader parameters and programs through an XML based shader description file
(JXS). This JXS file offers an easy way of setting up any required OpenGL state to achieve a particular effect, without any
additional patcher related work.

The JXS file may contain a list of parameters and textures, followed by a set of language dependent implementations for the
shader's vertex and fragment programs.

Each language implementation must specify both a vertex and a fragment program. These programs may either reference
external files, or be stored inline within a CDATA section or an XML comment. Programs for each language implementation
will be loaded and bound in the order that they are listed in the JXS file. If a particular language implementation fails to
compile, the next implementation will be used, until a successful candidate is found.

Inside of the language implementation declaration, any shader parameter previously specified must be identified with a bind
tag that indicates which shader program should receive the parameter's values.
The following listing outlines the format of a typical JXS file:

<jittershader name="myshader>"

<!-- optional description -->

<description>This is my shader</description>

<!-- optional list of texture objects to bind -->


<texture file="mytexture.jpg"/>

<!-- optional list of shader parameters -->

<param="myparam" type="vec3" default="3.0 4.0 5.0">

<description>This is my parameter</description>

</param>

<!-- list of language implementations -->

<language type="glsl" version="1.0">

<!-- list of binding targets for shader parameters -->

<bind param="myparam" program="vp"/>

<!-- vertex and fragment programs -->

<program name="vp" type="vertex" source="sh.passthru.xform.vp.glsl"/>

<program name="fp" type="fragment">

<![CDATA[

// entry point

void main()

{
gl_FragColor=vec4(0.5, 0.5, 0.5, 1.0);

]]>

</program>

</language>

</jittershader>

Note that the XML document must be well-formed with matching opening/closing tags.

JXS Tags
Any of the following XML tags may be used inside the JXS document:
Building Standalone Applications with Jitter
Appendix D: Building Standalone Applications with Jitter

If you want to create a standalone application that uses Jitter, you will need to copy a number of files to your standalone
application folder (for Windows applications) or include them in your Macintosh applications package. The appendix
describes the files you will need to copy if you intend to include Jitter, Jitter shaders, Java, or Javascript support in your
application.

For more information about building standalone applications, see the chapter on Collectives in the Max Tutorials and Topics
Manual.

Windows Standalone Format


A standalone application on Windows is actually a folder containing Max Runtime executable plus a .mxf collective file
containing your patches and files. In addition, the standalone folder contains a support folder with files necessary to run
your application.

Jitter Shader
To include Jitter shader components in your standalone application:

Copy the file /Program Files/Common Files/Cycling '74/jitter-shaders to {standalone folder}/support/jitter-shaders

Copy the file /Program Files/Cycling '74/Max 6/support/cg.dll to {standalone folder}/support/cg.dll

Copy the file /Program Files/Cycling '74/Max 6/support/cgGL.dll to {standalone folder}/support/cgGL.dll

Java
To include Java components in your standalone application:

Copy the file /Program Files/Common Files/Cycling '74/java/lib/max.jar to {standalone folder}/support/java/lib/max.jar

Copy any other necessary jar files (e.g. jitter.jar) to {standalone folder}/support/java/lib/max.jar

Copy /Program Files/Common Files/Cycling '74/java/classes/*.class to {standalone folder}/support/java/classes/*.class


(all your necessary class files)

Javascript
To include Javascript components in your standalone application:

Copy the file /Program Files/Cycling '74/Max 6/support/js32mt.dll to {standalone folder}/support/js32mt.dll

Copy the file /Program Files/Common Files/Cycling '74/jsextensions/ to {standalone folder}/support/jsextensions/

Macintosh Standalone Format


On Macintosh, the standalone is an application package, which is also a folder that looks like a file in the Finder. You can
peek into the package by control-clicking on it and choosing Show Package Contents from the contextual menu. As with the
Windows standalone, inside the Contents/MacOS folder you will find a .mxf collective, a runtime application, and a support
folder.

Jitter shader
To include Jitter shader components in your standalone application:

Copy the file /Applications/Max6/Cycling '74/jitter-externals/Cg.framework to


{Package}/Contents/MacOS/support/Cg.framework

Copy the file /Applications/Max6/Cycling '74/jitter-shaders to {Package}/Contents/MacOS/support/jitter-shaders

Java
To include Java components in your standalone application:

Copy the file /Applications/Max6/Cycling '74/java/lib/max.jar to {Package}/Contents/MacOS/support/java/lib/max.jar

Copy any other necessary jar files (e.g. jitter.jar) to {Package}/Contents/MacOS/support/java/lib/

Copy /Applications/Max6/Cycling '74/java/classes/*.class to {Package}/Contents/MacOS/support/java/classes/*.class (all


your necessary class files)

Javascript
To include Javascript components in your standalone application:

Copy the file /Library/CFMSupport/JSRefThreadsafe.shlb to {Package}/Contents/MacOS/JSRefThreadsafe.shlb

Copy the file /Applications/Max6/Cycling '74/jsextensions/ to {Package}/Contents/MacOS/support/jsextensions/


For Your Further Reading Pleasure
Jitter Bibliography: For Your Further Reading Pleasure
Jitter Reference List
The following is a list of books, articles, and web sites you might find helpful for learning more about different Jitter-related
topics.

Video
Jim Blinn, Jim Blinn's Corner: Dirty Pixels (San Francisco: Morgan Kaufmann, 1998). ISBN: 1558604553

An excellent introduction to a diverse array of topics including analog and digital video formats, aliasing, compositing,
tensor arithmetic, and the world's largest Easter Egg.

A. Bovik et al., Handbook of Image and Video Processing (San Diego: Academic Press, 2000). ISBN: 0121197921

Richard Rickitt, Special Effects: The History and Technique (London: Virgin Books, 2000). ISBN: 1852278005

A very readable introduction to the history and technology of special effects in film.

Image Processing
W. K. Pratt, Digital Image Processing (New York: John Wiley and Sons, 2001). ISBN: 0-471-85766-1

A. S. Glassner, Principles of Digital Image Synthesis (San Francisco: Morgan Kaufmann, 1995). ISBN: 1558602763

Video Codecs
Peter Symes, Digital Video Compression (New York: McGraw-Hill, 2003). ISBN: 0071424873

M. Ghanbari, Standard Codecs: Image Compression to Advanced Video Coding (IEEE Publishing: 2004). ISBN:
0852967101

OpenGL and 3D Graphics


D. Schreiner et al., OpenGL Programming Guide (the "Red Book") (Reading: Addison-Wesley, 1999). ISBN: 0321335732

An earlier online version of the Red Book

OpenGL Architecture Review Board, OpenGL Reference Manual (The "Blue Book") (Reading: Addison-Wesley, 1999). ISBN:
0201657651
An earlier online version of the Blue Book

Randi J. Rost , OpenGL Shading Language (aka "The Orange Book") (Reading: Addison-Wesley, 2004). ISBN: 0321197895

An online version of the Orange Book

E. Angel, OpenGL 1.2: A Primer (Reading: Addison-Wesley, 2001). ISBN: 0201741865

David S. Ebert, F. Kenton Musgrave, Darwyn Peachey, Ken Perlin, Steven Worley, Texturing and Modeling: a Procedural
Approach (AP Professional, July 1998). ISBN: 0122287606

This book gives the reader a working knowledge of several procedural texturing, modeling, and animation techniques,
including two-dimensional texturing, solid texturing, hypertextures, volume density functions, and fractal algorithms.
Emphasis is placed on practical applications with many code examples.

A. Watt, 3D Computer Graphics (Essex: Addison-Wesley, 2000). ISBN: 0201398559

Shaders
Graphica Obscura

Randima Fernando, Mark J. Kilgard , Cg Tutorial: The Definitive Guide to Programmable Real-Time Graphics (Reading:
Addison-Wesley, 2003). ISBN: 0321194969

Randima Fernando, GPU Gems: Programming Techniques, Tips, and Tricks for Real-Time Graphics (Reading: Addison-
Wesley, 2004). ISBN: 0321228324

Procedural Texturing and Modeling


Ebert, Musgrave, et. al,, Texturing and Modeling: A Procedural Approach (San Francisco: Morgan Kaufman, 2002). ISBN:
1558608486

Anthony A. Apodaca and Larry Gritz, Advanced RenderMan: Creating CGI for Motion Pictures (San Francisco: Morgan
Kaufman, 1999). ISBN: 1558606181

2D Graphics and Vector Animation


A. S. Glassner et al., Graphics Gems (San Diego: Academic Press, 1990). ISBN: 0122861655

The faqs.org graphics listing

Video Art
Gene Youngblood, Expanded Cinema (New York: Dutton, 1970). ISBN: 0525101527

An overview of "synaesthetic cinema" techniques in film and video with an introduction by R. Buckminster Fuller. Covers
the work of the Whitneys, Carolee Schneeman, Jordan Belson, Stan Brakhage, Nam June Paik, Michael Snow and others.
The first book on video and computer graphics as an art medium. An essential historical connection, unfortunately out of
print.

Generative Art
Craig Reynolds' website (flocking algorithms, etc.)

Linear Algebra and Mathematical Matrix Operations


G. Stephenson, An Introduction to Matrices, Sets, and Groups for Science Students (Toronto: Dover, 1986). ISBN:
0486650774
Topics in Mathematics: Linear and Matrix Algebra

Math Reference Tables of all kinds

Wolfram's Math World

SOS Math - Matrix Algebra

General Programming
David Flanagan, Javascript: The Definitive Guide (Cambridge: OReilly and Associates, 1998). ISBN: 1565923928

Colin Moock, Actionscript for Flash MX: The Definitive Guide (Cambridge: OReilly and Associates, 2001). ISBN:
059600396X

David Flanagan, Java in a Nutshell (Cambridge: OReilly and Associates, 2005). ISBN: 0596007736

Patrick Niemeyer and Jonathan Knudsen, Learning Java (Cambridge: OReilly and Associates, 2005). ISBN: 0596008732

Miscellaneous
Don Ritter, E's for Artists: a handbook for New Media Artists (forthcoming, publisher to be determined.)

Randall Packer and Ken Jordan, eds., Multimedia: From Wagner to Virtual Reality (New York: Norton, 2001). ISBN:
0393049795

Stephen Wolfram, A New Kind of Science (Champaign: Wolfram Media, 2001). ISBN: 1579550088

A wide-ranging exploration of the potential of cellular automata for solving problems in mathematics, biology, and
theoretical physics. Most of the concepts and algorithms illustrated in this book could be easily realized using Jitter.

You might also like