### Processor and Namespace Aliases Source: https://cmajor.dev/docs/LanguageReference Provides examples of creating aliases for parameterised processors and namespaces as a shorthand. ```cmajor processor MyAlias1 = my_namespace::MyProcessor(float<2>, 1234), MyAlias2 = my_namespace::MyProcessor(float<3>, 5432); namespace n123 = some_namespace(float64)::other_namespace(1.0f); ``` -------------------------------- ### Execute ONNX to Cmajor conversion Source: https://cmajor.dev/docs/Tools/MachineLearning Example command to run the ONNX conversion script with model and output directory arguments. ```bash onnxToCmajor.py --model "path/to/your/model.onnx" --patchDir "path/to/output/patch" ``` -------------------------------- ### Execute RTNeural to Cmajor conversion Source: https://cmajor.dev/docs/Tools/MachineLearning Example command to run the RTNeural conversion script with model and output directory arguments. ```bash rtneuralToCmajor.py --model "path/to/your/model.json" --patchDir "path/to/output/patch" ``` -------------------------------- ### Cmajor Aggregate Literals Source: https://cmajor.dev/docs/LanguageReference Provides examples of initializing arrays, structs, and typed collections using aggregate literals in Cmajor. ```cmajor int[5] x = (2, 3, 4, 5, 6); MyStruct y = (3, 6.5f, "hello", (3, 4, false)); var z = bool<4> (true, false, false, true); ``` -------------------------------- ### Define a processor for testing Source: https://cmajor.dev/docs/TestFileFormat Example of a processor definition used to illustrate input event and value file requirements. ```Cmajor processor Test [[ main ]] { input event float in; input value float valueIn; output event float out; } ``` -------------------------------- ### Cmaj testConsole Example Source: https://cmajor.dev/docs/TestFileFormat Shows how to use `testConsole` to test console output. The processor's output stream is ignored, but its console writes are compared against an expected string. ```cmajor ## testConsole ("hello world") processor P { output stream int out; void main() { console <- "hello " <- "world"; out <- -1; advance(); } } ``` -------------------------------- ### Get Help for cmaj Command-Line Tool Source: https://cmajor.dev/docs/GettingStarted Run this command to display the latest set of available arguments for the cmaj command-line tool. This is useful for understanding all available operations. ```bash $ cmaj help ``` -------------------------------- ### Handling Array Endpoints in Connections Source: https://cmajor.dev/docs/LanguageReference Provides examples of valid and invalid connections involving array nodes and endpoints, illustrating rules for index specification and type compatibility. ```cmajor graph ReturnsArray { output stream float32 out1[3]; output stream float32 out2; } graph Test { output stream float32 out; output stream float32 instanceOut[3]; output stream float32 arrayElement[10]; node n = ReturnsArray[10]; connection { n.out1 -> arrayElement; // invalid - the node is an array, and the endpoint is also an array type n.out1[1] -> arrayElement; // invalid - as above, n.out1 is an invalid type, so you can't take an index n[2].out1 -> instanceOut; // valid - n[2] selects a node, so the type is float32[3] n[2].out1[2] -> out; // valid - n[2] selects a node, out1[2] selects an array member, so type is float n.out2 -> arrayElement; // valid - type is float[10] n[1].out2 -> out; // valid - type is float } } ``` -------------------------------- ### Cmaj testProcessor Example Source: https://cmajor.dev/docs/TestFileFormat Demonstrates the `testProcessor` directive, which compiles a processor and checks its output stream for integers. A stream of 1s is a pass, any 0 is a fail. The stream must end with -1. ```cmajor ## testProcessor() processor P { output stream int out; void main() { out <- 1; advance(); // this is a pass out <- 0; advance(); // sending a zero will cause a fail to be logged out <- -1; advance(); // always send a -1 at the end to stop the test } } ``` -------------------------------- ### Get MIDI Note/Pitch Information Source: https://cmajor.dev/docs/StandardLibrary Retrieves note number, pitch, and velocity from MIDI messages. Use `getFloatVelocity` for floating-point velocity values. ```cmajor int32 get14BitValue (const Message& this) ``` ```cmajor bool isNoteOn (const Message& this) ``` ```cmajor bool isNoteOff (const Message& this) ``` ```cmajor int32 getNoteNumber (const Message& this) ``` ```cmajor float32 getPitch (const Message& this) ``` ```cmajor int32 getVelocity (const Message& this) ``` ```cmajor float32 getFloatVelocity (const Message& this) ``` -------------------------------- ### Clone and Initialize GuitarLSTM Repository Source: https://cmajor.dev/docs/Examples/GuitarLSTM Commands to download the repository and initialize necessary submodules. ```bash git clone git@github.com:cmajor-lang/GuitarLSTM.git cd GuitarLSTM git submodule init git submodule update ``` -------------------------------- ### Get MIDI System Messages Source: https://cmajor.dev/docs/StandardLibrary Checks for various MIDI system messages like All Notes Off, Clock, Start, Stop, etc. ```cmajor bool isAllNotesOff (const Message& this) ``` ```cmajor bool isAllSoundOff (const Message& this) ``` ```cmajor bool isQuarterFrame (const Message& this) ``` ```cmajor bool isClock (const Message& this) ``` ```cmajor bool isStart (const Message& this) ``` ```cmajor bool isContinue (const Message& this) ``` ```cmajor bool isStop (const Message& this) ``` ```cmajor bool isActiveSense (const Message& this) ``` -------------------------------- ### Cmaj testFunction Example Source: https://cmajor.dev/docs/TestFileFormat Example of using the `testFunction` directive to test Cmaj functions that return a boolean. Only functions taking no parameters and returning bool are executed. ```cmajor ## testFunction() bool test1() { return 1 + 1 == 2; } // this will pass bool test2() { return 1 + 2 == 3; } // this will fail int notATest() {} // this function will be ignored since it doesn't return a bool ``` -------------------------------- ### Train the GuitarLSTM Model Source: https://cmajor.dev/docs/Examples/GuitarLSTM Execute the training script using input and output WAV files. ```bash ./train.py data/ts9_test1_in_FP32.wav data/ts9_test1_out_FP32.wav test ``` -------------------------------- ### Multiple Destinations and Braced Connections Source: https://cmajor.dev/docs/LanguageReference Shows how to send an output to multiple destinations using a comma-separated list or a braced block for declaring connections. ```cmajor // You can use a comma-separated list to send an output to multiple destinations: connection node.output1 -> node2.in1, node3.in3; // As for nodes and endpoints, you can also use a braced block to declare the connections: connection { node3.output7 -> output3; node1.output1 -> node2 -> node3 -> output3; } ``` -------------------------------- ### Get MIDI Meta Events Source: https://cmajor.dev/docs/StandardLibrary Checks for meta events within MIDI messages, such as Song Position Pointer. ```cmajor bool isMetaEvent (const Message& this) ``` ```cmajor bool isSongPositionPointer (const Message& this) ``` ```cmajor int32 getSongPositionPointerValue (const Message& this) ``` -------------------------------- ### Processor with Various Parameter Types Source: https://cmajor.dev/docs/LanguageReference Demonstrates a processor accepting type, processor, namespace, and constant value parameters. ```cmajor // Examples of all the types of parameter that can be used: processor Example (using TypeName, processor MyProcessor, namespace MyNamespace, float<2> myConstant) { ... ``` -------------------------------- ### Get MIDI Channel Source: https://cmajor.dev/docs/StandardLibrary Extracts MIDI channel information from a message. Supports 0-15 and 1-16 indexed channels. ```cmajor int32 getChannel0to15 (const Message& this) ``` ```cmajor int32 getChannel1to16 (const Message& this) ``` -------------------------------- ### Parameterised Namespace Usage and Aliasing Source: https://cmajor.dev/docs/LanguageReference Shows how to use a parameterised namespace and create a local alias to simplify repeated usage. ```cmajor namespace ExampleNamespace (using Type, int value) { Type addValue (Type x) { return x + Type (value); } } void f() { // When using a parameterised namespace, it can be quite long-winded... let x1 = ExampleNamespace (int, 10)::addValue (100); // ...so you can use 'namespace' to declare a local alias: namespace N = ExampleNamespace (int, 10); let x2 = N::addValue (101); let x3 = N::addValue (102); } ``` -------------------------------- ### Graph Delays and Feedback Loops Source: https://cmajor.dev/docs/LanguageReference Shows how to insert delays into connections and create legal feedback loops by ensuring at least one sample of delay. ```Cmajor connection mySource -> [100] -> myDest; // this adds a 100 frame delay between these two endpoints ``` ```Cmajor graph G { // declare 3 nodes node p1 = MyProcessor, p2 = MyProcessor, p3 = MyProcessor; // Declaring a loop like this would cause a compile error: connection p1 -> p2 -> p3 -> p1; // ...but if you insert a delay somewhere, it becomes legal: connection p1 -> p2 -> [1] -> p3 -> p1; } ``` -------------------------------- ### Implement getScaleFactorLimits for GUI scaling Source: https://cmajor.dev/docs/PatchFormat Define the minimum and maximum scale factors for a web component to enable automatic GUI scaling during window resizing. ```javascript class MyAmazingPatchView extends HTMLElement { // constructor and other methods... getScaleFactorLimits() { return { minScale: 0.5, maxScale: 1.25 }; } } ``` -------------------------------- ### Get MIDI Aftertouch Information Source: https://cmajor.dev/docs/StandardLibrary Retrieves aftertouch values from MIDI messages. Supports both raw integer and floating-point representations. ```cmajor bool isAftertouch (const Message& this) ``` ```cmajor int32 getAfterTouchValue (const Message& this) ``` ```cmajor float32 getFloatAfterTouchValue (const Message& this) ``` -------------------------------- ### Processor and Endpoint Annotations Source: https://cmajor.dev/docs/LanguageReference Demonstrates how to attach annotations to processors, endpoints, and variables using double-square-brackets `[[ ]]` for metadata. ```cmajor // A processor annotation is written after its name and before the open-brace: processor P [[ name: "hello", animal: "cat", size: 123 ]] { // An endpoint or variable annotation goes between its name and the semi-colon: input event float in [[ name: "input", min: 10.0, max: 100.0 ]]; int x [[ desc: "blah", number: 1234 ]]; } ``` -------------------------------- ### Cmajor String Literal Example Source: https://cmajor.dev/docs/LanguageReference Shows the syntax for string literals in Cmajor, which use double-quotes and support JSON-style escape characters. ```cmajor string myString = " Hello\n World\n \uD83D\uDE00"; ``` -------------------------------- ### Defining Arrays and Slices Source: https://cmajor.dev/docs/LanguageReference Demonstrates the syntax for declaring fixed-size arrays and dynamic slices. ```Cmajor int[] x; // a slice int[3] y; // an array // Functions can take slices as parameters void myFunction (int[] x) { ... ``` -------------------------------- ### Get MIDI Controller Information Source: https://cmajor.dev/docs/StandardLibrary Checks for controller messages and retrieves their number and value. Use `isControllerNumber` for specific controller checks. ```cmajor bool isController (const Message& this) ``` ```cmajor bool isControllerNumber (const Message& this, int32 number) ``` ```cmajor int32 getControllerNumber (const Message& this) ``` ```cmajor int32 getControllerValue (const Message& this) ``` ```cmajor float32 getFloatControllerValue (const Message& this) ``` -------------------------------- ### Load audio data into raw array Source: https://cmajor.dev/docs/PatchFormat Demonstrates loading audio file data directly into a raw float array, noting that sample rate information is discarded. ```Cmajor processor MyProcessor { external float[] audioData; ``` ```JSON "externals": { "MyProcessor::audioData" : "piano_36.ogg", } ``` -------------------------------- ### Get MIDI Message Type Source: https://cmajor.dev/docs/StandardLibrary Retrieves the type of a MIDI message. Useful for routing or conditional logic based on message type. ```cmajor int32 getMessageType (const Message& this) ``` -------------------------------- ### Asset Handling Methods Source: https://cmajor.dev/docs/PatchFormat Methods for handling assets within the patch bundle. ```APIDOC ## Asset Handling Methods ### `getResourceAddress(path)` #### Description This takes a relative path to an asset within the patch bundle, and converts it to a path relative to the root of the browser that is showing the view. You need to use this in your view code to translate your asset URLs to a form that can be safely used in your view’s HTML DOM (e.g. in its CSS). This is needed because the host’s HTTP server (which is delivering your view pages) may have a different ‘/’ root than the root of your patch (e.g. if a single server is serving multiple patch GUIs). ### Parameters #### Path Parameters - **path** (string) - Required - A relative path to an asset within the patch bundle. ``` -------------------------------- ### Get Impulse Data Function Source: https://cmajor.dev/docs/StandardLibrary Retrieves a float32 value from an ImpulseChannel at a specified index. This function is part of the std::convolution namespace. ```cmajor get `float32 get ( ImpulseChannel& this, int32 index) ` ``` -------------------------------- ### Configure ONNX to Cmajor conversion Source: https://cmajor.dev/docs/Tools/MachineLearning Displays the command-line options available for the onnxToCmajor.py script. ```text --model Specifies the ONNX model file to convert --patchDir Specifies a folder into which the generated patch will be written If no patchDir argument is supplied, the output will be a single Cmajor file. ``` -------------------------------- ### Get MIDI Channel Pressure Information Source: https://cmajor.dev/docs/StandardLibrary Retrieves channel pressure values from MIDI messages. Supports both raw integer and floating-point representations. ```cmajor bool isChannelPressure (const Message& this) ``` ```cmajor int32 getChannelPressureValue (const Message& this) ``` ```cmajor float32 getFloatChannelPressureValue (const Message& this) ``` -------------------------------- ### Get MIDI Program Change Information Source: https://cmajor.dev/docs/StandardLibrary Checks if a message is a program change and retrieves its number. Use `isProgramChange` to test the message type. ```cmajor bool isProgramChange (const Message& this) ``` ```cmajor int32 getProgramChangeNumber (const Message& this) ``` -------------------------------- ### Connection Functions: Constant and Arithmetic Expressions Source: https://cmajor.dev/docs/LanguageReference Illustrates using constants and arithmetic expressions as the source for stream and value connections. ```cmajor /// specify a constant 0.5f -> node1.in; /// Perform an arithmetic expression on multiple input values or streams in1 * in2 -> node2.in; /// Take the minimum of two inputs std::min (in1, in2) -> node2.in; ``` -------------------------------- ### Using wrap and clamp integer types Source: https://cmajor.dev/docs/LanguageReference Demonstrates the behavior of `wrap` and `clamp` types, which limit 32-bit integers to a specified range using modulo or boundary capping, respectively. Useful for safe array indexing. ```cmajor wrap<5> w; clamp<5> c; loop (7) { ++w; ++c; } // after being incremented 7 times, w == 2 and c == 4 w = 4 - 5; // w == 4 c = 4 - 5; // c == 0 ``` -------------------------------- ### File Class Source: https://cmajor.dev/docs/ScriptFileFormat Helper class for filesystem operations. ```APIDOC ## Class: File ### Description Provides access to the filesystem. ### Methods - **exists()**: Returns true if file exists. - **read()**: Reads file content as string or byte array. - **readAudioData(annotations)**: Reads audio file data. - **overwrite(newContent)**: Overwrites file with new content. - **findChildren(shouldFindFolders, recursive, wildcard)**: Scans folder for children. ``` -------------------------------- ### Get MIDI Message Bytes Source: https://cmajor.dev/docs/StandardLibrary Extracts individual byte values from a MIDI message. Use these functions to access raw byte data. ```cmajor int32 getByte1 (const Message& this) ``` ```cmajor int32 getByte2 (const Message& this) ``` ```cmajor int32 getByte3 (const Message& this) ``` -------------------------------- ### Processor Composition Source: https://cmajor.dev/docs/LanguageReference Demonstrates nesting a processor within another processor and manually advancing its state. ```Cmajor processor FilterComposition { input stream float in; output stream float out; node lowPass = std::filters::tpt::onepole::Processor (0, 1000); void main() { loop { lowPass.in <- in; lowPass.advance(); out <- lowPass.out; advance(); } } } ``` -------------------------------- ### Get MIDI Pitch Wheel Information Source: https://cmajor.dev/docs/StandardLibrary Checks if a message is a pitch wheel event and retrieves its value. Use `isPitchWheel` to test the message type. ```cmajor bool isPitchWheel (const Message& this) ``` ```cmajor int32 getPitchWheelValue (const Message& this) ``` -------------------------------- ### Vector Sum and Product Source: https://cmajor.dev/docs/LanguageReference The standard library provides functions like `sum()` and `product()` for vectors and arrays. These operations are applied to all elements. ```cmajor let s = sum (x); ``` -------------------------------- ### Create and Initialize Struct Object Source: https://cmajor.dev/docs/LanguageReference Struct objects can be created using their name as a type. Members can be accessed using dot notation. Zero-initialization occurs for default objects. ```cmajor struct Position { float x, y; } Position getMovedPosition (Position p) { Position newPos; newPos.x = p.x + 10.0f; newPos.y = p.y - 5.0f; return newPos; } ``` -------------------------------- ### Utility Functions Source: https://cmajor.dev/docs/StandardLibrary A collection of general utility functions. ```APIDOC ## allTrue ### Description Takes a vector or array of bools, and returns true if all of its elements are true. ### Method N/A (Function Signature) ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (N/A) Returns a boolean value. #### Response Example `true` or `false` ``` ```APIDOC ## allEqual ### Description Takes two array or vector arguments, and returns true if all of their corresponding elements are equal. ### Method N/A (Function Signature) ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (N/A) Returns a boolean value. #### Response Example `true` or `false` ``` ```APIDOC ## swap ### Description Swaps the contents of two assignable values. ### Method N/A (Function Signature) ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (N/A) void (no return value) #### Response Example None ``` ```APIDOC ## sin ### Description Sine of an angle. ### Method N/A (Function Signature) ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (N/A) Returns the sine of the input angle. #### Response Example `T` (where T is the input type) ``` ```APIDOC ## cos ### Description Cosine of an angle. ### Method N/A (Function Signature) ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (N/A) Returns the cosine of the input angle. #### Response Example `T` (where T is the input type) ``` ```APIDOC ## tan ### Description Tangent of an angle. ### Method N/A (Function Signature) ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (N/A) Returns the tangent of the input angle. #### Response Example `T` (where T is the input type) ``` ```APIDOC ## atan ### Description Arc tangent (inverse tangent) of x. ### Method N/A (Function Signature) ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (N/A) Returns the arc tangent of the input value. #### Response Example `T` (where T is the input type) ``` ```APIDOC ## sinh ### Description Hyperbolic sine of an angle. ### Method N/A (Function Signature) ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (N/A) Returns the hyperbolic sine of the input angle. #### Response Example `T` (where T is the input type) ``` ```APIDOC ## cosh ### Description Hyperbolic cosine of an angle. ### Method N/A (Function Signature) ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (N/A) Returns the hyperbolic cosine of the input angle. #### Response Example `T` (where T is the input type) ``` ```APIDOC ## tanh ### Description Hyperbolic tangent of an angle. ### Method N/A (Function Signature) ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (N/A) Returns the hyperbolic tangent of the input angle. #### Response Example `T` (where T is the input type) ``` ```APIDOC ## atanh ### Description Arc hyperbolic tangent. ### Method N/A (Function Signature) ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (N/A) Returns the arc hyperbolic tangent of the input value. #### Response Example `T` (where T is the input type) ``` ```APIDOC ## asin ### Description Arc sine (inverse sine) of an angle. ### Method N/A (Function Signature) ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (N/A) Returns the arc sine of the input angle. #### Response Example `T` (where T is the input type) ``` ```APIDOC ## acos ### Description Arc cosine (inverse cosine) of an angle. ### Method N/A (Function Signature) ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (N/A) Returns the arc cosine of the input angle. #### Response Example `T` (where T is the input type) ``` ```APIDOC ## asinh ### Description Arc hyperbolic sine. ### Method N/A (Function Signature) ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (N/A) Returns the arc hyperbolic sine of the input value. #### Response Example `T` (where T is the input type) ``` ```APIDOC ## acosh ### Description Arc hyperbolic cosine. ### Method N/A (Function Signature) ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (N/A) Returns the arc hyperbolic cosine of the input value. #### Response Example `T` (where T is the input type) ``` ```APIDOC ## atan2 ### Description Arc tangent of y/x. ### Method N/A (Function Signature) ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (N/A) Returns the arc tangent of y/x. #### Response Example `T` (where T is the input type) ``` -------------------------------- ### Auto-updating Expect Error Directive Source: https://cmajor.dev/docs/TestFileFormat When a directive is provided without arguments, the tool automatically inserts the correct expected outcome and re-saves the test file. This example shows an 'expectError' directive being updated. ```cmajor ## expectError void f (XX& x) {} ``` ```cmajor ## expectError ("2:9: error: Cannot find symbol 'XX'") void f (XX& x) {} ``` -------------------------------- ### Create a New Cmajor Patch Source: https://cmajor.dev/docs/GettingStarted Initializes a new empty patch directory using the Cmajor command-line tool. ```bash $ cmaj create AnnoyingBeep ``` -------------------------------- ### Cmajor Patch Manifest Example Source: https://cmajor.dev/docs/PatchFormat This JSON defines the properties of a Cmajor patch, including version, ID, name, and source file. Required properties include CmajorVersion, ID, version, and name. ```json { "CmajorVersion": 1, "ID": "dev.cmajor.examples.helloworld", "version": "1.0", "name": "Hello World", "description": "The classic audio Hello World", "manufacturer": "Cmajor Software Ltd", "category": "generator", "isInstrument": false, "source": "HelloWorld.cmajor" } ``` -------------------------------- ### std::levels Namespace Source: https://cmajor.dev/docs/StandardLibrary Utilities for decibel and gain conversions. ```APIDOC ## namespace std::levels ### Functions #### dBtoGain ##### Description Converts a relative gain in decibels to a gain factor. ##### Signature `T dBtoGain (T decibels)` #### gainTodB ##### Description Converts a gain factor to a relative number of decibels. ##### Signature `T gainTodB (T gainFactor)` ``` -------------------------------- ### Defining a Cmajor Graph with Connections Source: https://cmajor.dev/docs/LanguageReference Define a graph in Cmajor by declaring its inputs and outputs, child processor nodes, and connection statements. This example shows a simple graph that applies a gain of 0.5 to a float stream. ```cmajor // This example graph just applies a gain of 0.5 to a mono stream of floats graph GainExample { // Declare the graph's inputs and outputs first - this is done with exactly the same // syntax as used in a processor declaration output stream float out; input stream float in; // now declare the nodes that the graph contains: node attenuatorNode = std::levels::ConstantGain (float, 0.5f); // now declare how the nodes are connected: connection in -> attenuatorNode -> out; } ``` -------------------------------- ### Manipulating Slices Source: https://cmajor.dev/docs/LanguageReference Shows how slices reference original arrays, how they can be resized, and how range slicing works. ```Cmajor int[4] originalArray = (1, 2, 3, 4); int[4] arrayCopy = originalArray; // creates a copy of the original int[] arraySlice = originalArray; // creates a slice of the original console <- arrayCopy[1] <- " " // prints 2 <- arraySlice[1] <- " "; // prints 2 originalArray[1] = 456; // modifying the original array console <- arrayCopy[1] <- " " // prings 2 <- arraySlice[1] <- " "; // prints 456 arraySlice = (); // sets the slice to be empty console <- arraySlice.size <- " " // prints 0 <- arraySlice[1] <- " "; // prints 0 arraySlice = originalArray[2:4]; // now make our slice point at the last two elements console <- arraySlice.size <- " " // prints 2 <- arraySlice[1]; // prints 4 ``` -------------------------------- ### Configure RTNeural to Cmajor conversion Source: https://cmajor.dev/docs/Tools/MachineLearning Displays the command-line options available for the rtneuralToCmajor.py script. ```text --model Specifies the RTNeural model file to convert --patchDir Specifies a folder into which the generated patch will be written --name Optional name for the model - defaults to "Model" --useFloat64 By default we use float32, but this changes the generated model to float64 If no patchDir argument is supplied, the output will be a single Cmajor file. ``` -------------------------------- ### Implementing For Loops Source: https://cmajor.dev/docs/LanguageReference For loops support standard C-style syntax, infinite loops, and range-based iteration. ```Cmaj for (int i = 0; i < 5; ++i) console <- i; // prints 0, 1, 2, 3, 4 for (;;) // an infinite loop advance(); int i = 0; for (; i < j; ++i) console <- i; // prints 0, 1, 2, 3, 4 ``` ```Cmaj for (wrap<5> i) console <- i; // prints 0, 1, 2, 3, 4 for (clamp<5> i = 2) // you can set an initial value console <- i; // prints 2, 3, 4 ``` -------------------------------- ### Create State Variable Filter Source: https://cmajor.dev/docs/StandardLibrary Initializes a state variable filter. Requires mode, processor frequency, filter frequency, and Q factor. ```cmajor Implementation create (int32 mode, float64 processorFrequency, float64 filterFrequency, float64 Q) ``` -------------------------------- ### Declare Processor Endpoints Source: https://cmajor.dev/docs/LanguageReference Demonstrates various ways to declare input and output endpoints within a processor, including grouping and array syntax. ```cmajor processor P { input stream float input1; // a simple stream of floats input stream float<4> input2; // a stream where each element is a float<4> vector input value int64 in3, in4; // two input value streams that hold int64s output event int out1; // an output which sends simple integers as events output event MyStruct out2; // an output of more complex object events output event (string, int) out3; // an output event stream which can accept either strings or ints output stream float<2> out4[4]; // an array of 4 output streams which each hold float<2> vectors input event void in; // An input event with no value // If you have a lot of endpoints, you can also use braces to group together definitions: output { stream int x; stream float y; } // ..or.. input event { int<2> x; float64 y; } } ``` -------------------------------- ### Declare functions and overloading Source: https://cmajor.dev/docs/LanguageReference Functions follow standard C-style syntax. Overloading is supported by providing different argument types. ```Cmajor void doSomething (int parameter1, bool parameter2) { // ... } float calculateAverage (float f1, float f2) { return (f1 + f2) / 2.0f; } ``` ```Cmajor void handleMessage(std::notes::NoteOn n){} ``` ```Cmajor void handleMessage(std::notes::NoteOff n){} ``` -------------------------------- ### Generate a native CLAP project Source: https://cmajor.dev/docs/PatchFormat Use the cmaj generate command to create a static C++ CLAP project from a patch. ```bash % cmaj generate --target=clap --output=[path to a target folder for the project] --clapIncludePath=[path to your CLAP include folder] MyAmazingPatch.cmajorpatch ``` -------------------------------- ### Create One Pole Filter Source: https://cmajor.dev/docs/StandardLibrary Initializes a one-pole filter. Ensure processorFrequency and filterFrequency are set appropriately for your audio rate. ```cmajor Implementation create (int32 mode, float64 processorFrequency, float64 filterFrequency) ``` -------------------------------- ### Audio Utility Functions Source: https://cmajor.dev/docs/StandardLibrary Functions for converting between frequency and MIDI note numbers, and calculating playback speed ratios. ```APIDOC ## Functions: Audio Utilities ### frequencyToNote - **Description**: Returns MIDI note equivalent for a frequency in Hz. - **Signature**: `float32 frequencyToNote (float32 frequency)` or `float32 frequencyToNote (float32 frequency, float32 frequencyOfA)` ### noteToFrequency - **Description**: Returns frequency in Hz for a MIDI note number. - **Signature**: `float32 noteToFrequency (T midiNoteNumber)` or `float32 noteToFrequency (T midiNoteNumber, float32 frequencyOfA)` ### getSpeedRatioBetween - **Description**: Calculates speed ratio to re-pitch a source note to a target note. - **Signature**: `float32 getSpeedRatioBetween (float32 sourceMIDINote, float32 targetMIDINote)` or `float64 getSpeedRatioBetween (float64 sourceSampleRate, float32 sourceMIDINote, float64 targetSampleRate, float32 targetMIDINote)` ``` -------------------------------- ### TimeDomainProcessor Event and Main Source: https://cmajor.dev/docs/StandardLibrary Event handler and main loop for the time domain processor. ```cmajor event impulseData (ImpulseType[] v) ``` ```cmajor void main() ``` -------------------------------- ### Export Patch to Web Audio HTML Source: https://cmajor.dev/docs/Examples Use this command to export Cmajor patches for web deployment using Web Audio and Web MIDI. The output includes HTML, Javascript, and WebAssembly. ```bash cmaj generate --target=webaudio-html --output= ``` -------------------------------- ### Constant and Mutable Slices Source: https://cmajor.dev/docs/LanguageReference Illustrates the difference between mutable and constant slices, and how they interact with array mutability. ```Cmajor int[4] originalArray = (1, 2, 3, 4); const int[4] constArray = (1, 2, 3, 4); int[] slice = originalArray; // Creates a mutable slice const int[] constSlice = originalArray; // Creates a const slice of the array int[] sliceOfConst = constArray; // error - cannot create a mutable slice of a constant array slice[2] = 10; // originalArray now contains (1, 2, 10, 4) slice = originalArray[2:]; // Update slice to point to new part of originalArray slice[2] = 20; // originalArray now contains (1, 2, 10, 20) slice[0:3] = 0; // originalArray now contains (0, 0, 10, 20) slice[:] = 1; // originalArray now contains (1, 1, 1, 1) constSlice[2] = 20; // error - cannot modify elements of a const slice constSlice = originalArray[2:]; // error - cannot update the const slice reference ``` -------------------------------- ### Implement patch GUI web component Source: https://cmajor.dev/docs/PatchFormat Exports a function that returns an HTMLElement to serve as the patch GUI, receiving a PatchConnection object. ```JavaScript class MyAmazingPatchView extends HTMLElement { // ...etc.. } export default function createPatchView (patchConnection) { return new MyAmazingPatchView (patchConnection); } ``` -------------------------------- ### Generate a native JUCE project Source: https://cmajor.dev/docs/PatchFormat Use the cmaj generate command to create a static C++ JUCE project for VST/AU/AAX plugins. ```bash % cmaj generate --target=juce --output=[path to a target folder for the project] --jucePath=[path to your JUCE folder] MyAmazingPatch.cmajorpatch ``` -------------------------------- ### Execute a test script with runScript Source: https://cmajor.dev/docs/TestFileFormat Configures and runs a processor test, comparing outputs against golden data files. ```Cmajor ## runScript ({ frequency:1000, blockSize:32, samplesToRender:1000, subDir:"gain"}) processor Gain [[ main ]] { input stream float<2> in; input value float gain; output stream float<2> out; } ``` -------------------------------- ### Processor Specialisation with Parameters Source: https://cmajor.dev/docs/LanguageReference Define a processor with type and constant parameters. These must be provided when instantiating the processor. ```cmajor // When anything tries to create an instant of this processor, the type MySampleType // and the integer myConstant must be provided. processor MyProcessor (using MySampleType, int myConstant) { output stream MySampleType out; void main() { MySampleType x[myConstant]; out <- MySampleType (myConstant + 10); advance(); } } graph G { // when instantiating a processor that takes parameters, you put the values // in parentheses after the name. In this example, the compiler will create // two different versions of MyProcessor with these two sets of parameters. node p1 = MyProcessor (float, 100), p2 = MyProcessor (float64<2>, 200); } ``` -------------------------------- ### One Pole Processor Constructor Source: https://cmajor.dev/docs/StandardLibrary Initializes the one-pole processor. Accepts an initial mode and frequency, with defaults provided. ```cmajor processor std::filters::tpt::onepole::Processor (int32 initialMode = Mode::lowPass, float32 initialFrequency = defaultFrequency) ``` -------------------------------- ### Performer Class Source: https://cmajor.dev/docs/ScriptFileFormat The Performer class is used to render a processor. ```APIDOC ## Class: Performer ### Description Wraps the cmaj::Performer class to handle audio rendering and processor interaction. ### Methods - **setBlockSize(frames)**: Sets the processing block size. - **advance()**: Advances the performer. - **getOutputFrames(h)**: Retrieves output frames for a handle. - **setInputFrames(h, d)**: Sets input frames for a handle. ``` -------------------------------- ### Complex number declaration and manipulation Source: https://cmajor.dev/docs/LanguageReference Shows various ways to declare and initialize `complex32` and `complex64` numbers, including using imaginary literals and the `complex()` constructor. Also demonstrates extracting real and imaginary parts. ```cmajor // These 3 statements are different ways to create the same complex value: complex32 c1 = 2.0fi + 3.0f; let c2 = 3.0f + 2.0fi; let c3 = complex (3.0f, 2.0f); let c4 = complex (4.0); // creates a value (4 + 0i) let ci = c1.imag; // extracts the imaginary part a complex number let cr = c1.real; // extracts the real part a complex number complex64<4> v = (2.0i + 5.0); // declares a vector of 4 complex 64-bits numbers. let r = v.real; // extracts the real elements from the vector so has type float64<4> ``` -------------------------------- ### Listener Methods Source: https://cmajor.dev/docs/PatchFormat Methods for attaching and detaching listeners to endpoints and parameters, and for requesting parameter values. ```APIDOC ## Listener Methods ### `addEndpointListener(endpointID, listener, granularity)` #### Description Attaches a listener function that will receive updates with the events or audio data that is being sent or received by an endpoint. If the endpoint is an event or value, the callback will be given an argument which is the new value. If the endpoint has the right shape to be treated as “audio” then the callback will receive a stream of updates of the min/max range of chunks of data that is flowing through it. There will be one callback per chunk of data, and the size of chunks is specified by the optional granularity parameter. If sendFullAudioData is false, the listener will receive an argument object containing two properties ‘min’ and ‘max’, which are each an array of values, one element per audio channel. This allows you to find the highest and lowest samples in that chunk for each channel. If sendFullAudioData is true, the listener’s argument will have a property ‘data’ which is an array containing one array per channel of raw audio samples data. ### `removeEndpointListener(endpointID, listener)` #### Description Removes a listener that was previously added with `addEndpointListener()`. ### `requestParameterValue(endpointID)` #### Description This will trigger an asynchronous callback to any parameter listeners that are attached, providing them with its up-to-date current value for the given endpoint. Use `addAllParameterListener()` to attach a listener to receive the result. ### `addParameterListener(endpointID, listener)` #### Description Attaches a listener function which will be called whenever the value of a specific parameter changes. The listener function will be called with an argument which is the new value. ### `removeParameterListener(endpointID, listener)` #### Description Removes a listener that was previously added with `addParameterListener()`. ### `addAllParameterListener(listener)` #### Description Attaches a listener function which will be called whenever the value of any parameter changes in the patch. The listener function will be called with an argument object with the fields `endpointID` and `value`. ### `removeAllParameterListener(listener)` #### Description Removes a listener that was previously added with `addAllParameterListener()`. ``` -------------------------------- ### Define input events in JSON Source: https://cmajor.dev/docs/TestFileFormat Format for providing input events to a processor, requiring monotonically increasing frame offsets. ```JSON [ { "frameOffset" : 10, "event" : 1.0 }, { "frameOffset" : 100, "event" : 5.0 } ] ``` -------------------------------- ### Graph with Default Parameter Values Source: https://cmajor.dev/docs/LanguageReference Illustrates how to provide default values for trailing parameters in a graph definition. ```cmajor graph G (int v = 100, processor P = MyProcessor) { ``` -------------------------------- ### Create a new patch via CLI Source: https://cmajor.dev/docs/GettingStarted Generates the boilerplate files for a new Cmajor patch in a specified directory. ```bash $ cmaj create --name="Hello" MyNewPatchFolderName ``` -------------------------------- ### testPatch() Source: https://cmajor.dev/docs/TestFileFormat Loads and compiles a Cmajor patch from a specified file path. Any compilation errors are registered as test failures. ```APIDOC ## testPatch() ### Description Attempts to load and compile a patch from a provided filename. Any compile errors will be registered as a failure. ### Parameters #### Path Parameters - **filename** (string) - Required - The relative or absolute path to the .cmajor_patch file. ### Request Example ## testPatch ("../../../my_patches/example_patch.cmajor_patch") ``` -------------------------------- ### Cmajor Build Settings API Source: https://cmajor.dev/docs/Tools/C%2B%2BAPI BuildSettings allows configuration of compile-time options for the Cmajor Engine. ```APIDOC ## cmaj::BuildSettings API ### Description The `BuildSettings` class encapsulates various compilation options that can be provided to the `cmaj::Engine` before it builds a program. These settings influence the compilation process and the resulting executable code. ### Configurable Options - Sample rate - Block size - Optimization level - Buffer sizes ```