Script References

Script-V2.0
Many procedures and functions have been deprecated in Script-V2.0. The new scripting engine is more in "object oriented" style.

The scripting language is an advanced concept which can be used to turn Usine into a very powerful audio, MIDI and data engine. The language is based on the Pascal programming language.

Structure of a script

Init

This procedure is called when the script is compiled or loaded. It's the place where you initialize inlets/outlet or any variable.

procedure Init;
begin
  // Initialisation code
 input := CreateParam('input',ptDatafader,pioInput);
 input.Min(0);
 input.Max(100);
 input.Symbol('%');
 input.DefaultValue(10);
 input.asFloat(10);  
end;

Destroy

This procedure is called when the script is destroyed.

Inlets/outlet are destroyed automatically so you mustn't destroy them in the Destroy bloc.

procedure Destroy;
begin
  MyStringList.free;
  SetLength(MyArray,0);
end;

Process

This procedure is called on each execution bloc (around 3ms with a normal setup). It's the place where you generally do the calculation.

procedure Process;
var inval : single;
begin
  inval := input.asFloat;
  output.asFloat(inval);     
end;

ProcessThread

This procedure is called in a autonomous realtime thread (not int the Audio thread neither in the IDLE thread) every 10ms. It's the place where you generally asynchronous heavy calculations.

this thread is not synchronized to the audio thread and is not suitable for MIDI processing.

procedure ProcessThread;
var inval : single;
begin
  for i:= 1 to NBVALUES 
  do begin
     inval := input[i].asFloat;
     output[i].asFloat(inval);
  end;
end;

Callback

This procedure is called each time an inlet is modified. The N parameter is the index of the modified inlet.

That allows an optimisation over constant running Process procedure: the code will run only if input changed.

The Callback will scan the inputs from 0 to n and can trigg a specific code when input change is detected.

So if results are supposed to be computed only when input changed, prefer the callback to the process procedure.

However if things need computations at a different bloc time that input changed, still need the process procedure.

For exemple an input change can set to 1 a parameter in callback, but if wanna set this param back to 0 next bloc, (like a 'has chg' behavior) the code to set back to 0 will occur in Process Procedure, unless it's trigg by an input.

You can use either Callback or Process Procedure, or booth simultaneously according to your needs.

The callback is provided at messages rate, typically every 25 or 50ms depending on the setup refresh speed.

To ensure a faster callback (immediately after the inlet has been modified) use the FastCallBack procedure describe bellow.

procedure Init;
begin
  // Initialisation of a fast callback inlet
 input := CreateParam('input',ptDatafader,pioInput);
 input.FastCallBack(true);
end;

procedure Callback(N:integer);
var inval : single;
begin
  if n=input
  then begin
    inval := input.asFloat;
    output.asFloat(inval);     
  end;
end;

ProcessIDLE

This procedure is called at the setup refresh speed (around 25ms or 50ms). It's the place where you do calculation which doesn't need a fast speed, IML or graphic stuffs like SendInternalMsg (see bellow).

procedure ProcessIDLE;
begin
...
end;

Example

Usine contains many examples that you can get in the browser-panel tab /Scripts/Examples/.

//GLOBAL VARIABLES AND TPARAMETER  DECLARATIONS
var input  :TParameter;               
var output :TParameter;                   

//PROCESS                 
PROCEDURE PROCESS();
BEGIN   
  output.asFloat(input.asFloat)
END;                  

//INIT PROCEDURE
PROCEDURE INIT();

BEGIN    
 input:=CreateParam('in',ptDataFader,pioInput);
 output:=CreateParam('out',ptDataFader,pioOutput);  
 ModuleColor($FF8E44AD);              
END;                     

//CALLBACK         
PROCEDURE CALLBACK(N:INTEGER);
BEGIN
  CASE N OF
   input: Begin     
          Trace('input has changed')
          End;
  End;          
END;                              

Declarations

Constants

BlocSize      // size of Usine audio blocs typically 128, see setup/audio
BlocDuration  // duration of a bloc calculation according to the sampling rate 
              // and bloc size, typically 2.9 ms
RefreshSpeed  // refresh speed in ms as defined in the setup, typically 25ms
SamplingRate  // current audio sampling rate, typically 44100

Types

Type TParameter = int32;
Type TAlphaColor= uint32;
type TScale     = (
                  lsLinear,
                  lsLog,
                  lsExp
                  );
