# 4. Platform Details | HTML5

## HTML5 Specific Starter Guide

Running FMOD as HTML5 on the web is made possible by having a web server host and deliver the JavaScript content to the client web browser. In a production environment this would be hosted using a professional web server such as Apache, but during development we recommend an easy to set up local server such as Web Server for Chrome

### SDK Version

FMOD is compiled using the following tools.

- Emscripten - 2.0.20 / 1.40.1 (Fastcomp)

### Limitations

The web presents a unique set of challenges that make this implementation less than perfect when compared to other platforms supported by the FMOD Engine.

#### Multi-threading

One significant disadvantage is the lack of multi-threading, or more specifically, limited browser support of features such as SharedArrayBuffer that prevent our toolchain from implementing pthread support. This limitation means we must run mixing, streaming and loading all in the game thread requiring added latency to hide the additional CPU cost.

#### Networking

Another disadvantage of the web platform is the lack of networking sockets. There are alternatives provided by our toolchain, however they require additional servers running as a proxy. This limitation means we cannot implement Live Update and Profiling features between the running code and FMOD Studio. Additionally this means we cannot support internet streaming of audio (netstreams).

#### Performance

Many platforms benefit from targeted instruction level optimization known as SIMD (single instruction multiple data), these optimizations allow FMOD to perform several times faster than with standard C code instructions alone. Unfortunately development of SIMD for the web is an ongoing process and not ready for us to consume. This coupled with the fact the native FMOD C code has been converted to run in a browser means you will experience worse performance than the equivalent application running natively (outside the browser).

### Technologies supported by HTML5, what to use

There are 3 ways to include FMOD in your project.

1. A JS file included in a HTML file, using the older ASM.JS technology. Slower and uses more memory, but best for compatibility.
2. A JS file included in a HTML file, using the newer WASM technology. Faster (approximately 30%) and uses half the memory of ASM.JS, but requires the web browser to support the WASM technology, and also a webserver that understands the .wasm 'application/wasm' mime type.
3. A BC file included in an emscripten project, using C++. This is if you are using Emscripten with your own C/C++ code to convert to JavaScript. BC is an intermediate format.

To include FMOD using JavaScript in a html file, use the following code in your HTML.

Core API Only:

    <script type="text/javascript" src="fmod.js"></script>

FMOD Studio API:

    <script type="text/javascript" src="fmodstudio.js"></script>

### Which files do you include?

Firstly we include two separate flavours of build, "fastcomp" and "upstream" representing the old and new back-ends supported by Emscripten.
Fastcomp builds intermediate bitcode (bc) binaries that are then linked to produce ASM.js and WASM implementations.
Upstream builds intermediate wasm32 (w32) static libraries that are then linked to produce Javascript and WASM implementations.
The Emscripten official website has further information about the differences.

Below are the 3 categories of files you can include based on the 3 categories listed above.
You can either use the FMOD Core API only, or the FMOD Studio API.

Fastcomp ASM.JS - FMOD Core API

- /api/core/lib/fastcomp/asm.js/fmod.js - Release library for production code
- /api/core/lib/fastcomp/asm.js/fmod.js.mem - memory file needed to accompany fmod.js (put in same folder)
- /api/core/lib/fastcomp/asm.js/fmodL.js - Release library with logging output, use for debugging.
- /api/core/lib/fastcomp/asm.js/fmodL.js.mem - memory file needed to accompany fmodL.js (put in same folder)
- /api/core/lib/fastcomp/asm.js/fmod_reduced.js - Release library for production code, w/reduced features for lower memory footprint. Check the reduced library section for what is removed.
- /api/core/lib/fastcomp/asm.js/fmod_reduced.js.mem - memory file needed to accompany fmod_reduced.js (put in same folder)

Fastcomp ASM.JS - FMOD Studio API

- /api/studio/lib/fastcomp/asm.js/fmodstudio.js - Release library for production code. Contains fmod_reduced.js, see note below.
- /api/studio/lib/fastcomp/asm.js/fmodstudio.js.mem - memory file needed to accompany fmodstudio.js
- /api/studio/lib/fastcomp/asm.js/fmodstudioL.js - Release library with logging output, use for debugging. Contains fmodL.js, see note below.
- /api/studio/lib/fastcomp/asm.js/fmodstudioL.js.mem - memory file needed to accompany fmodstudioL.js

Upstream Javascript - FMOD Core API

