7d76f065a17ef28290e4181f42c84b89d9b0cdbd
[Faustine.git] / interpretor / faust-0.9.47mr3 / documentation / faust-quick-reference-src / chapters / syntax.tex
1 \chapter{\faust syntax}
2
3 This section describes the syntax of \faust. Figure \ref{fig:syntax} gives an overview of the various concepts and where they are defined in this section.
4 %% suggestion Carlos : la figure crée une confusion entre la syructure de la syntaxe et la structure de la section. Faire un autre schema!
5 \begin{figure}[ht!]
6 \centering
7 \includegraphics[scale=0.45]{illustrations/syntax-chart}
8 \caption{Overview of \faust syntax}
9 \label{fig:syntax}
10 \end{figure}
11
12 As we will see, \textit{definitions} and \textit{expressions} have a central role.
13
14 \section{\faust program}
15
16 A \faust program is essentially a list of \textit{statements}. These statements can be \textit{declarations}, \textit{imports}, \textit{definitions} and \textit{documentation tags}, with optional C++ style (//... and /*...*/) comments.
17
18 \begin{rail}
19 program : (statement)+;
20 \end{rail}
21
22 Here is a short \faust program that implements of a simple noise generator. It exhibits various kind of statements : two \textit{declarations}, an \textit{import}, a \textit{comment} and a \textit{definition}. We will see later on \textit{documentation} statements (\ref{sec:documentation}).
23
24 \begin{lstlisting}
25 declare name "noise";
26 declare copyright "(c)GRAME 2006";
27
28 import("music.lib");
29
30 // noise level controlled by a slider
31 process = noise * vslider("volume", 0, 0, 1, 0.1);
32 \end{lstlisting}
33
34 The keyword \lstinline'process' is the equivalent of \lstinline'main' in C/C++. Any \faust program, to be valid, must at least define \lstinline'process'.
35
36
37 \section{Statements}
38
39 The \textit{statements} of a \faust program are of four kinds : \textit{metadata declarations}, \textit{file imports}, \textit{definitions} and \textit{documentation}. All statements but documentation end with a semicolon (\lstinline';').
40 %
41 % \begin{grammar}
42 % <statement> ::=
43 % \begin{syntdiag}
44 % \begin{stack}
45 % <declaration>\\
46 % <fileimport>\\
47 % <definition>\\
48 % <documentation>
49 % \end{stack}
50 % \end{syntdiag}
51 % \end{grammar}
52
53 \begin{rail}
54 statement : declaration | fileimport | definition | documentation;
55 \end{rail}
56
57 \subsection{Declarations}
58
59 Meta-data declarations (for example \lstinline'declare name "noise";') are optional and typically used to document a \faust project.
60
61 % \begin{grammar}
62 % <declaration> ::=
63 % \begin{syntdiag}
64 % "declare" <key> <string> ";"
65 % \end{syntdiag}
66 % \end{grammar}
67 %
68 % \begin{grammar}
69 % <key> ::=
70 % <identifier>
71 % \end{grammar}
72
73 \begin{rail}
74 declaration : "declare" key string ';';
75 key : identifier;
76 \end{rail}
77
78 Contrary to regular comments, these declarations will appear in the C++ code generated by the compiler. A good practice is to start a \faust program with some standard declarations:
79 \begin{lstlisting}
80 declare name "MyProgram";
81 declare author "MySelf";
82 declare copyright "MyCompany";
83 declare version "1.00";
84 declare license "BSD";
85 \end{lstlisting}
86
87
88
89 \subsection{Imports}
90
91 File imports allow to import definitions from other source files.
92
93 % \begin{grammar}
94 % <fileimport> ::=
95 % \begin{syntdiag}
96 % "import" "(" <filename> ")" ";"
97 % \end{syntdiag}
98 % \end{grammar}
99
100 \begin{rail}
101 fileimport : "import" '(' filename ')' ';';
102 \end{rail}
103
104 For example \lstinline{import("math.lib");} imports the definitions of the \lstinline{math.lib} library, a set of additional mathematical functions provided as foreign functions.
105
106
107 \subsection{Documentation}
108 \label{sec:documentation}
109
110 Documentation statements are optional and typically used to control the generation of the mathematical documentation of a \faust program. This documentation system is detailed chapter \ref{chapter:mdoc}. In this section we will essentially describe the documentation statements syntax.
111
112 A documentation statement starts with an opening \lstinline'<mdoc>' tag and ends with a closing \lstinline'</mdoc>' tag. Free text content, typically in \latex format, can be placed in between these two tags.
113
114 % \begin{grammar}
115 % <documentation> ::=
116 % \begin{syntdiag}
117 % "<mdoc>"
118 % \begin{stack}
119 % <free text>\\
120 % <equation>\\
121 % <diagram>\\
122 % <metadata>\\
123 % <notice>\\
124 % <listing>
125 % \end{stack}
126 % "</mdoc>"
127 % \end{syntdiag}
128 % \end{grammar}
129
130 \begin{rail}
131 documentation : "<mdoc>" ((freetext|equation|diagram|metadata|notice|listing)+) "</mdoc>";
132 \end{rail}
133
134
135 Moreover, optional sub-tags can be inserted in the text content itself to require the generation, at the insertion point, of mathematical \textit{equations}, graphical \textit{block-diagrams}, \faust source code \textit{listing} and explanation \textit{notice}.
136
137 % \begin{grammar}
138 % <equation> ::=
139 % \begin{syntdiag}
140 % "<equation>" <expression> "</equation>"
141 % \end{syntdiag}
142 % \end{grammar}
143
144 \begin{rail}
145 equation : "<equation>" expression "</equation>";
146 \end{rail}
147
148 The generation of the mathematical equations of a \faust expression can be requested by placing this expression between an opening \lstinline'<equation>' and a closing \lstinline'</equation>' tag. The expression is evaluated within the lexical context of the \faust program.
149
150 % \begin{grammar}
151 % <diagram> ::=
152 % \begin{syntdiag}
153 % "<diagram>" <expression> "</diagram>"
154 % \end{syntdiag}
155 % \end{grammar}
156
157 \begin{rail}
158 diagram : "<diagram>" expression "</diagram>";
159 \end{rail}
160
161 Similarly, the generation of the graphical block-diagram of a \faust expression can be requested by placing this expression between an opening \lstinline'<diagram>' and a closing \lstinline'</diagram>' tag. The expression is evaluated within the lexical context of the \faust program.
162
163 % \begin{grammar}
164 % <diagram> ::=
165 % \begin{syntdiag}
166 % "<metadata>" <keyword> "</metadata>"
167 % \end{syntdiag}
168 % \end{grammar}
169
170
171 \begin{rail}
172 metadata : "<metadata>" keyword "</metadata>";
173 \end{rail}
174
175
176 The \lstinline'<metadata>' tags allow to reference \faust metadatas (cf. declarations), calling the corresponding keyword.
177
178 % \begin{grammar}
179 % <notice> ::=
180 % \begin{syntdiag}
181 % "<notice />"
182 % \end{syntdiag}
183 % \end{grammar}
184
185 \begin{rail}
186 notice : "<notice />";
187 \end{rail}
188
189 The \lstinline'<notice />' empty-element tag is used to generate the conventions used in the mathematical equations.
190 %
191 % \begin{grammar}
192 % <listing> ::=
193 % \begin{syntdiag}
194 % "<listing "
195 % \begin{stack}
196 % \\
197 % \begin{rep}
198 % <listingattribute>
199 % \end{rep}
200 % \end{stack}
201 % " />"
202 % \end{syntdiag}
203 % \end{grammar}
204
205 \begin{rail}
206 listing : "<listing" (listingattribute*) " />";
207 listingattribute : ("mdoctags" | "dependencies" | "distributed") "=" ('"true"' | '"false"');
208 \end{rail}
209
210
211 % \begin{grammar}
212 % <listingattribute> ::=
213 % \begin{syntdiag}
214 % \begin{stack}
215 % "mdoctags" \\
216 % "dependencies" \\
217 % "distributed"
218 % \end{stack}
219 % "=" "\""
220 % \begin{stack}
221 % "true" \\ "false"
222 % \end{stack}
223 % "\""
224 % \end{syntdiag}
225 % \end{grammar}
226
227 The \lstinline'<listing />' empty-element tag is used to generate the listing of the \faust program. Its three attributes \lstinline'mdoctags', \lstinline'dependencies' and \lstinline'distributed' enable or disable respectively \lstinline'<mdoc>' tags, other files dependencies and distribution of interleaved faust code between \lstinline'<mdoc>' sections.
228
229
230 \section{Definitions}
231
232 A \textit{definition} associates an identifier with an expression it stands for.
233
234 Definitions are essentially a convenient shortcut avoiding to type long expressions. During compilation, more precisely during the evaluation stage, identifiers are replaced by their definitions. It is therefore always equivalent to use an identifier or directly its definition. Please note that multiple definitions of a same identifier are not allowed, unless it is a pattern matching based definition.
235
236 \subsection{Simple Definitions}
237
238 The syntax of a simple definition is:
239
240 \begin{rail}
241 definition : identifier '=' expression ';';
242 \end{rail}
243
244 For example here is the definition of \lstinline'random', a simple pseudo-random number generator:
245
246 \begin{lstlisting}
247 random = +(12345) ~ *(1103515245);
248 \end{lstlisting}
249
250
251 \subsection{Function Definitions}
252
253 Definitions with formal parameters correspond to functions definitions.
254
255 \begin{rail}
256 definition : identifier '(' (parameter + ',') ')' '=' expression ';';
257 \end{rail}
258
259 For example the definition of \lstinline'linear2db', a function that converts linear values to decibels, is :
260
261 \begin{lstlisting}
262 linear2db(x) = 20*log10(x);
263 \end{lstlisting}
264
265 Please note that this notation is only a convenient alternative to the direct use of \textit{lambda-abstractions} (also called anonymous functions). The following is an equivalent definition of \lstinline'linear2db' using a lambda-abstraction:
266
267 \begin{lstlisting}
268 linear2db = \(x).(20*log10(x));
269 \end{lstlisting}
270
271
272 \subsection{Definitions with pattern matching}
273
274 Moreover, formal parameters can also be full expressions representing patterns.
275 \begin{rail}
276 definition : identifier '(' (pattern + ',') ')' '=' expression ';';
277 pattern : identifier | expression;
278 \end{rail}
279
280 This powerful mechanism allows to algorithmically create and manipulate block diagrams expressions. Let's say that you want to describe a function to duplicate an expression several times in parallel:
281 \begin{lstlisting}
282 duplicate(1,x) = x;
283 duplicate(n,x) = x, duplicate(n-1,x);
284 \end{lstlisting}
285
286 Please note that this last definition is a convenient alternative to the more verbose :
287 \begin{lstlisting}
288 duplicate = case {
289 (1,x) => x;
290 (n,x) => duplicate(n-1,x);
291 };
292 \end{lstlisting}
293
294 Here is another example to count the number of elements of a list. Please note that we simulate lists using parallel composition : (1,2,3,5,7,11). The main limitation of this approach is that there is no empty list. Moreover lists of only one element are represented by this element :
295 \begin{lstlisting}
296 count((x,xs)) = 1+count(xs);
297 count(x) = 1;
298 \end{lstlisting}
299
300 If we now write \lstinline'count(duplicate(10,666))' the expression will be evaluated to \lstinline'10'.
301
302 Please note that the order of pattern matching rules matters. The more specific rules must precede the more general rules. When this order is not respected, as in :
303 \begin{lstlisting}
304 count(x) = 1;
305 count((x,xs)) = 1+count(xs);
306 \end{lstlisting}
307 the first rule will always match and the second rule will never be called.
308
309
310
311
312
313 \section{Expressions}
314
315 Despite its textual syntax, \faust is conceptually a block-diagram language. \faust expressions represent DSP block-diagrams and are assembled from primitive ones using various \textit{composition} operations. More traditional \textit{numerical} expressions in infix notation are also possible. Additionally \faust provides time based expressions, like delays, expressions related to lexical environments, expressions to interface with foreign function and lambda expressions.
316
317 \begin{rail}
318 expression : diagram | numerical | time | lexical | foreign | lambda;
319 \end{rail}
320
321 \subsection{Diagram Expressions}
322
323 Diagram expressions are assembled from primitive ones using either binary composition operations or high level iterative constructions.
324
325 \begin{rail}
326 diagramexp : diagcomposition | diagiteration;
327 \end{rail}
328
329 \subsubsection{Diagram composition operations}
330 Five binary \emph{composition operations} are available to combine block-diagrams : \textit{recursion}, \textit{parallel}, \textit{sequential}, \textit{split} and \textit{merge} composition. One can think of each of these composition operations as a particular way to connect two block diagrams.
331
332 \begin{rail}
333 diagcomposition : expression (recur|','|':'|'<:'|':>') expression;
334 \end{rail}
335
336 To describe precisely how these connections are done, we have to introduce some notation. The number of inputs and outputs of a bloc-diagram $A$ are notated $\mathrm{inputs}(A)$ and $\mathrm{outputs}(A)$ . The inputs and outputs themselves are respectively notated : $[0]A$, $[1]A$, $[2]A$, $\ldots$ and $A[0]$, $A[1]$, $A[2]$, etc..
337
338 For each composition operation between two block-diagrams $A$ and $B$ we will describe the connections $A[i]\rightarrow [j]B$ that are created and the constraints on their relative numbers of inputs and outputs.
339
340 The priority and associativity of this five operations are given table \ref{table:composition}.
341
342 \begin{table}[ht]
343 \centering
344 \begin{tabular}{|l|l|l|l|}
345 \hline
346 \textbf{Syntax} & \textbf{Pri.} & \textbf{Assoc.} & \textbf{Description} \\
347 \hline
348 \texttt{\farg{expression}\ $\sim$\ \farg{expression}} & 4 & left & recursive composition \\
349 \texttt{\farg{expression}\ ,\ \farg{expression}} & 3 & right & parallel composition \\
350 \texttt{\farg{expression}\ :\ \farg{expression}} & 2 & right & sequential composition \\
351 \texttt{\farg{expression}\ <:\ \farg{expression}} & 1 & right & split composition \\
352 \texttt{\farg{expression}\ :>\ \farg{expression}} & 1 & right & merge composition \\
353 \hline
354 \end{tabular}
355 \caption{Block-Diagram composition operation priorities}
356 \label{table:composition}
357 \end{table}
358
359
360
361
362 \paragraph{Parallel Composition}
363 The \emph{parallel composition} \lstinline'(A,B)' (figure \ref{figure:par1}) is probably the simplest one. It places the two block-dia\-grams one on top of the other, without connections. The inputs of the resulting block-diagram are the inputs of \lstinline$A$ and \lstinline$B$. The outputs of the resulting block-diagram are the outputs of \lstinline$A$ and \lstinline$B$.
364
365 \emph{Parallel composition} is an associative operation : \lstinline$(A,(B,C))$ and \lstinline$((A,B),C)$ are equivalents. When no parenthesis are used : \lstinline'A,B,C,D', \faust uses right associativity and therefore build internally the expression \lstinline$(A,(B,(C,D)))$. This organization is important to know when using pattern matching techniques on parallel compositions.
366
367 \begin{figure}[h]
368 \centering
369 \includegraphics[scale=0.7]{images/par1}
370 \caption{Example of parallel composition \lstinline'(10,*)'}
371 \label{figure:par1}
372 \end{figure}
373
374
375 \paragraph{Sequential Composition}
376 The \emph{sequential composition} \lstinline$A:B$ (figure \ref{figure:seq1}) expects:
377 \begin{equation}
378 \mathrm{outputs}(A)=\mathrm{inputs}(B)
379 \end{equation}
380 It connects each output of $A$ to the corresponding input of $B$:
381 \begin{equation}
382 A[i]\rightarrow[i]B
383 \end{equation}
384
385 \begin{figure}[h]
386 \centering
387 \includegraphics[scale=0.7]{images/seq1}
388 \caption{Example of sequential composition \lstinline'((*,/):+)' }
389 \label{figure:seq1}
390 \end{figure}
391
392 \emph{Sequential composition} is an associative operation : \lstinline$(A:(B:C))$ and \lstinline$((A:B):C)$ are equivalents. When no parenthesis are used, like in \lstinline$A:B:C:D$, \faust uses right associativity and therefore build internally the expression \lstinline$(A:(B:(C:D)))$.
393
394 \paragraph{Split Composition}
395 The \emph{split composition} \lstinline$A<:B$ (figure \ref{figure:split1}) operator is used to distribute the outputs
396 of $A$ to the inputs of $B$.
397
398 \begin{figure}[h]
399 \centering
400 \includegraphics[scale=0.7]{images/split1}
401 \caption{example of split composition \lstinline'((10,20) <: (+,*,/))'}
402 \label{figure:split1}
403 \end{figure}
404
405 For the operation to be valid the number of inputs of $B$ must be a multiple of the number of outputs of $A$ : \begin{equation}
406 \mathrm{outputs}(A).k=\mathrm{inputs}(B) \end{equation}
407 Each input $i$ of $B$ is connected to the output $i \bmod k$ of $A$ :
408 \begin{equation}
409 A[i \bmod k]\rightarrow\ [i]B \end{equation}
410
411
412 \paragraph{Merge Composition}
413 The \emph{merge composition} \lstinline$A:>B$ (figure \ref{figure:merge1}) is the dual of the \emph{split composition}. The number of outputs of $A$ must be a multiple of the number of inputs of $B$ :
414 \begin{equation}
415 \mathrm{outputs}(A)=k.\mathrm{inputs}(B) \end{equation}
416 Each output $i$ of $A$ is connected to the input $i \bmod k$ of $B$ :
417 \begin{equation}
418 A[i]\rightarrow\ [i \bmod k]B \end{equation}
419 The $k$ incoming signals of an input of $B$ are summed together.
420
421 \begin{figure}[h]
422 \centering
423 \includegraphics[scale=0.7]{images/merge1}
424 \caption{example of merge composition \lstinline'((10,20,30,40) :> *)'}
425 \label{figure:merge1}
426 \end{figure}
427
428
429 \paragraph{Recursive Composition}
430 The \emph{recursive composition} \lstinline'A~B' (figure \ref{figure:rec1}) is used to create cycles in the block-diagram in order to express recursive computations. It is the most complex operation in terms of connections.
431
432 To be applicable it requires that :
433 \begin{equation}
434 \mathrm{outputs}(A) \geq \mathrm{inputs}(B) and \mathrm{inputs}(A) \geq \mathrm{outputs}(B) \end{equation}
435 Each input of $B$ is connected to the corresponding output of $A$ via an implicit 1-sample delay :
436 \begin{equation}
437 A[i]\stackrel{Z^{-1}}{\rightarrow}[i]B
438 \end{equation}
439 and each output of $B$ is connected to the corresponding input of $A$:
440 \begin{equation}
441 B[i]\rightarrow [i]A
442 \end{equation}
443
444 The inputs of the resulting block diagram are the remaining unconnected inputs of $A$. The outputs are all the outputs of $A$.
445
446 \begin{figure}[h]
447 \centering
448 \includegraphics[scale=0.7]{images/rec1}
449 \caption{example of recursive composition \lstinline'+(12345) ~ *(1103515245)'}
450 \label{figure:rec1}
451 \end{figure}
452
453
454
455
456 %Let's see these composition operations in action with two simple examples (figure \ref{fig:integrator}).
457
458 %The first example uses the recursive composition operator (\lstinline'~'). It is an integrator \lstinline'process = +~_;' that produces an output signal $Y$ such that $Y(t)=X(t)+Y(t-1)$.
459
460 %\begin{figure}[t]
461 % \centering
462 % \begin{tabular}{ccc}
463 % \includegraphics[scale=0.7]{illustrations/integrator}&
464 % \includegraphics[scale=0.7]{illustrations/ms}
465 % \end{tabular}
466 % \caption{a) integrator, b) mid/side stereo matrix}
467 % \label{fig:integrator}
468 %\end{figure}
469
470
471 %The second example uses the parallel (\lstinline',') and split (\lstinline'<:') composition operators. It implements a Mid/Side stereophonic matrix: \lstinline'process = _,_<:+,-;' that produces two output signals $Y_0$ and $Y_1$ such that $Y_0(t)=X_0(t)+X_1(t)$ and $Y_1(t)=X_0(t)-X_1(t)$
472
473
474 \subsubsection{Iterations}
475 Iterations are analogous to \lstinline'for(...)' loops and provide a convenient way to automate some complex block-diagram constructions.
476
477 % \begin{grammar}
478 % <diagiteration> ::=
479 % \begin{syntdiag}
480 % \begin{stack}
481 % "par" "(" <ident> "," <numiter> "," <expression> ")"\\
482 % "seq" "(" <ident> "," <numiter> "," <expression> ")"\\
483 % "sum" "(" <ident> "," <numiter> "," <expression> ")"\\
484 % "prod" "(" <ident> "," <numiter> "," <expression> ")"
485 % \end{stack}
486 % \end{syntdiag}
487 % \end{grammar}
488
489 \begin{rail}
490 diagiteration: "par" '(' ident ',' numiter ',' expression ')'
491 | "seq" '(' ident ',' numiter ',' expression ')'
492 | "sum" '(' ident ',' numiter ',' expression ')'
493 | "prod" '(' ident ',' numiter ',' expression ')';
494 \end{rail}
495
496 The following example shows the usage of \lstinline'seq' to create a 10-bands filter:
497
498 \begin{lstlisting}
499 process = seq(i, 10,
500 vgroup("band %i",
501 bandfilter( 1000*(1+i) )
502 )
503 );
504 \end{lstlisting}
505
506
507
508 \begin{rail}
509 numiter : expression;
510 \end{rail}
511 The number of iterations must be a constant expression.
512
513
514 \subsection{Numerical Expressions}
515
516 Numerical expressions are essentially syntactic sugar allowing to use a familiar infix notation to express mathematical expressions, bitwise operations and to compare signals. Please note that is this section only built-in primitives with an infix syntax are presented. A complete description of all the build-ins is available in the primitive section (see \ref{primitives}).
517
518 \begin{rail}
519 numerical : math | bitwise | comparison;
520 \end{rail}
521
522 \subsubsection{Mathematical expressions} are the familiar 4 operations as well as the modulo and power operations
523 \begin{rail}
524 math : expression ('+'|'-'|'*'|'/'|'\%'|hat) expression;
525 \end{rail}
526
527
528 \subsubsection{Bitwise expressions} are the boolean operations and the left and right arithmetic shifts.
529
530 \begin{rail}
531 bitwise : expression (pipe|ampersand|'xor'|'<<' |'>>') expression;
532 \end{rail}
533
534 \subsubsection{Comparison} operations allow to compare signals and result in a boolean signal that is 1 when the condition is true and 0 when the condition is false.
535
536 \begin{rail}
537 comparison : expression ('<'|'<='|'>'|'>='|'=='|'!=') expression;
538 \end{rail}
539
540
541
542 \subsection{Time expressions}
543
544 Time expressions are used to express delays. The notation \lstinline'X@10' represent the signal \lstinline'X' delayed by 10 samples. The notation \lstinline"X'" represent the signal X delayed by one sample and is therefore equivalent to \lstinline'X@1'.
545
546 \begin{rail}
547 time : expression arobase expression|expression kot;
548 \end{rail}
549
550 The delay don't have to be fixed, but it must be positive and bounded. The values of a slider are perfectly acceptable as in the following example:
551
552 \begin{lstlisting}
553 process = _ @ hslider("delay",0, 0, 100, 1);
554 \end{lstlisting}
555
556 \subsection{Environment expressions}
557 \faust is a lexically scoped language. The meaning of a \faust expression is determined by its context of definition (its lexical environment) and not by its context of use.
558
559 To keep their original meaning, \faust expressions are bounded to their lexical environment in structures called \textit{closures}. The following constructions allow to explicitly create and access such environments. Moreover they provide powerful means to reuse existing code and promote modular design.
560
561 % \begin{grammar}
562 % <envexp> ::=
563 % \begin{syntdiag}
564 % \begin{stack}
565 % <expression> "with" "\{"
566 % \begin{rep}
567 % <definition>
568 % \end{rep}
569 % "\}" \\
570 % "environment" "\{"
571 % \begin{rep}
572 % <definition>
573 % \end{rep}
574 % "\}" \\
575 % <expression> "." <ident> \\
576 % "library" "(" <filename> ")" \\
577 % "component" "(" <filename> ")" \\
578 % <expression> "["
579 % \begin{rep}
580 % <definition>
581 % \end{rep}
582 % "]"
583 % \end{stack}
584 % \end{syntdiag}
585 % \end{grammar}
586
587
588
589 \begin{rail}
590 envexp : expression 'with' lbrace (definition+) rbrace
591 | 'environment' lbrace (definition+) rbrace
592 | expression '.' ident
593 | 'library' '(' filename ')'
594 | 'component' '(' filename ')'
595 | expression '[' (definition+) ']';
596 \end{rail}
597
598 \subsubsection{With}
599 The \lstinline'with' construction allows to specify a \textit{local environment}, a private list of definition that will be used to evaluate the left hand expression
600
601 % \begin{grammar}
602 % <withexpression> ::=
603 % \begin{syntdiag}
604 % <expression> "with" "\{"
605 % \begin{rep}
606 % <definition>
607 % \end{rep}
608 % "\}"
609 % \end{syntdiag}
610 % \end{grammar}
611
612 \begin{rail}
613 withexpression : expression 'with' lbrace (definition+) rbrace;
614 \end{rail}
615
616
617 In the following example :
618 \begin{lstlisting}
619 pink = f : + ~ g with {
620 f(x) = 0.04957526213389*x
621 - 0.06305581334498*x'
622 + 0.01483220320740*x'';
623 g(x) = 1.80116083982126*x
624 - 0.80257737639225*x';
625 };
626 \end{lstlisting}
627 the definitions of \lstinline'f(x)' and \lstinline'g(x)' are local to \lstinline'f : + ~ g'.
628
629 Please note that \lstinline'with' is left associative and has the lowest priority:
630 \begin{itemize}
631 \item[-] \lstinline'f : + ~ g with {...}' is equivalent to \lstinline'(f : + ~ g) with {...}'.
632 \item[-] \lstinline'f : + ~ g with {...} with {...}' is equivalent to \lstinline'((f : + ~ g) with {...}) with {...}'.
633 \end{itemize}
634
635 \subsubsection{Environment}
636
637 The \lstinline'environment' construction allows to create an explicit environment. It is like a \lstinline'with', but without the left hand expression. It is a convenient way to group together related definitions, to isolate groups of definitions and to create a name space hierarchy.
638
639 % \begin{grammar}
640 % <environment> ::=
641 % \begin{syntdiag}
642 % "environment" "\{"
643 % \begin{rep}
644 % <definition>
645 % \end{rep}
646 % "\}"
647 % \end{syntdiag}
648 % \end{grammar}
649
650 \begin{rail}
651 environment : 'environment' lbrace (definition+) rbrace;
652 \end{rail}
653
654 In the following example an \lstinline'environment' construction is used to group together some constant definitions :
655
656 \begin{lstlisting}
657 constant = environment {
658 pi = 3.14159;
659 e = 2,718 ;
660 ...
661 };
662 \end{lstlisting}
663 The \lstinline'.' construction allows to access the definitions of an environment (see next paragraph).
664
665 \subsubsection{Access}
666 Definitions inside an environment can be accessed using
667 the '.' construction.
668
669 % \begin{grammar}
670 % <access> ::=
671 % \begin{syntdiag}
672 % <expression> "." <ident>
673 % \end{syntdiag}
674 % \end{grammar}
675
676 \begin{rail}
677 access : expression '.' ident;
678 \end{rail}
679
680 For example \lstinline'constant.pi' refers to the definition of \lstinline'pi' in the above \lstinline'constant' environment.
681
682 Please note that environment don't have to be named. We could have written directly
683 \lstinline'environment{pi = 3.14159; e = 2,718;....}.pi'
684
685
686
687 \subsubsection{Library}
688 The \lstinline'library' construct allows to create an environment by reading the definitions from a file.
689
690 \begin{rail}
691 library : 'library' '(' filename ')';
692 \end{rail}
693
694 For example \lstinline'library("filter.lib")' represents the environment
695 obtained by reading the file "filter.lib". It works like \lstinline'import("filter.lib")' but all the read definitions are stored in a new separate lexical environment. Individual definitions can be accessed as described in the previous paragraph. For example \lstinline'library("filter.lib").lowpass' denotes the function \lstinline'lowpass' as defined in the file \lstinline'"filter.lib"'.
696
697 To avoid name conflicts when importing libraries it is recommended to prefer \lstinline'library' to \lstinline'import'. So instead of :
698
699 \begin{lstlisting}
700 import("filter.lib");
701 ...
702 ...lowpass....
703 ...
704 };
705 \end{lstlisting}
706 the following will ensure an absence of conflicts :
707 \begin{lstlisting}
708 fl = library("filter.lib");
709 ...
710 ...fl.lowpass....
711 ...
712 };
713 \end{lstlisting}
714
715
716
717
718 \subsubsection{Component}
719 The \lstinline'component(...)' construction allows to reuse a full \faust program as a simple expression.
720
721 \begin{rail}
722 component : 'component' '(' filename ')';
723 \end{rail}
724
725 For example \lstinline'component("freeverb.dsp")' denotes the signal processor defined in file "freeverb.dsp".
726
727 Components can be used within expressions like in:
728 \begin{lstlisting}
729 ...component("karplus32.dsp"):component("freeverb.dsp")...
730 \end{lstlisting}
731
732 Please note that \lstinline'component("freeverb.dsp")' is equivalent to \lstinline'library("freeverb.dsp").process'.
733
734
735 \subsubsection{Explicit substitution}
736
737 Explicit substitution can be used to customize a component or any expression with a lexical environment by replacing some of its internal definitions, without having to modify it.
738
739 % \begin{grammar}
740 % <explicitsubst> ::=
741 % \begin{syntdiag}
742 % <expression> "["
743 % \begin{rep}
744 % <definition>
745 % \end{rep}
746 % "]"
747 % \end{syntdiag}
748 % \end{grammar}
749
750 \begin{rail}
751 explicitsubst : expression "[" (definition+) "]";
752 \end{rail}
753
754 For example we can create a customized version of \lstinline'component("freeverb.dsp")', with a different definition of \lstinline'foo(x)', by writing :
755 \begin{lstlisting}
756 ...component("freeverb.dsp")[foo(x) = ...;]...
757 };
758 \end{lstlisting}
759
760
761 \subsection{Foreign expressions}
762
763 Reference to external C \textit{functions}, \textit{variables} and \textit{constants} can be introduced using the \textit{foreign function} mechanism.
764
765 \begin{rail}
766 foreignexp : 'ffunction' '(' signature ',' includefile ',' comment ')'
767 | 'fvariable' '(' type identifier ',' includefile ')'
768 | 'fconstant' '(' type identifier ',' includefile ')' ;
769 \end{rail}
770
771
772 \subsubsection{ffunction}
773 An external C function is declared by indicating its name and signature as well as the required include file.
774 The file \lstinline'"math.lib"' of the \faust distribution contains several foreign function definitions, for example the inverse hyperbolic sine function \lstinline'asinh':
775
776 \begin{lstlisting}
777 asinh = ffunction(float asinhf (float), <math.h>, "");
778 \end{lstlisting}
779
780 Foreign functions with input parameters are considered pure math functions. They are therefore considered free of side effects and called only when their parameters change (that is at the rate of the fastest parameter).
781
782 Exceptions are functions with no input parameters. A typical example is the C \lstinline'rand()' function. In this case the compiler generate code to call the function at sample rate.
783
784
785 \subsubsection{signature}
786 The signature part (\lstinline'float asinhf (float)' in our previous example) describes the prototype of the C function : return type, function name and list of parameter types.
787
788 \begin{rail}
789 signature : type identifier '(' (type + ',') ')';
790 \end{rail}
791
792
793 \subsubsection{types}
794 Note that currently only numerical functions involving simple int and float parameters are allowed. No vectors, tables or data structures can be passed as parameters or returned.
795
796 \begin{rail}
797 type : 'int'|'float';
798 \end{rail}
799
800 \subsubsection{variables and constants}
801 External variables and constants can also be declared with a similar syntax. In the same \lstinline'"math.lib"' file we can found the definition of the sampling rate constant \lstinline'SR' and the definition of the block-size variable \lstinline'BS' :
802
803 \begin{lstlisting}
804 SR = fconstant(int fSamplingFreq, <math.h>);
805 BS = fvariable(int count, <math.h>);
806 \end{lstlisting}
807
808 Foreign constants are not supposed to vary. Therefore expressions involving only foreign constants are only computed once, during the initialization period.
809
810 Variable are considered to vary at block speed. This means that expressions depending of external variables are computed every block.
811
812
813 \subsubsection{include file}
814 In declaring foreign functions one as also to specify the include file. It allows the \faust compiler to add the corresponding \lstinline'#include...' in the generated code.
815
816
817 \begin{rail}
818 includefile : '<' (char+) '>' | '"' (char+) '"' ;
819 \end{rail}
820
821
822
823 %The syntax of these foreign declarations is the following :
824 %The foreign function mechanism allows to use external functions, variables and constants. External functions are limited to numerical ones.
825 %
826
827 %\begin{lstlisting}
828 %process = ffunction(float toto (), "foo.h", "commentaire");
829 %\end{lstlisting}
830
831
832 %ffunction are pure math unless no params
833 %difference between fconstant and fvariable
834
835 %\begin{lstlisting}
836 %SR = fconstant(int fSamplingFreq, <math.h>);
837 %BS = fvariable(int count, <math.h>);
838 %\end{lstlisting}
839
840 %\begin{rail}
841 %includefile : '<' (char+) '>' | string;
842
843 %signature : type identifier '(' (type + ',') ')';
844
845 %type : 'int'|'float';
846 %\end{rail}
847
848 %that take simple numerical parameters and return a number.
849 %Foreign functions, variables and constants. Example of foreign function expression : \lstinline'ffunction (float acoshf (float), <math.h>, "")'.
850
851 \subsection{Applications and Abstractions}
852
853 \textit{Abstractions} and \textit{applications} are fundamental programming constructions directly inspired by the Lambda-Calculus. These constructions provide powerful ways to describe and transform block-diagrams algorithmically.
854
855 % \begin{grammar}
856 % <progexp> ::=
857 % \begin{syntdiag}
858 % \begin{stack}
859 % <abstraction> \\ <application>
860 % \end{stack}
861 % \end{syntdiag}
862 % \end{grammar}
863
864 \begin{rail}
865 progexp : abstraction|application;
866 \end{rail}
867
868 \subsubsection{Abstractions}
869
870 Abstractions correspond to functions definitions and allow to generalize a block-diagram by \textit{making variable} some of its parts.
871
872 % \begin{grammar}
873 % <abstraction> ::=
874 % \begin{syntdiag}
875 % \begin{stack}
876 % <lambdaabstraction> \\ <patternabstraction>
877 % \end{stack}
878 % \end{syntdiag}
879 % \end{grammar}
880 %
881 % \begin{grammar}
882 % <lambdaabstraction> ::=
883 % \begin{syntdiag}
884 % "\\" "("
885 % \begin{rep}
886 % <ident> \\ ","
887 % \end{rep}
888 % ")" "." "(" <expression> ")"
889 % \end{syntdiag}
890 % \end{grammar}
891
892 \begin{rail}
893 abstraction : lambdaabstraction | patternabstraction;
894
895 lambdaabstraction : backslash '(' (ident + ',') ')' '.' '(' expression ')';
896 \end{rail}
897
898 Let's say you want to transform a stereo reverb, \lstinline'freeverb' for instance, into a mono effect. You can write the following expression:
899 \begin{lstlisting}
900 _ <: freeverb :> _
901 \end{lstlisting}
902 The incoming mono signal is splitted to feed the two input channels of the reverb, while the two output channels of the reverb are mixed together to produce the resulting mono output.
903
904 Imagine now that you are interested in transforming other stereo effects. It can be interesting to generalize this principle by making \lstinline'freeverb' a variable:
905 \begin{lstlisting}
906 \(freeverb).(_ <: freeverb :> _)
907 \end{lstlisting}
908
909 The resulting abstraction can then be applied to transform other effects. Note that if \lstinline'freeverb' is a perfectly valid variable name, a more neutral name would probably be easier to read like:
910 \begin{lstlisting}
911 \(fx).(_ <: fx :> _)
912 \end{lstlisting}
913
914 Moreover it could be convenient to give a name to this abstraction:
915 \begin{lstlisting}
916 mono = \(fx).(_ <: fx :> _);
917 \end{lstlisting}
918
919 Or even use a more traditional, but equivalent, notation:
920 \begin{lstlisting}
921 mono(fx) = _ <: fx :> _;
922 \end{lstlisting}
923
924
925
926
927 \subsubsection{Applications}
928 Applications correspond to function calls and allow to replace the variable parts of an abstraction with the specified arguments.
929
930 \begin{rail}
931 application : expression '(' (expression + ',') ')';
932 \end{rail}
933
934 For example you can apply the previous abstraction to transform your stereo harmonizer:
935 \begin{lstlisting}
936 mono(harmonizer)
937 \end{lstlisting}
938
939 The compiler will start by replacing \lstinline'mono' by its definition:
940 \begin{lstlisting}
941 \(fx).(_ <: fx :> _)(harmonizer)
942 \end{lstlisting}
943
944 Whenever the \faust compiler find an application of an abstraction it replaces\marginpar{Replacing the \emph{variable part} with the argument is called $\beta$-reduction in Lambda-Calculus} the \emph{variable part} with the argument. The resulting expression is as expected:
945 \begin{lstlisting}
946 (_ <: harmonizer :> _)
947 \end{lstlisting}
948
949
950
951 \subsubsection{Pattern Matching}
952 Pattern matching rules provide an effective way to analyze and transform block-diagrams algorithmically.
953 \begin{rail}
954 patternabstraction : "case" lbrace (rule +) rbrace ;
955 Rule : '(' (pattern + ',') ')' "=>" expression ';';
956 Pattern : ident | expression;
957 \end{rail}
958
959 For example \lstinline'case{ (x:y) => y:x; (x) => x; }' contains two rules. The first one will match a sequential expression and invert the two part. The second one will match all remaining expressions and leave it untouched. Therefore the application:
960
961 \begin{lstlisting}
962 case{(x:y) => y:x; (x) => x;}(freeverb:harmonizer)
963 \end{lstlisting}
964
965 will produce:
966
967 \begin{lstlisting}
968 (harmonizer:freeverb)
969 \end{lstlisting}
970
971
972
973
974 Please note that patterns are evaluated before the pattern matching operation. Therefore only variables that appear free in the pattern are binding variables during pattern matching.
975
976
977
978 %--------------------------------------------------------------------------------------------------------------
979 \section{Primitives}
980 %--------------------------------------------------------------------------------------------------------------
981 \label{primitives}
982 The primitive signal processing operations represent the built-in functionalities of \faust, that is the atomic operations on signals provided by the language. All these primitives denote \emph{signal processors}, functions transforming \emph{input signals} into \emph{output signals}.
983
984 %--------------------------------------------------------------------------------------------------------------
985 \subsection{Numbers}
986 %--------------------------------------------------------------------------------------------------------------
987
988 \faust considers two types of numbers : \textit{integers} and \textit{floats}. Integers are implemented as 32-bits integers, and floats are implemented either with a simple, double or extended precision depending of the compiler options. Floats are available in decimal or scientific notation.
989
990 \begin{rail}
991 int : (|'+'|'-')(digit+) ;
992 float : (|'+'|'-')( ((digit+)'.'(digit*)) | ((digit*) '.' (digit+)) )(|exponent);
993 exponent : 'e'(|'+'|'-')(digit+);
994 digit : "0--9";
995 \end{rail}
996
997
998 \bigskip
999
1000 Like any other \faust expression, numbers are signal processors. For example the number $0.95$ is a signal processor of type $\mathbb{S}^{0}\rightarrow\mathbb{S}^{1}$ that transforms an empty tuple of signals $()$ into a 1-tuple of signals $(y)$ such that $\forall t\in\mathbb{N}, y(t)=0.95$.
1001
1002 %\begin{tabular}{|l|l|l|}
1003 %\hline
1004 %\textbf{Syntax} & \textbf{Type} & \textbf{Description} \\
1005 %\hline
1006 %$n$ & $\mathbb{S}^{0}\rightarrow\mathbb{S}^{1}$ & integer number: $y(t)=n$ \\
1007 %$r$ & $\mathbb{S}^{0}\rightarrow\mathbb{S}^{1}$ & floating point number: $y(t)=r$ \\
1008 %\hline
1009
1010 %\end{tabular}
1011
1012 %--------------------------------------------------------------------------------------------------------------
1013 \subsection{C-equivalent primitives}
1014 %--------------------------------------------------------------------------------------------------------------
1015
1016 Most \faust primitives are analogue to their C counterpart but lifted to signal processing.
1017 For example $+$ is a function of type $\mathbb{S}^{2}\rightarrow\mathbb{S}^{1}$ that transforms a pair of signals $(x_1,x_2)$ into a 1-tuple of signals $(y)$ such that $\forall t\in\mathbb{N}, y(t)=x_{1}(t)+x_{2}(t)$.
1018
1019 \bigskip
1020
1021 \begin{tabular}{|l|l|l|}
1022 \hline
1023 \textbf{Syntax} & \textbf{Type} & \textbf{Description} \\
1024 \hline
1025 $n$ & $\mathbb{S}^{0}\rightarrow\mathbb{S}^{1}$ & integer number: $y(t)=n$ \\
1026 $n.m$ & $\mathbb{S}^{0}\rightarrow\mathbb{S}^{1}$ & floating point number: $y(t)=n.m$ \\
1027
1028 \texttt{\_} & $\mathbb{S}^{1}\rightarrow\mathbb{S}^{1}$ & identity function: $y(t)=x(t)$ \\
1029 \texttt{!} & $\mathbb{S}^{1}\rightarrow\mathbb{S}^{0}$ & cut function: $\forall x\in\mathbb{S},(x)\rightarrow ()$\\
1030
1031 \texttt{int} & $\mathbb{S}^{1}\rightarrow\mathbb{S}^{1}$ & cast into an int signal: $y(t)=(int)x(t)$ \\
1032 \texttt{float} & $\mathbb{S}^{1}\rightarrow\mathbb{S}^{1}$ & cast into an float signal: $y(t)=(float)x(t)$ \\
1033
1034 \texttt{+} & $\mathbb{S}^{2}\rightarrow\mathbb{S}^{1}$ & addition: $y(t)=x_{1}(t)+x_{2}(t)$ \\
1035 \texttt{-} & $\mathbb{S}^{2}\rightarrow\mathbb{S}^{1}$ & subtraction: $y(t)=x_{1}(t)-x_{2}(t)$ \\
1036 \texttt{*} & $\mathbb{S}^{2}\rightarrow\mathbb{S}^{1}$ & multiplication: $y(t)=x_{1}(t)*x_{2}(t)$ \\
1037 \texttt{$\land$} & $\mathbb{S}^{2}\rightarrow\mathbb{S}^{1}$ & power: $y(t)=x_{1}(t)^{x_{2}(t)}$ \\
1038 \texttt{/} & $\mathbb{S}^{2}\rightarrow\mathbb{S}^{1}$ & division: $y(t)=x_{1}(t)/x_{2}(t)$ \\
1039 \texttt{\%} & $\mathbb{S}^{2}\rightarrow\mathbb{S}^{1}$ & modulo: $y(t)=x_{1}(t)\%x_{2}(t)$ \\
1040
1041 \texttt{\&} & $\mathbb{S}^{2}\rightarrow\mathbb{S}^{1}$ & logical AND: $y(t)=x_{1}(t)\&x_{2}(t)$ \\
1042 \texttt{|} & $\mathbb{S}^{2}\rightarrow\mathbb{S}^{1}$ & logical OR: $y(t)=x_{1}(t)|x_{2}(t)$ \\
1043 \texttt{xor} & $\mathbb{S}^{2}\rightarrow\mathbb{S}^{1}$ & logical XOR: $y(t)=x_{1}(t)\land x_{2}(t)$ \\
1044
1045 \texttt{<<} & $\mathbb{S}^{2}\rightarrow\mathbb{S}^{1}$ & arith. shift left: $y(t)=x_{1}(t) << x_{2}(t)$ \\
1046 \texttt{>>} & $\mathbb{S}^{2}\rightarrow\mathbb{S}^{1}$ & arith. shift right: $y(t)=x_{1}(t) >> x_{2}(t)$ \\
1047
1048
1049 \texttt{<} & $\mathbb{S}^{2}\rightarrow\mathbb{S}^{1}$ & less than: $y(t)=x_{1}(t) < x_{2}(t)$ \\
1050 \texttt{<=} & $\mathbb{S}^{2}\rightarrow\mathbb{S}^{1}$ & less or equal: $y(t)=x_{1}(t) <= x_{2}(t)$ \\
1051 \texttt{>} & $\mathbb{S}^{2}\rightarrow\mathbb{S}^{1}$ & greater than: $y(t)=x_{1}(t) > x_{2}(t)$ \\
1052 \texttt{>=} & $\mathbb{S}^{2}\rightarrow\mathbb{S}^{1}$ & greater or equal: $y(t)=x_{1}(t) >= x_{2}(t)$ \\
1053 \texttt{==} & $\mathbb{S}^{2}\rightarrow\mathbb{S}^{1}$ & equal: $y(t)=x_{1}(t) == x_{2}(t)$ \\
1054 \texttt{!=} & $\mathbb{S}^{2}\rightarrow\mathbb{S}^{1}$ & different: $y(t)=x_{1}(t) != x_{2}(t)$ \\
1055
1056 \hline
1057
1058 \end{tabular}
1059
1060 \bigskip
1061
1062
1063 %--------------------------------------------------------------------------------------------------------------
1064 \subsection{\texttt{math.h}-equivalent primitives}
1065 %--------------------------------------------------------------------------------------------------------------
1066
1067 Most of the C \texttt{math.h} functions are also built-in as primitives (the others are defined as external functions in file \texttt{math.lib}).
1068
1069 \bigskip
1070 \begin{tabular}{|l|l|l|}
1071 \hline
1072 \textbf{Syntax} & \textbf{Type} & \textbf{Description} \\
1073 \hline
1074
1075 \texttt{acos} & $\mathbb{S}^{1}\rightarrow\mathbb{S}^{1}$ & arc cosine: $y(t)=\mathrm{acosf}(x(t))$ \\
1076 \texttt{asin} & $\mathbb{S}^{1}\rightarrow\mathbb{S}^{1}$ & arc sine: $y(t)=\mathrm{asinf}(x(t))$ \\
1077 \texttt{atan} & $\mathbb{S}^{1}\rightarrow\mathbb{S}^{1}$ & arc tangent: $y(t)=\mathrm{atanf}(x(t))$ \\
1078 \texttt{atan2} & $\mathbb{S}^{2}\rightarrow\mathbb{S}^{1}$ & arc tangent of 2 signals: $y(t)=\mathrm{atan2f}(x_{1}(t), x_{2}(t))$ \\
1079
1080 \texttt{cos} & $\mathbb{S}^{1}\rightarrow\mathbb{S}^{1}$ & cosine: $y(t)=\mathrm{cosf}(x(t))$ \\
1081 \texttt{sin} & $\mathbb{S}^{1}\rightarrow\mathbb{S}^{1}$ & sine: $y(t)=\mathrm{sinf}(x(t))$ \\
1082 \texttt{tan} & $\mathbb{S}^{1}\rightarrow\mathbb{S}^{1}$ & tangent: $y(t)=\mathrm{tanf}(x(t))$ \\
1083
1084 \texttt{exp} & $\mathbb{S}^{1}\rightarrow\mathbb{S}^{1}$ & base-e exponential: $y(t)=\mathrm{expf}(x(t))$ \\
1085 \texttt{log} & $\mathbb{S}^{1}\rightarrow\mathbb{S}^{1}$ & base-e logarithm: $y(t)=\mathrm{logf}(x(t))$ \\
1086 \texttt{log10} & $\mathbb{S}^{1}\rightarrow\mathbb{S}^{1}$ & base-10 logarithm: $y(t)=\mathrm{log10f}(x(t))$ \\
1087 \texttt{pow} & $\mathbb{S}^{2}\rightarrow\mathbb{S}^{1}$ & power: $y(t)=\mathrm{powf}(x_{1}(t),x_{2}(t))$ \\
1088 \texttt{sqrt} & $\mathbb{S}^{1}\rightarrow\mathbb{S}^{1}$ & square root: $y(t)=\mathrm{sqrtf}(x(t))$ \\
1089 \texttt{abs} & $\mathbb{S}^{1}\rightarrow\mathbb{S}^{1}$ & absolute value (int): $y(t)=\mathrm{abs}(x(t))$ \\
1090 & & absolute value (float): $y(t)=\mathrm{fabsf}(x(t))$ \\
1091 \texttt{min} & $\mathbb{S}^{2}\rightarrow\mathbb{S}^{1}$ & minimum: $y(t)=\mathrm{min}(x_{1}(t),x_{2}(t))$ \\
1092 \texttt{max} & $\mathbb{S}^{2}\rightarrow\mathbb{S}^{1}$ & maximum: $y(t)=\mathrm{max}(x_{1}(t),x_{2}(t))$ \\
1093 \texttt{fmod} & $\mathbb{S}^{2}\rightarrow\mathbb{S}^{1}$ & float modulo: $y(t)=\mathrm{fmodf}(x_{1}(t),x_{2}(t))$ \\
1094 \texttt{remainder} & $\mathbb{S}^{2}\rightarrow\mathbb{S}^{1}$ & float remainder: $y(t)=\mathrm{remainderf}(x_{1}(t),x_{2}(t))$ \\
1095
1096 \texttt{floor} & $\mathbb{S}^{1}\rightarrow\mathbb{S}^{1}$ & largest int $\leq$: $y(t)=\mathrm{floorf}(x(t))$ \\
1097 \texttt{ceil} & $\mathbb{S}^{1}\rightarrow\mathbb{S}^{1}$ & smallest int $\geq$: $y(t)=\mathrm{ceilf}(x(t))$ \\
1098 \texttt{rint} & $\mathbb{S}^{1}\rightarrow\mathbb{S}^{1}$ & closest int: $y(t)=\mathrm{rintf}(x(t))$ \\
1099
1100 \hline
1101 \end{tabular}
1102 \bigskip
1103
1104
1105
1106
1107
1108 %--------------------------------------------------------------------------------------------------------------
1109 \subsection{Delay, Table, Selector primitives}
1110 %--------------------------------------------------------------------------------------------------------------
1111
1112 The following primitives allow to define fixed delays, read-only and read-write tables and 2 or 3-ways selectors (see figure \ref{fig:delays}).
1113
1114 \bigskip
1115 \begin{tabular}{|l|l|l|}
1116 \hline
1117 \textbf{Syntax} & \textbf{Type} & \textbf{Description} \\
1118 \hline
1119
1120 \texttt{mem} & $\mathbb{S}^{1}\rightarrow\mathbb{S}^{1}$ & 1-sample delay: $y(t+1)=x(t),y(0)=0$ \\
1121 \texttt{prefix} & $\mathbb{S}^{2}\rightarrow\mathbb{S}^{1}$ & 1-sample delay: $y(t+1)=x_{2}(t),y(0)=x_{1}(0)$ \\
1122 \texttt{@} & $\mathbb{S}^{2}\rightarrow\mathbb{S}^{1}$ & fixed delay: $y(t+x_{2}(t))=x_{1}(t), y(t<x_{2}(t))=0$ \\
1123
1124 \texttt{rdtable} & $\mathbb{S}^{3}\rightarrow\mathbb{S}^{1}$ & read-only table: $y(t)=T[r(t)]$ \\
1125 \texttt{rwtable} & $\mathbb{S}^{5}\rightarrow\mathbb{S}^{1}$ & read-write table: $T[w(t)]=c(t); y(t)=T[r(t)]$ \\
1126
1127 \texttt{select2} & $\mathbb{S}^{3}\rightarrow\mathbb{S}^{1}$ & select between 2 signals: $T[]=\{x_{0}(t),x_{1}(t)\}; y(t)=T[s(t)]$ \\
1128 \texttt{select3} & $\mathbb{S}^{4}\rightarrow\mathbb{S}^{1}$ & select between 3 signals: $T[]=\{x_{0}(t),x_{1}(t),x_{2}(t)\}; y(t)=T[s(t)]$ \\
1129
1130 \hline
1131 \end{tabular}
1132 \bigskip
1133
1134
1135 \begin{figure}
1136 \centering
1137 \includegraphics[scale=0.6]{illustrations/faust-diagram4}
1138 \includegraphics[scale=0.6]{illustrations/faust-diagram5}
1139 \includegraphics[scale=0.6]{illustrations/faust-diagram6}
1140 \caption{Delays, tables and selectors primitives }
1141 \label{fig:delays}
1142 \end{figure}
1143
1144
1145
1146 %--------------------------------------------------------------------------------------------------------------
1147 \subsection{Multirate and multidimension primitives}
1148 %--------------------------------------------------------------------------------------------------------------
1149
1150 The role of the following four primitives is to extend Faust capabilities to domains such as FFT-based spectral processing that involves multiple computation rates.
1151 The principle is to link rate changes to data structure manipulation operations : creating a vector-valued output signal divides the rate of input signals by the vector size, while serializing vectors multiplies rates accordingly.
1152
1153 \subsubsection{Vectorize}
1154 Vectors are created using the \lstinline'vectorize' primitive that takes two input signals : the signal $x$ to vectorize and the size $n$ of the output vectors, and produces an output signal of vectors of size $n$. The output signal is obtained by collecting $n$ consecutive samples from $x$.
1155
1156 \begin{figure}[h]
1157 \centering
1158 \includegraphics[scale=0.5]{images/mr_vectorize}
1159 \caption{\lstinline'+(1)~_' vectorized by 3}
1160 \label{fig:vectorize}
1161 \end{figure}
1162
1163 Figure \ref{fig:vectorize} illustrates the signal \lstinline'+(1)~_' vectorized by 3. This expression can be notated:
1164 \begin{lstlisting}
1165 +(1)~_, 3 : vectorize
1166 \end{lstlisting}
1167 or alternatively
1168 \begin{lstlisting}
1169 +(1)~_ : vectorize(3)
1170 \end{lstlisting}
1171 Here \lstinline'vectorize(3)' is a convenient notation for \lstinline'_, 3 : vectorize'.
1172
1173 If the first input signal $x$ is of type $T$ and rate $f$, and the second input signal $n$ is a constant signal known at compile time, then the output signal is of type $\mathtt{vector}_{n}(T)$ and rate $f/n$. The rate inferrence system will make sure the $f$ is a multiple of $n$.
1174
1175 \subsubsection{Serialize}
1176
1177 The \lstinline'serialize' primitive is the dual of \lstinline'vectorize'. It maps a signal of type $\mathtt{vector}_{n}(T)$ and rate $f$ into a signal of type $T$ and rate $n.f$.
1178
1179 \lstinline'serialize' with an input signal of vectors of size 3 is illustrated Figure \ref{fig:serialize}.
1180
1181 \begin{figure}[h]
1182 \centering
1183 \includegraphics[scale=0.5]{images/mr_serialize}
1184 \caption{Serialize}
1185 \label{fig:serialize}
1186 \end{figure}
1187
1188 \subsubsection{Concatenate}
1189 The infix operation \lstinline'#' is used to concatenate vectors as illustrated figure \ref{fig:concat}.
1190 \begin{figure}[h]
1191 \centering
1192 \includegraphics[scale=0.5]{images/mr_concat}
1193 \caption{concat vectors}
1194 \label{fig:concat}
1195 \end{figure}
1196
1197 It takes two inputs signals of types $\mathtt{vector}_{n}(T)$ and $\mathtt{vector}_{m}(T)$ and produces an output signal of type $\mathtt{vector}_{n+m}(T)$.
1198
1199 \subsubsection{Access}
1200 Vector elements can be accessed using \lstinline'[]'. This binary operation takes two input signals : a vector signal and an index signal, and delivers the corresponding elements of the vector signal as illustrated figure \ref{fig:access}.
1201
1202 \begin{figure}[h]
1203 \centering
1204 \includegraphics[scale=0.5]{images/mr_access}
1205 \caption{Access}
1206 \label{fig:access}
1207 \end{figure}
1208
1209
1210 \subsubsection{Polymorphic extension of other primitives}
1211 In order to deal with non scalar signals (signals of vectors, matrices, etc...), \faust primitives are extended
1212
1213 \bigskip
1214 \begin{tabular}{|l|l|l|}
1215 \hline
1216 \textbf{Syntax} & \textbf{Type} & \textbf{Description} \\
1217 \hline
1218
1219 \texttt{vectorize} & $\mathbb{S}^{2}\rightarrow\mathbb{S}^{1}$ & vectorize: $y(t+1)=x_{2}(t),y(0)=x_{1}(0)$ \\
1220 \texttt{serialize} & $\mathbb{S}^{1}\rightarrow\mathbb{S}^{1}$ & serialize: $y(t+1)=x(t),y(0)=0$ \\
1221 \texttt{\#} & $\mathbb{S}^{2}\rightarrow\mathbb{S}^{1}$ & concatenate vectors: $y(t+x_{2}(t))=x_{1}(t), y(t<x_{2}(t))=0$ \\
1222
1223 \texttt{[]} & $\mathbb{S}^{3}\rightarrow\mathbb{S}^{1}$ & vector access: $y(t)=T[r(t)]$ \\
1224
1225 \hline
1226 \end{tabular}
1227
1228 %--------------------------------------------------------------------------------------------------------------
1229 \subsection{User Interface Elements}
1230 %--------------------------------------------------------------------------------------------------------------
1231
1232
1233 \faust user interface widgets allow an abstract description of the user interface from within the \faust code. This description is
1234 independent of any GUI toolkits. It is based on \emph{buttons}, \emph{checkboxes}, \emph{sliders}, etc. that are grouped together
1235 vertically and horizontally using appropriate grouping schemes.
1236
1237 All these GUI elements produce signals. A button for example (see figure \ref{fig:button}) produces a signal which is 1 when the button is pressed and 0 otherwise. These signals can be freely combined with other audio signals.
1238
1239 \begin{figure}[h]
1240 \centering
1241 \includegraphics[scale=0.5]{illustrations/button}
1242 \caption{User Interface Button}
1243 \label{fig:button}
1244 \end{figure}
1245
1246
1247 \bigskip
1248
1249 \begin{tabular}{|l|l|}
1250 \hline
1251 \textbf{Syntax} & \textbf{Example} \\
1252 \hline
1253 \texttt{button(\farg{str})} & \texttt{button("play")}\\
1254 \texttt{checkbox(\farg{str})} & \texttt{checkbox("mute")}\\
1255 \texttt{vslider(\farg{str},\farg{cur},\farg{min},\farg{max},\farg{step})} & \texttt{vslider("vol",50,0,100,1)}\\
1256 \texttt{hslider(\farg{str},\farg{cur},\farg{min},\farg{max},\farg{step})} & \texttt{hslider("vol",0.5,0,1,0.01)}\\
1257 \texttt{nentry(\farg{str},\farg{cur},\farg{min},\farg{max},\farg{step})} & \texttt{nentry("freq",440,0,8000,1)}\\
1258 \texttt{vgroup(\farg{str},\farg{block-diagram})} & \texttt{vgroup("reverb", \ldots)}\\
1259 \texttt{hgroup(\farg{str},\farg{block-diagram})} & \texttt{hgroup("mixer", \ldots)}\\
1260 \texttt{tgroup(\farg{str},\farg{block-diagram})} & \texttt{vgroup("parametric", \ldots)}\\
1261 \texttt{vbargraph(\farg{str},\farg{min},\farg{max})} & \texttt{vbargraph("input",0,100)}\\
1262 \texttt{hbargraph(\farg{str},\farg{min},\farg{max})} & \texttt{hbargraph("signal",0,1.0)}\\
1263 \texttt{attach} & \texttt{attach(x, vumeter(x))}\\
1264 \hline
1265 \end{tabular}
1266
1267 \bigskip
1268 \subsubsection{Labels}
1269 Every user interface widget has a label (a string) that identifies it and informs the user of its purpose. There are three important mechanisms associated with labels (and coded inside the string): \textit{variable parts}, \textit{pathnames} and \textit{metadata}.
1270
1271 \paragraph{Variable parts.}
1272 Labels can contain variable parts. These variable parts are indicated by the sign '\texttt{\%}' followed by the name of a variable. During compilation each label is processed in order to replace the variable parts by the value of the variable.
1273 For example \lstinline'par(i,8,hslider("Voice %i", 0.9, 0, 1, 0.01))' creates 8 different sliders in parallel :
1274
1275 \begin{lstlisting}
1276 hslider("Voice 0", 0.9, 0, 1, 0.01),
1277 hslider("Voice 1", 0.9, 0, 1, 0.01),
1278 ...
1279 hslider("Voice 7", 0.9, 0, 1, 0.01).
1280 \end{lstlisting}
1281
1282 while \lstinline'par(i,8,hslider("Voice", 0.9, 0, 1, 0.01))' would have created only one slider and duplicated its output 8 times.
1283
1284
1285 The variable part can have an optional format digit.
1286 For example \lstinline'"Voice %2i"' would indicate to use two digit when inserting the value of i in the string.
1287
1288 An escape mechanism is provided.
1289 If the sign \lstinline'%' is followed by itself, it will be included in the resulting string.
1290 For example \lstinline'"feedback (%%)"' will result in \lstinline'"feedback (%)"'.
1291
1292 \paragraph{Pathnames.}
1293 Thanks to horizontal, vertical and tabs groups, user interfaces have a hierarchical structure analog to a hierarchical file system. Each widget has an associated \textit{pathname} obtained by concatenating the labels of all its surrounding groups with its own label.
1294
1295 In the following example :
1296 \begin{lstlisting}
1297 hgroup("Foo",
1298 ...
1299 vgroup("Faa",
1300 ...
1301 hslider("volume",...)
1302 ...
1303 )
1304 ...
1305 )
1306 \end{lstlisting}
1307 the volume slider has pathname \lstinline'/h:Foo/v:Faa/volume'.
1308
1309 In order to give more flexibility to the design of user interfaces, it is possible to explicitly specify the absolute or relative pathname of a widget directly in its label.
1310
1311 In our previous example the pathname of :
1312 \begin{lstlisting}
1313 hslider("../volume",...)
1314 \end{lstlisting}
1315 would have been \lstinline'"/h:Foo/volume"', while the pathname of :
1316 \begin{lstlisting}
1317 hslider("t:Fii/volume",...)
1318 \end{lstlisting}
1319 would have been :
1320 \lstinline'"/h:Foo/v:Faa/t:Fii/volume"'.
1321
1322 The grammar for labels with pathnames is the following:
1323 % \begin{grammar}
1324 % <label> ::=
1325 % \begin{syntdiag}
1326 % <path> <name>
1327 % \end{syntdiag}
1328 % \end{grammar}
1329 % %
1330 % \begin{grammar}
1331 % <path> ::=
1332 % \begin{syntdiag}
1333 % \begin{stack} \\ "/" \end{stack}
1334 % \begin{stack} \\ \begin{rep} <folder> "/" \end{rep} \end{stack}
1335 % \end{syntdiag}
1336 % \end{grammar}
1337 % %
1338 % \begin{grammar}
1339 % <folder> ::=
1340 % \begin{syntdiag}
1341 % \begin{stack}
1342 % ".." \\
1343 % \begin{stack} "h:" \\ "v:" \\ "t:" \end{stack} <name>
1344 % \end{stack}
1345 % \end{syntdiag}
1346 % \end{grammar}
1347
1348 \begin{rail}
1349 label : path name;
1350 path : (| '/') (| (folder '/')+);
1351 folder : (".." | ("h:" | "v:" | "t:" ) name);
1352 \end{rail}
1353
1354
1355 \paragraph{Metadata}
1356 Widget labels can contain metadata enclosed in square brackets. These metadata associate a key with a value and are used to provide additional information to the architecture file. They are typically used to improve the look and feel of the user interface.
1357 The \faust code :
1358 \begin{lstlisting}
1359 process = *(hslider("foo [key1: val 1][key2: val 2]",
1360 0, 0, 1, 0.1));
1361 \end{lstlisting}
1362
1363 will produce and the corresponding C++ code :
1364
1365 \begin{lstlisting}
1366 class mydsp : public dsp {
1367 ...
1368 virtual void buildUserInterface(UI* interface) {
1369 interface->openVerticalBox("m");
1370 interface->declare(&fslider0, "key1", "val 1");
1371 interface->declare(&fslider0, "key2", "val 2");
1372 interface->addHorizontalSlider("foo", &fslider0,
1373 0.0f, 0.0f, 1.0f, 0.1f);
1374 interface->closeBox();
1375 }
1376 ...
1377 };
1378 \end{lstlisting}
1379
1380 All the metadata are removed from the label by the compiler and
1381 transformed in calls to the \lstinline'UI::declare()' method. All these
1382 \lstinline'UI::declare()' calls will always take place before the \lstinline'UI::AddSomething()'
1383 call that creates the User Interface element. This allows the
1384 \lstinline'UI::AddSomething()' method to make full use of the available metadata.
1385
1386 It is the role of the architecture file to decide what to do with these
1387 metadata. The \lstinline'jack-qt.cpp' architecture file for example implements the
1388 following :
1389 \begin{enumerate}
1390 \item \lstinline'"...[style:knob]..."' creates a rotating knob instead of a regular
1391 slider or nentry.
1392 \item \lstinline'"...[style:led]..."' in a bargraph's label creates a small LED instead
1393 of a full bargraph
1394 \item \lstinline'"...[unit:dB]..."' in a bargraph's label creates a more realistic
1395 bargraph with colors ranging from green to red depending of the level of
1396 the value
1397 \item \lstinline'"...[unit:xx]..."' in a widget postfixes the value displayed with xx
1398 \item \lstinline'"...[tooltip:bla bla]..."' add a tooltip to the widget
1399 \item \lstinline'"...[osc:/address min max]..."' Open Sound Control message alias
1400 \end{enumerate}
1401
1402 Moreover starting a label with a number option like in \lstinline'"[1]..."' provides
1403 a convenient means to control the alphabetical order of the widgets.
1404
1405 \subsubsection{Attach}
1406 The \lstinline'attach' primitive takes two input signals and produce one output signal which is a copy of the first input. The role of \lstinline'attach' is to force its second input signal to be compiled with the first one. From a mathematical point of view \lstinline'attach(x,y)' is equivalent to \lstinline'1*x+0*y', which is in turn equivalent to \lstinline'x', but it tells the compiler not to optimize-out \lstinline'y'.
1407
1408 To illustrate this role let say that we want to develop a mixer application with a vumeter for each input signals. Such vumeters can be easily coded in \faust using an envelop detector connected to a bargraph. The problem is that these envelop signals have no role in the output signals. Using \lstinline'attach(x,vumeter(x))' one can tel the compiler that when \lstinline'x' is compiled \lstinline'vumeter(x)' should also be compiled.
1409
1410