type TParamType = (
                   ptTextField, 
                   ptColor,
                   ptMIDI,
                   ptGainFader,
                   ptAudio,
                   ptDataField,
                   ptDataFader,
                   ptButton,
                   ptListBox,
                   ptSwitch,
                   ptArray,
                   ptIpAddress,
                   ptSmpte,
                   ptMIDINoteFader,
                   ptPointerBitMap,
                   ptPointer,
                   ptLed,
                   ptLed,
                   ptChooseFolder,
                   ptRightLed,
                   ptTriggerLed,
                   ptFileName
                   );
type  TParamIOType = (
                   pioInput,          // the parameter is an inlet
                   pioOutput,         // the parameter is an outlet
                   pioBoth,           // the parameter is an inlet and outlet
                   pioNone            // the parameter is not visible in the module
                   ); 

type  TMIDI        = Record
                   Msg   : Byte;
                   Data1 : Byte;
                   Data2 : Byte;
                   Channel : byte;
                   end;

Create Parameters

Parameters must be created in the Init procedure.

// Create a new parameter, 
// returns the parameter's number
function CreateParam    (caption: string; typ: TParamType, ioTyp : TParamIOType ):TParameter; 

procedure TParameter.IsInput   (val: boolean);      // set to true if the parameter has input port
procedure TParameter.IsOutput  (val: boolean);      // set to true if the parameter has output port
procedure TParameter.Scale     (val: TScale);       // set the scale, if the param is a fader
procedure TParameter.Color     (val: TAlphaColor);  // set the front color of the fader or ON Color for switches
procedure TParameter.OffColor  (val: TAlphaColor);  // set the off color only for switches parameters
procedure TParameter.Visible   (val: Boolean);      // determines if the parameter is visible, true by default
procedure TParameter.Min       (val: single);       // set min parameter value
procedure TParameter.Max       (val: single);       // set max parameter value
procedure TParameter.MinMaxNoLimit(val : boolean);  // when set to TRUE the parameter's bounds are not limited 
                                                    //by min/max

procedure TParameter.DefaultValue  (val: single);   // set default param value, when created
procedure TParameter.Caption       (val: string);   // set or change displayed caption 
procedure TParameter.Symbol        (val: string);   // set displayed symbol ie. 'ms','%'
procedure TParameter.Format        (val: string);   // set format string of the displayed value 
                                                    // ie. '%g','%.0f','%.1f'
procedure TParameter.ListBoxString (val: string);   // set listbox items commaText ie.'"item1","item2"'
procedure TParameter.ReadOnly      (val: boolean);  // set to TRUE if the user can't modify value
procedure TParameter.FastCallBack  (val: boolean);  // set to TRUE to use a fast callback instead of the
                                                    // normal queue processing  (25-50 ms)
procedure TParameter.DontSave      (val: boolean);  // specifies if the parameter need to be save 
                                                    // in the patch or not
procedure TParameter.SavedName     (val: string);   // set name which will be used to store the value
                                                    // by default value are stored according 
                                                    // their caption
procedure TParameter.IsSeparator   (val: boolean);  // determines if the parameter is followed by a 
                                                    // blank line in the module's panel

Example of parameters creation

///////////////////////////////////////////////////////////////////
// example of parameters creation
///////////////////////////////////////////////////////////////////
var  pInput, pOutOrder, pMono, pMaxOut : tParameter;
var  pOutput : ARRAY[1..NUM_OUTPUTS] of tParameter;  

procedure init;
var i : Integer;
begin 
   pInput := CreateParam('midi in', ptMidi, pioInput); 

   pOutOrder := CreateParam('out order', ptListBox,pioInput);
   pOutOrder.ListBoxString('"round robin","from first","random","rnd no repeat"');
   outOrder := roundRobin;

   pMono := CreateParam('monophonic', ptSwitch,pioInput); 

   pMaxOut := CreateParam('max out used', ptDataFader,pioInput); 
   pMaxOut.Min(1); 
   pMaxOut.Max(NUM_OUTPUTS); 
   pMaxOut.asInteger(NUM_OUTPUTS);
   pMaxOut.Format('%.0f');

   for i := 1 TO NUM_OUTPUTS do 
   begin
      pOutput[i] := CreateParam('midi out ' + inttostr(i), ptMidi,pioOutput);
   end;      
end;

Access to parameter's Value

float (single) values

procedure TParameter.asFloat(val : single);                       // set the value of a float parameter
function TParameter.asFloat:single;                               // get the value of a float parameter

//example
output.asFloat(sin(input.asFloat));

integer values

procedure TParameter.asInteger(val : integer);               // set the value of an integer parameter
function TParameter.asInteger:integer;                       // get the value of a integer parameter

//example
if listbox.asInteger=-1 
then listbox.asInteger(1);