- /api/core/lib/upstream/js/fmod.js - Release library for production code
- /api/core/lib/upstream/js/fmod.js.mem - memory file needed to accompany fmod.js (put in same folder)
- /api/core/lib/upstream/js/fmodL.js - Release library with logging output, use for debugging.
- /api/core/lib/upstream/js/fmodL.js.mem - memory file needed to accompany fmodL.js (put in same folder)
- /api/core/lib/upstream/js/fmod_reduced.js - Release library for production code, w/reduced features for lower memory footprint. Check the reduced library section for what is removed.
- /api/core/lib/upstream/js/fmod_reduced.js.mem - memory file needed to accompany fmod_reduced.js (put in same folder)

Upstream Javascript - FMOD Studio API

- /api/studio/lib/upstream/js/fmodstudio.js - Release library for production code. Contains fmod_reduced.js, see note below.
- /api/studio/lib/upstream/js/fmodstudio.js.mem - memory file needed to accompany fmodstudio.js
- /api/studio/lib/upstream/js/fmodstudioL.js - Release library with logging output, use for debugging. Contains fmodL.js, see note below.
- /api/studio/lib/upstream/js/fmodstudioL.js.mem - memory file needed to accompany fmodstudioL.js

Fastcomp WASM - FMOD Core API

- /api/core/lib/fastcomp/wasm/fmod.js - Release library for production code
- /api/core/lib/fastcomp/wasm/fmod.wasm - Web Assembly file needed to accompany fmod.js (put in same folder)
- /api/core/lib/fastcomp/wasm/fmodL.js - Release library with logging output, use for debugging.
- /api/core/lib/fastcomp/wasm/fmodL.wasm - Web Assembly file needed to accompany fmodL.js (put in same folder)
- /api/core/lib/fastcomp/wasm/fmod_reduced.js - Release library for production code, w/reduced features for lower memory footprint. Check the reduced library section for what is removed.
- /api/core/lib/fastcomp/wasm/fmod_reduced.wasm - Web Assembly file needed to accompany fmod_reduced.js (put in same folder)

Fastcomp WASM - FMOD Studio API

- /api/studio/lib/fastcomp/wasm/fmodstudio.js - Release library for production code. Contains fmod_reduced.js, see note below.
- /api/studio/lib/fastcomp/wasm/fmodstudio.wasm - Web Assembly file needed to accompany fmodstudio.js
- /api/studio/lib/fastcomp/wasm/fmodstudioL.js - Release library with logging output, use for debugging. Contains fmodL.js, see note below.
- /api/studio/lib/fastcomp/wasm/fmodstudioL.wasm - Web Assembly file needed to accompany fmodstudioL.js

Upstream WASM - FMOD Core API

- /api/core/lib/upstream/wasm/fmod.js - Release library for production code
- /api/core/lib/upstream/wasm/fmod.wasm - Web Assembly file needed to accompany fmod.js (put in same folder)
- /api/core/lib/upstream/wasm/fmodL.js - Release library with logging output, use for debugging.
- /api/core/lib/upstream/wasm/fmodL.wasm - Web Assembly file needed to accompany fmodL.js (put in same folder)
- /api/core/lib/upstream/wasm/fmod_reduced.js - Release library for production code, w/reduced features for lower memory footprint. Check the reduced library section for what is removed.
- /api/core/lib/upstream/wasm/fmod_reduced.wasm - Web Assembly file needed to accompany fmod_reduced.js (put in same folder)

Upstream WASM - FMOD Studio API

- /api/studio/lib/upstream/wasm/fmodstudio.js - Release library for production code. Contains fmod_reduced.js, see note below.
- /api/studio/lib/upstream/wasm/fmodstudio.wasm - Web Assembly file needed to accompany fmodstudio.js
- /api/studio/lib/upstream/wasm/fmodstudioL.js - Release library with logging output, use for debugging. Contains fmodL.js, see note below.
- /api/studio/lib/upstream/wasm/fmodstudioL.wasm - Web Assembly file needed to accompany fmodstudioL.js

Fastcomp BitCode - FMOD Core API

- /api/core/lib/fastcomp/bitcode/fmod.bc - Release binary for production code.
- /api/core/lib/fastcomp/bitcode/fmodL.bc - Release binary with logging enabled for development.
- /api/core/lib/fastcomp/bitcode/fmod_reduced.bc - Release binary with reduced features, for production code. Check the reduced library section for what is removed.