string values

procedure TParameter.asString(val : string);                 // set the value of a string parameter
function TParameter.asString:string;                         // get the value of a string parameter

//example
if textfield.asString='' 
then listbox.asString('default value string');

MIDI values

procedure TParameter.asMidi(index : integer; val : TMIDI);       // set the value of a MIDI parameter at the index
function TParameter.asMidi(index : integer):TMIDI;               // get the value of a MIDI parameter at the index

nbOfMidi := input.Length;  // get the number of incoming midi codes  
output.length(nbOfMidi);

if nbOfMidi > 0 
then begin           
   transpoVal := trunc(transpo.asInteger); // get the transpo value    

   for i := 0 to nbOfMidi-1         // loop for all input codes, for polyphonic data (chords)
   do begin
     ReceivedMidi := input.asMidi(i); // get each code
     ReceivedMidi.data1 := ReceivedMidi.data1+transpoVal; // calculate transpo
     output.asMidi(i,ReceivedMidi); // set output value     
   end;
end 

Array values

procedure TParameter.asArray(index : integer; val : single);          // set the value of a float array parameter at the index
function TParameter.asArray(index : integer):single;                  // get the value of a float array parameter at the index

SL1.Create;      
L:= arrayIn.Length;     
For i:= 0 to L-1                                                    
do begin                                   
      s := ArrayIn.asArray(i);                
      SL1.add(FloatToStr(s)); 
end;                          
CommaOut.asString(SL1.GetCommatext);  
SL1.Free

Colors values

procedure TParameter.asColor(val : TAlphaColor); // set the value of a float parameter
function TParameter.asColor:TAlphaColor;         // get the value of a float parameter

col := colorIn.asColor;      
// complementary color
col.R(255-col.R);
col.G(255-col.G);
col.B(255-col.B);
colorOut.asColor(col);

Get the length of a values (number of elements)

procedure TParameter.Length(l : integer);                        // set le length of a parameter
function TParameter.Length:integer;                              // get the length of a parameter

L:= arrayIn.Length;     
For i:= 0 to L-1                                                    
do begin                                   
      s := ArrayIn.asArray(i);                
      trace(s); 
end;                          

various boolean functions

function TParameter.equal1:boolean;                              // returns true if a parameter's value equal 1
function TParameter.equal0:boolean;                              // returns true if a parameter's value equal 0

if switch.equal1
then trace('on');
if switch.equal0
then trace('off');

Global functions and procedures

Trace Values

To display informations in the trace-panel.

procedure Trace(S:string; Value:variant);  
procedure Trace(S:string);  
procedure Trace(I:Integer); 
procedure Trace(F:single);  

Module color

Procedure ModuleColor(Color:TAlphaColor);    // set the color of the module
                                             // as it is displayed in the patch

Example of module's color (red and blue) inside a patch.

SMPTE and Markers Position.

function GetSmptePos:double;
procedure SetSmptePos (pos:double);
function GetLoopMarkerPos (N:integer):double; // N from 0 to nbMarkers-1

Dynamic Array's or String Length Manipulation

function getarraylength (arr :array: integer;
procedure setarraylength(arr :array; len:integer);

Usine Internal Messages (IML)

SendUsineMsg(msg:string); 
SendUsineMsg(msg,arg1:string);
SendUsineMsg(msg,arg1,arg2:string);
SendUsineMsg(msg,arg1,arg2,arg3:string);
SendUsineMsg(msg,arg1,arg2,arg3,arg4:string);   
SendUsineMsg(msg,arg1,arg2,arg3,arg4,arg6:string);

function GetVariableString(name:string):string;
function GetVariableInteger(name:string):integer;
function GetVariableFloat(name:string):double;

The SendInternalMsg script command should not be executed in the process procedure context.

You can use safely it in the processIDLE procedure. In the callback procedure set SetFastCallBack(false); to asynchronously execute the callback function that contains the SendUsineMsg calls in the Usine IDLE processing thread instead of the process thread. Otherwise IML calls might lead to undefined behavior (function might not be executed, Usine crashes, etc.)

// example
SendInternalMsg2('SET-TARGET-PATCH','SENDER-PATCH');
SendInternalMsg4 ('GET-VALUE',GetStringValue(Input1),GetStringValue(Input2),'THEPARAMVALUE');
SendInternalMsg3 ('SET-VALUE','PARAM','1','THEPARAMVALUE');
SendInternalMsg4('SET-VALUE',GetStringValue(Input1),GetStringValue(Input2),FloatTostr(GetValue(Input3)));

StringList

  function TStringList.create:TStringList; 
  function TStringList.GetCommaText:String;
  procedure TStringList.SetCommaText(Comma:string);
  procedure TStringList.Sort;
  procedure TStringList.SaveToFile(FileName:string);   // If no path is specified for the file; will default to the last location saved/opened in Usine. 
  procedure TStringList.LoadFromFile(FileName:string); // If no path is specified for the file; will default to the last location saved/opened in Usine.
  procedure TStringList.clear;
  procedure TStringList.free;
  function TStringList.getstrings(index:integer):String;
  procedure TStringList.setstrings(index:integer;value:String);
  procedure TStringList.add(value:String);
  procedure TStringList.delete(index:integer);  // Deletes the string at the index
  procedure TStringList.delete(value:integer);  // Deletes the value if it exists
  function TStringList.indexOf(value:string):integer;
  function TStringList.count:integer;
  function TStringList.Getcount:integer;
// example
procedure ReadTextFile;
begin
  st.create;              
  st.clear;          
  st.loadfromFile(fname.asString);
  textOut.asString(st.GetCommaText);
  st.free;          
end;  

// example
procedure SaveToTextFile;
begin                    
  st.create;                          
  st.setcommaText(input.asString);    
  st.SaveToFile(folder.asString+pathdelim+fname.asString);
  st.free;       
end;    

// example
st.create;      
L:= arrayIn.Length;     
For i:= 0 to L-1                                                    
do begin                                   
  s := ArrayIn.asArray(i);                
  SL1.add(FloatToStr(s)); 
end;                          
CommaOut.asString(SL1.GetCommatext);   
st.free;

Math functions

  Function minS(const A,B:single):Single;
  Function MaxS(const A,B: Single): Single;
  Function maxI(const A,B:integer):integer;
  Function minI(const A,B:integer):integer;

  Function Pi   : Extended;
  Function Log  (e: Extended) : Extended;
  Function Exp  (e: Extended) : Extended;) : Extended;
  Function Arctan   (e: Extended) : Extended;
  Function Arcsin   (e: Extended) : Extended;
  Function Arccos   (e: Extended) : Extended;
  function Abs(d: Extended): Extended;
  function Abs(d: Int64): Int64;
  function Power(Base, Exponent: Extended): Extended;
  function Sqr(d: Extended): Extended;
  function Sqrt(d: Extended): Extended;
  function ArcTan(d: Extended): Extended;
  function Ln(d: Extended): Extended;
  function Sin(d: Extended): Extended;
  function Cos(d: Extended): Extended;
  function Exp(d: Extended): Extended;
  function Round(d: Extended): Int64;
  function Round(d: Extended; Precision: Int8): Extended;
  function Frac(d: Extended): Extended;
  function Int(d: Extended): Extended;
  function Trunc(d: Extended): Int64;
  function Ceil(d: Extended): Int64;
  function Floor(d: Extended): Int64;

  function Random(Min, Max: Int64): Int64;
  function Random(l: Int64): Int64;
  function Random: Extended;
  procedure Randomize;

Date and Time functions


var
  HoursPerDay,
  MinsPerHour,
  SecsPerMin,
  MSecsPerSec,
  MinsPerDay,
  SecsPerDay,
  MSecsPerDay,
  DateDelta;

type
  TDateTime : double;
  TTime : double;

  function EncodeDate(Year, Month, Day: UInt16): TDateTime;
  function EncodeTime(Hour, Min, Sec, MSec: UInt16): TDateTime;
  procedure DecodeDate(DateTime: TDateTime; var Year, Month, Day: UInt16);
  function DecodeDateFully(DateTime: TDateTime; var Year, Month, Day, DOW: UInt16): Boolean;
  procedure DecodeTime(DateTime: TDateTime; var Hour, Min, Sec, MSec: UInt16);

  function Date: TDateTime;
  function Time: TDateTime;
  function Now: TDateTime;

  function GetTickCount: UInt32;
  procedure Sleep(MilliSeconds: UInt32);

  procedure ReplaceTime(var DateTime: TDateTime; NewTime: TDateTime);
  procedure ReplaceDate(var DateTime: TDateTime; NewDate: TDateTime);
  function DateTimeInRange(ADateTime: TDateTime; AStartDateTime, AEndDateTime: TDateTime): Boolean;
  function FormatDateTime(Format: string; DateTime: TDateTime): string;
  function StrToDate(s: string): TDateTime;
  function StrToDateDef(s: string; Default: TDateTime): TDateTime;
  function StrToTime(s: string): TDateTime;
  function StrToTimeDef(s: string; Default: TDateTime): TDateTime;
  function StrToDateTime(s: string): TDateTime;
  function StrToDateTimeDef(s: string; Default: TDateTime): TDateTime;