Fastcomp BitCode - FMOD Studio API

- /api/studio/lib/fastcomp/bitcode/fmodstudio.bc - Release binary for production code. Contains fmod_reduced.bc, see note below.
- /api/studio/lib/fastcomp/bitcode/fmodstudioL.bc - Release binary with logging enabled for development. Contains fmodL.bc, see note below.

Upstream W32 - FMOD Core API

- /api/core/lib/upstream/w32/fmod.a - Release binary for production code.
- /api/core/lib/upstream/w32/fmodL.a - Release binary with logging enabled for development.
- /api/core/lib/upstream/w32/fmod_reduced.a - Release binary with reduced features, for production code. Check the reduced library section for what is removed.

Upstream W32 - FMOD Studio API

- /api/studio/lib/upstream/w32/fmodstudio.a - Release binary for production code. Contains fmod_reduced.a, see note below.
- /api/studio/lib/upstream/w32/fmodstudioL.a - Release binary with logging enabled for development. Contains fmodL.a, see note below.

Note. The FMOD Studio API .js (and .bc) files already contain the core API, so you do NOT need to include the core API files as well.
Note2. The fmodstudio.js or .bc file links to the fmod_reduced version of the core, so accessing things like .ogg/.mp3 (see reduced ) through Studio::System::getCoreSystem are not supported.

### Build your own ASM.JS or WASM files from the BitCode (.bc) files.

FMOD's ASM.JS and WASM builds are supplied, but to build from LLVM bitcode (.bc) to any target (and compatible Emscripten version) for FMOD, use the following command line.

#### For the FMOD Core API

WASM:

    emcc --bind -Os -s EXPORT_NAME="'FMODModule'" -s MODULARIZE=1 -s FORCE_FILESYSTEM=1 -s EXTRA_EXPORTED_RUNTIME_METHODS="['cwrap','setValue','getValue']" -s WASM=1 -s ALLOW_MEMORY_GROWTH=1 -o fmod.js fmod.bc fmod_bindings.bc

ASM.JS:

    emcc --bind -Os -s EXPORT_NAME="'FMODModule'" -s MODULARIZE=1 -s FORCE_FILESYSTEM=1 -s EXTRA_EXPORTED_RUNTIME_METHODS="['cwrap','setValue','getValue']" -s WASM=0 -s "BINARYEN_TRAP_MODE='js'" -o fmod.js fmod.bc fmod_bindings.bc

#### For FMOD Studio Runtime API

WASM:

    emcc --bind -Os -s EXPORT_NAME="'FMODModule'" -s MODULARIZE=1 -s FORCE_FILESYSTEM=1 -s EXTRA_EXPORTED_RUNTIME_METHODS="['cwrap','setValue','getValue']" -s WASM=1 -s ALLOW_MEMORY_GROWTH=1 -o fmodstudio.js fmodstudio.bc fmodstudio_bindings.bc

ASM.JS:

    emcc --bind -Os -s EXPORT_NAME="'FMODModule'" -s MODULARIZE=1 -s FORCE_FILESYSTEM=1 -s EXTRA_EXPORTED_RUNTIME_METHODS="['cwrap','setValue','getValue']" -s WASM=0 -s "BINARYEN_TRAP_MODE='js'" -o fmodstudio.js fmodstudio.bc fmodstudio_bindings.bc

### Building a C/C++ program that uses FMOD libraries

If you have a C/C++ program that uses FMOD and are converting it to JavaScript using Emscripten, you will need to link the relevant FMOD binaries as per the Emscripten Documentation, and ensure the following flag is added in your Emscripten compilation arguments:

    -s EXTRA_EXPORTED_RUNTIME_METHODS=['cwrap','setValue','getValue']

### Browser Compatibility

- FMOD requires a browser to support web-audio to be compatible, this is supported by all current browsers, see details here.
- For using the WASM version of FMOD there are additional restrictions, however most mainstream browsers have support, see details here.
- Browser support for 5.1 / surround sound is supported but maybe limited to certain browsers, and was adopted early by Mozilla Firefox verified in version 50.1.0.
- Modern browsers require user interaction to initiate audio, see "Essential Startup Information" below for details.
- Browsers that support AudioWorkletNode will automatically use FMOD_OUTPUTTYPE_AUDIOWORKLET for this functionality.
- If AudioWorkletNode is supported, a fast code path using SharedArrayBuffer can be set from the server header, using "Cross-Origin-Opener-Policy: same-origin" and "Cross-Origin-Embedder-Policy: require-corp" policies. Please follow this guide for further information on how this is done.
- Presently there is a bug where AudioWorkletNode functionality will not download from the web if your website uses http but https works correctly. If it fails to download FMOD will default to FMOD_OUTPUTTYPE_WEBAUDIO.