File names functions

  // File Names
  function  ExtractFileName(filename:String):string;
  function  ExtractFileDir(filename:String):string;
  function  ExtractFileExt(filename:String):string;
  function  SubFileExt(filename:String):string;
  function  PathDelim:string; // returns '/' on MACOS, '\' on windows
  procedure CreateDir(dir:String);
  function  GetApplicationPath:string; //give the absolute path of the current Usine's folder

Strings functions

  type TTextLineBreakStyle  = (tlbsLF, tlbsCRLF, tlbsCR);
  type TReplaceFlags = set of (rfReplaceAll, rfIgnoreCase);

  function UpperCase(s: string): string;;
  function LowerCase(s: string): string;
  function UpCase(c: AnsiChar): AnsiChar;
  function UpCase(c: WideChar): WideChar;

  function CompareStr(s1, s2: string): Int32;
  function CompareMem(p1, p2: Pointer; Length: PtrUInt): EvalBool;
  function CompareText(s1, s2: string): Int32;
  function SameText(s1, s2: string): EvalBool;

  function  Copy (s: string; ifrom, icount: Longint): string;
  procedure Delete(var s: string; ifrom, icount: Longint);
  procedure Insert(s: string; var s2: string; ipos: Longint): string;
  function  StrGet(var S : String; i : Integer) : Char;
  procedure StrSet(c: Char; I : Integer; var s : String);
  function  Length(s: String) : Longint; 
  procedure SetLength(var S: String; L: Longint); 

  function AnsiUpperCase(s: string): string;
  function AnsiLowerCase(s: string): string;
  function AnsiCompareStr(s1, s2: string): Int32;
  function AnsiCompareText(s1, s2: string): Int32;
  function AnsiSameText(s1,s2:String): EvalBool;
  function AnsiSameStr(s1,s2:String): EvalBool;

  function Trim(s: string): string;
  function TrimLeft(s: string): string;
  function TrimRight(s: string): string;
  function PadL(s: string; Len: SizeInt; c: Char = '' ''): string;
  function PadR(s: string; Len: SizeInt; c: Char = '' ''): string;
  function Padz (s: string;I : longInt) : string; //  Is similar to Padl, but adds zeroes instead of spaces
  function QuotedStr(s: string): string;
  function AnsiQuotedStr(s: string; Quote: Char): string;
  function AnsiDequotedStr(s: string; AQuote: Char): string;

  function WrapText(Line, BreakStr: string; BreakChars: set of AnsiChar; MaxCol: Int32): string;
  function AdjustLineBreaks(s: string; Style: TTextLineBreakStyle): string;

  function IntToHex(Value: Int64; Digits: Int32 = 1): string;
  function IntToHex(Value: UInt64; Digits: Int32 = 1): string;
  function IntToStr(i: Int64): string; overload;
  function IntToStr(i: UInt64): string;
  function StrToInt(s: string): Int32;
  function StrToIntDef(s: string; Def: Int32): Int32;
  function StrToInt64(s: string): Int64;
  function StrToInt64Def(s: string; Def: Int64): Int64;
  function StrToUInt64(s: string): UInt64;
  function StrToUInt64Def(s: string; Def: UInt64): UInt64;
  function FloatToStr(f: Extended): string;
  function StrToFloat(s: string): Extended;
  function StrToFloatDef(s: string; Def: Extended): Extended;
  function CurrToStr(Value: Currency): string;
  function StrToCurr(s: string): Currency;
  function StrToCurrDef(s: string; Def: Currency): Currency;
  function StrToBool(s: string): EvalBool;
  function BoolToStr(B: EvalBool; TrueS: string = ''True''; FalseS: string = ''False''): string;
  function StrToBoolDef(s: string; Default: EvalBool): EvalBool;

  function Format(Fmt: string; Args: array of Variant): string;
  function FormatFloat(Format: string; Value: Extended): string;
  function FormatCurr(Format: string; Value: Currency): string;

  function LastDelimiter(Delimiters, s: string): SizeInt;
  function StringReplace(S, OldPattern, NewPattern: string; Flags: TReplaceFlags): string;
  Function IsDelimiter(Delimiters, s: string; Index: SizeInt): EvalBool;

  function Pos(Substr: string; Source: string): SizeInt;
  function StringOfChar(c: Char; l: SizeInt): string;
  function Replicate(c: char; I : longInt) : string; // Builds a string containing i times the character c

See also

More examples

version 4.1.200905

Edit All Pages