### Output Modes

The FMOD engine supports two FMOD_OUTPUTTYPE modes for Web Audio.

- FMOD_OUTPUTTYPE_WEBAUDIO - at the code level this uses ScriptProcessorNode which is now deprecated. This output mode will only be used as legacy or a last resort fallback.
- FMOD_OUTPUTTYPE_AUDIOWORKLET - at the code level this uses AudioWorkletNode. FMOD will always default to this if the browser supports this functionality. FMOD also relies on the Worklet addModule function to be supported as well. If none of that functionality is supported FMOD will default to using FMOD_OUTPUTTYPE_WEBAUDIO. FMOD_OUTPUTTYPE_AUDIOWORKLET coupled with SharedArrayBuffer gives the best performance.

### Essential Startup Information

#### Start up code

To start with FMOD in a JavaScript environment you must initialize a global FMOD object, which you can then call FMOD functions with.

This involves declaring a variable (ie 'FMOD') then calling a constructor function on it ( 'ie FMODModule(FMOD); )

There are 2 optional functions which can be used to set up 'pre-runtime' information like file loading, and

    var FMOD = {};                          // FMOD global object which must be declared to enable 'main' and 'preRun' and then call the constructor function.
    FMOD['preRun'] = prerun;                // Will be called because FMOD runs, but after the Emscripten runtime has initialized
    FMOD['onRuntimeInitialized'] = main;    // Called when the Emscripten runtime has initialized
    FMOD['TOTAL_MEMORY'] = 64*1024*1024;    // (ASM.JS ONLY) FMOD Heap defaults to 16mb which is enough for this demo, but set it differently here for demonstration (64mb)
    FMODModule(FMOD);                       // Calling the constructor function with our object

#### Safari and Chrome Browser user interaction requirement (use for all browsers)

Safari (on iOS) and Chrome Browser (version 66 and above) both have a user interaction requirement, or audio will not be audible.
This was implemented to stop unscrupulous websites from auto playing audio in things like advertisements.

The workaround is that a web app must start an audio context from a touch event or a mouse click event, meaning there was user interaction.
FMOD's mechanism for doing this currently is to call System::mixerSuspend followed by System::mixerResume. This 'reinitializes' the webaudio driver and because it is in the context of a user interaction, the audio will start successfully.

It is up to the developer to determine where the click/touch must be at the start of the application, this will have to be part of the application design.
No audio is possible without it, so traditional splash screens or introductions are not possible with audio.

FMOD examples all have code that can be copied into a developer's application. Here is the relevant JavaScript code.

    // Set up iOS/Chrome workaround.  Webaudio is not allowed to start unless screen is touched or button is clicked.
    function resumeAudio()
    {
        if (!gAudioResumed)
        {
            console.log("Resetting audio driver based on user input.");

            result = gSystem.mixerSuspend();
            CHECK_RESULT(result);
            result = gSystem.mixerResume();
            CHECK_RESULT(result);

            gAudioResumed = true;
        }
    }

    var iOS = /iPad|iPhone|iPod/.test(navigator.userAgent) && !window.MSStream;
    if (iOS)
    {
        window.addEventListener('touchend', resumeAudio, false);
    }
    else
    {
        document.addEventListener('click', resumeAudio);
    }

### Reduced Feature build

fmod_reduced.js and fmodstudio.js feature removal

#### Overview

The fmod_reduced library is a smaller subset of features. The following is a list of what is removed.

fmodstudio.js links to fmod_reduced.js by default. To get the full feature set use fmodstudioL.js instead.

#### Codec Support

The following are removed in favour of .FSB only. .FSB support includes vorbis, FADPCM and pcm compression formats.

- AIFF file format support
- DLS file format support
- FLAC file format support
- WAV file format support
- MOD file format support
- S3M file format support
- XM file format support
- IT file format support
- MID/MIDI file format support
- MP2/MP3 file format support
- OGG file format support
- PLS/M3U file format support
- DLS file format support

#### DSP Effect support

The following are removed due to relative expensiveness of the effect and usage rates being below other types of effects.

- Envelope follower DSP support
- Cubic / Spline and 'none' interpolation support. Linear interpolation only.

#### Speaker mode support

- 5.1 / 7.1 etc support is supported on certain browsers.
- FMOD_OUTPUTTYPE_WEBAUDIO - System::setSoftwareFormat must be used to set the right speaker mode.
- FMOD_OUTPUTTYPE_AUDIOWORKLET - This will automatically select the speaker mode from the computer's OS speaker settings.
- Not all browsers support 5.1. See the table at the top of this document for tested working browsers.

#### Feature support

The following features have been removed

- 3D Geometry occlusion processing (via polygons).

### API - JavaScript port of a C/C++ API. Differences.

#### Setting and getting.

This is an important section if coming from knowledge of a C/C++ background of the FMOD API.

Javascript parameters are passed by value, therefore when you pass one to a function, it makes the concept of a 'getter' function difficult.
The variable's value cannot be changed by the function from the caller's perspective, but it can add a new member to the variable, which is the mechanism FMOD always uses when 'getting' data from a function.

In C the variable can be altered as it would be passed by reference (using pointers).
In FMOD for JavaScript, the variable you pass in gets a new member called val which contains the new data.
i.e.

    var outval;    // generic variable to reuse and be passed to FMOD functions.
    var name;      // to store name of sound.

    sound.getName(outval);
    name = outval.val;  // 'val' contains the data.  Pass it to the variable we want to keep.

    console.log(name);

All FMOD functions that produce data in a variable after calling a function return data this way.

#### Constants that started with FMOD_ in C/C++

In FMOD for JavaScript the enumerated values are members of the object declared at the top of the file.
As this would normally be a variable called 'FMOD' it would be redundant to keep the FMOD_ as part of the constant name, so it is removed to avoid duplication.
For example, instead of

    FMOD.FMOD_OK

in FMOD for HTML5 it becomes:

    FMOD.OK

similarly

    FMOD_INIT_NORMAL
    FMOD_DEFAULT
    FMOD_ERR_FILE_NOTFOUND
    FMOD_GUID
    FMOD_3D_ATTRIBUTES
    etc

becomes

    FMOD.INIT_NORMAL
    FMOD.DEFAULT
    FMOD.ERR_FILE_NOTFOUND
    FMOD.GUID()
    etc

Not that for attributes that start with a number after the FMOD namespace, it has to start with an underscore.
For example.

    FMOD._3D
    FMOD._2D
    FMOD._3D_ATTRIBUTES()

#### Using structures

In the above example you may notice that () is used to 'construct' a javascript object which represents a C structure in the FMOD API.
When using a structure to pass information to FMOD, a helper/constuctor function must be called to create the structure before using it/filling in its members, so that FMOD can understand what is being passed to it.
If these constructor functions are not used, the function it is being passed to will probably result in a 'binding' error (in the browser debug/log console/window).

    var guid = FMOD.GUID();
    var info = FMOD.STUDIO_BANK_INFO();

#### API differences

Some API constructs are redundant for JavaScript, so are removed from the API.

Examples are 'cbsize' inside a struct. The JavaScript version of a struct already knows its own size, so it is removed/redundant here.

Structures like FMOD_CREATESOUNDEXINFO, FMOD_ADVANCEDSETTINGS and FMOD_STUDIO_ADVANCEDSETTINGS have these members, it can just be left out.

### File Access

FMOD lets you load data from the host in a few different ways, depending on your setup.

#### Direct from host, via FMOD's filesystem

FMOD exposes an emscripten mechanism to mount/pre-load files in the 'prerun()' function, that is described above in the "Essential Startup Information" section of this document.
Call FMOD.FS_createPreloadedFile to register your files so that FMOD can use filenames in file related functions. See Emscripten docs for more on this function.
For example the playsound example

    // Will be called because FMOD runs, but after the Emscripten runtime has initialized
    // Call FMOD file preloading functions here to mount local files.  Otherwise load custom data from memory or use own file system.
    function prerun()
    {
        var fileUrl = "/public/js/";
        var fileName;
        var folderName = "/";
        var canRead = true;
        var canWrite = false;

        fileName = [
            "dog.wav",
            "lion.wav",
            "wave.mp3"
        ];

        for (var count = 0; count < fileName.length; count++)
        {
            FMOD.FS_createPreloadedFile(folderName, fileName[count], fileUrl + fileName[count], canRead, canWrite);
        }
    }

Then later in your app you can simply reference a file by path/filename.

    result = gSystem.createSound("/lion.wav", FMOD.LOOP_OFF, null, outval);
    CHECK_RESULT(result);

#### Via memory

If you have raw data in memory that you want to pass to FMOD , you can. Warning though, javascript passes data by value, so the memory usage will temporarily double for the sound data when it is passed to fmod.
The load_from_memory has an example of this

    var chars  = new Uint8Array(e.target.result);
    var outval = {};
    var result;
    var exinfo = FMOD.CREATESOUNDEXINFO();
    exinfo.length = chars.length;

    result = gSystem.createStream(chars.buffer, FMOD.LOOP_OFF | FMOD.OPENMEMORY, exinfo, outval);
    CHECK_RESULT(result);

#### Via callbacks

If you have a file system you can use file callbacks to load data into FMOD. See System::setFileSystem, or Studio::System::loadBankCustom
In load_bank example, there is a demonstration of this

    var info = new FMOD.STUDIO_BANK_INFO();

    info.opencallback = customFileOpen;
    info.closecallback = customFileClose;
    info.readcallback = customFileRead;
    info.seekcallback = customFileSeek;
    info.userdata = filename;

    result = gSystem.loadBankCustom(info, FMOD.STUDIO_LOAD_BANK_NONBLOCKING, outval);
    CHECK_RESULT(result);

In this case the filename is passed as userdata to let the callback get information for what file to load.
Here is the customFileOpen callback getting the filename and opening a file handle.
The file is opened in this case with a special FMOD provided file API. Replace this with your own API.

    function customFileOpen(name, filesize, handle, userdata)
    {
        var filesize_outval = {};
        var handle_outval = {}

        // We pass the filename into our callbacks via userdata in the custom info struct
        var filename = userdata;

        var result = FMOD.file_open(gSystemLowLevel, filename, filesize_outval, handle_outval)
        if (result == FMOD.OK)
        {
            filesize.val = filesize_outval.val;
            handle.val = handle_outval.val;
        }

        return result;
    }

To read data in the callback, into the buffer that FMOD has provided, FMOD has used a special technique where it passes the memory address, instead of a javascript buffer.
This means to write data to FMOD's buffer you must use FMOD.setValue using the buffer address, writing the data in a loop, a byte at a time. This could be optimized somewhat by using i32 to write 4 bytes at a time.

    function customFileRead(handle, buffer, sizebytes, bytesread, userdata)
    {
        var bytesread_outval = {};
        var buffer_outval = {};

        // Read from the file into a new buffer.  This part can be swapped for your own file system.
        var result = FMOD.file_read(handle, buffer_outval, sizebytes, bytesread_outval)   // read produces a new array with data.
        if (result == FMOD.OK)
        {
            bytesread.val = bytesread_outval.val;
        }

        // Copy the new buffer contents into the buffer that is passed into the callback.  'buffer' is a memory address, so we can only write to it with FMOD.setValue
        for (count = 0; count < bytesread.val; count++)
        {
            FMOD.setValue(buffer + count, buffer_outval.val[count], 'i8');      // See https://kripken.github.io/emscripten-site/docs/api_reference/preamble.js.html#accessing-memory for docs on setValue.
        }

        return result;
    }

### JavaScript specific functions for FMOD

#### Helper functions

FMOD comes with some functions to aid with reading file data and writing to memory buffers.
Here is the list of functions that are provided.

#### System

    FMOD['preRun'] = callback                // Variable to assign a function callback to.  Will be called before FMOD runs, but after the Emscripten runtime has initialized
    FMOD['onRuntimeInitialized'] = callback  // Assign a function to this member of FMOD, pre Called when the Emscripten runtime has initialized **
    FMODModule(fmodobject)                   // Constructor function to set up FMOD object before use.  fmodobject = the main FMOD object you will use throughout the application lifetime.

    FMOD.FS_createPreloadedFile              // Mounts a local file so that FMOD can recognize it when calling a function that uses a filename (ie loadBank/createSound).  See https://emscripten.org/docs/api_reference/Filesystem-API.html#FS.createPreloadedFile for more on this function.
    FMOD.System_Create                       // Only exported in FMOD.JS or FMODL.JS (Only use this function if using pure Core API).  See docs for System_Create
    FMOD.Studio_System_Create                // Only exported in FMODSTUDIO.JS or FMODSTUDIOL.JS (Only use this function if using Studio API). See docs for Studio::System_Create
    FMOD.ReadFile                            // Read the entire contents of a file into a memory variable, as preloaded by FMOD.FS_createPreloadedFile.  Call FMOD.Memory_Free on the variable after using it.  NOTE: output variable has 'val' and 'length' as the JS members to use as parameters to System::loadBankMemory.
    FMOD.Memory_Free                         // Free memory allocated by FMOD internally in FMOD.ReadFile

#### File

    FMOD.file_open
    FMOD.file_close
    FMOD.file_read
    FMOD.file_seek

#### Misc

    FMOD.setValue                           // See https://kripken.github.io/emscripten-site/docs/api_reference/preamble.js.html#accessing-memory for docs on setValue.

### Linking FMOD for HTML5 in a C program that is to be converted via emscripten

You should be able to port existing C code with no special HTML5 related functionality. Link the fmod.bc file or the fmodstudio.bc file (not both!) into your application to get it to link.
As mentioned previously FMOD_NONBLOCKING will not be needed, so your program might hang if System::update is not processed during any logic that waits on a getState function.

### Performance and Memory

#### CPU Overhead

By default FMOD mixes at 48000hz. If the browser is not running at that rate, it will introduce a resampler to convert the rate, which consumes CPU time and adds a DSP block worth of latency.
This can be solved by querying the hardware's rate before System::init, and calling System::setSoftwareFormat to the same rate as the output. Here is an example (from the PlaySound example)

    var outval = {};
    result = gSystem.getDriverInfo(0, null, null, outval, null, null);
    CHECK_RESULT(result);
    result = gSystem.setSoftwareFormat(outval.val, FMOD.SPEAKERMODE_DEFAULT, 0)
    CHECK_RESULT(result);

#### Audio Stability (Stuttering)

Some devices cannot handle the default buffer size of 4 blocks of 1024 samples (4096 samples) without stuttering, so to avoid this set the buffer size in your application to 2 blocks of 2048.
Here is an example

    result = gSystem.setDSPBufferSize(2048, 2);
    CHECK_RESULT(result);

#### Threads

As stated in the introduction, FMOD for HTML5 does not have access to any threads so any loading/mixing/decoding/streaming/dsp has to be run in a blocking mode, from the main application loop.

Keep this in mind when loading sounds, or implementing DSP that may take a large time slice. If the application pre-loads sounds, and has a fast enough framerate that the FMOD mixing can execute in the same frame (with time left over) then there should be no audible glitching or frame rate glitching.

#### 'Heap' Memory

FMOD defaults to 16mb of memory to load sounds with and create FMOD objects with. Use the following global before calling the main FMOD constructor object, to control how much memory to use.

    FMOD['TOTAL_MEMORY'] = 64*1024*1024;    // (ASM.JS ONLY) FMOD Heap defaults to 16mb which is enough for this demo, but set it differently here for demonstration (64mb)

For WASM support, FMOD uses ALLOW_MEMORY_GROWTH, which is more dynamic, so TOTAL_MEMORY is ignored.

### Limitations

#### Non-blocking loading

FMOD_NONBLOCKING and FMOD_STUDIO_LOAD_BANK_NONBLOCKING do not allow sound to load in the background, but it will process loading from the update loop instead.

Streaming is executed from the main thread. This may impact performance, so pre-loading sounds is preferred.

Streaming infers that the source is being loaded from 'disk' which is not usually done with HTML5, because data is usually pre-packaged with the javascript file, or streamed over http (from an external URL) so loading sounds into memory might make more sense here.

### Known Issues

The following functions are not supported.
Some have no place in JavaScript (ie loadPlugin) but others are incomplete at this point and can be added in a later point release.

- System::loadPlugin
- Geometry::addPolygon
- Geometry::save

The following callbacks remain unimplemented at this point, so they will not work.

- FMOD_FILE_ASYNCREAD_CALLBACK
- FMOD_FILE_ASYNCCANCEL_CALLBACK
- FMOD_3D_ROLLOFF_CALLBACK
- FMOD_STUDIO_COMMANDREPLAY_FRAME_CALLBACK
- FMOD_STUDIO_COMMANDREPLAY_LOAD_BANK_CALLBACK
- FMOD_STUDIO_COMMANDREPLAY_CREATE_INSTANCE_CALLBACK