diff --git a/.clang-format b/.clang-format index 0d953b84..f8aef8a9 100644 --- a/.clang-format +++ b/.clang-format @@ -125,7 +125,8 @@ ObjCSpaceAfterProperty: false ObjCSpaceBeforeProtocolList: true --- Language: JavaScript -JavaScriptQuotes: Leave -JavaScriptWrapImports: true +DisableFormat: true +--- +Language: Json +DisableFormat: true ... - diff --git a/.cmake-format b/.cmake-format new file mode 100644 index 00000000..e1a9abeb --- /dev/null +++ b/.cmake-format @@ -0,0 +1,2 @@ +with section("format"): + tab_size = 4 diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index b9eddfd8..79bd2615 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -3,6 +3,15 @@ on: pull_request: jobs: + pre-commit: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + with: + submodules: recursive + - uses: actions/setup-python@v5 + - uses: pre-commit/action@v3.0.1 + build: strategy: matrix: @@ -58,12 +67,16 @@ jobs: cmake --build build/consumer-b --config ${{ matrix.build_type }} all-passed: - needs: build + needs: [pre-commit, build] runs-on: ubuntu-latest if: always() steps: - name: Check all matrix jobs passed run: | + if [ "${{ needs.pre-commit.result }}" != "success" ]; then + echo "pre-commit failed" + exit 1 + fi if [ "${{ needs.build.result }}" != "success" ]; then echo "build matrix failed" exit 1 diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 718b19b0..d5de3f54 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -1,9 +1,25 @@ +exclude: ^external_libraries/ repos: + - repo: https://github.com/pre-commit/pre-commit-hooks + rev: v6.0.0 + hooks: + - id: check-yaml + args: [--allow-multiple-documents] + - id: end-of-file-fixer + - id: trailing-whitespace + - id: pretty-format-json + args: [--autofix, --no-sort-keys] + - repo: https://github.com/pre-commit/mirrors-clang-format rev: v19.1.7 hooks: - id: clang-format + - repo: https://github.com/cheshirekow/cmake-format-precommit + rev: v0.6.13 + hooks: + - id: cmake-format + - repo: https://github.com/psf/black rev: 25.1.0 hooks: diff --git a/CHANGELOG.md b/CHANGELOG.md index b07a3e49..ad11dffc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -24,8 +24,14 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - `docs/osc-api.md` (moved from `doc/OSC API.md`) - `examples/README.md` describing the thADDeus and sampler examples +### Removed + +- PNaCl test harness (`tests/pnacl/`, `examples/common/`) +- Duplicate `tinydir` copy in `examples/sampler/libs/`; Xcode projects now reference `external_libraries/tinydir` + ### Changed +- Disabled clang-format for JavaScript files - Dependency management modernised: `FetchContent` for oscpp and googletest; Boost 1.91.0 vendored with `methcla_boost` namespace to avoid symbol collisions (#129) - C++ standard raised to C++17 - `Driver::Options` channel and buffer size fields changed from `int` to `size_t` (#80) diff --git a/CMakeLists.txt b/CMakeLists.txt index ed658cea..2f7d3f72 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -14,18 +14,14 @@ endif() set(CMAKE_CXX_STANDARD 17) set(CMAKE_C_STANDARD 99) -set(methcla_warnings - -Wall - -Wextra - -Wstrict-aliasing - -Werror) +set(methcla_warnings -Wall -Wextra -Wstrict-aliasing -Werror) function(methcla_target_warnings target) - target_compile_options(${target} PRIVATE - "$<$:${methcla_warnings}>" - "$<$:${methcla_warnings}>" - "$<$:${methcla_warnings}>" - ) + target_compile_options( + ${target} + PRIVATE "$<$:${methcla_warnings}>" + "$<$:${methcla_warnings}>" + "$<$:${methcla_warnings}>") endfunction() include(GNUInstallDirs) @@ -44,7 +40,8 @@ if(PROJECT_IS_TOP_LEVEL) add_subdirectory(tools) endif() -install(EXPORT methclaTargets +install( + EXPORT methclaTargets NAMESPACE methcla:: DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/methcla) @@ -53,7 +50,6 @@ write_basic_package_version_file( VERSION ${PROJECT_VERSION} COMPATIBILITY SameMajorVersion) -install(FILES - cmake/methclaConfig.cmake - "${CMAKE_CURRENT_BINARY_DIR}/methclaConfigVersion.cmake" - DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/methcla) +install(FILES cmake/methclaConfig.cmake + "${CMAKE_CURRENT_BINARY_DIR}/methclaConfigVersion.cmake" + DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/methcla) diff --git a/CMakePresets.json b/CMakePresets.json index 96dbfb34..0527201b 100644 --- a/CMakePresets.json +++ b/CMakePresets.json @@ -1,6 +1,10 @@ { "version": 3, - "cmakeMinimumRequired": { "major": 3, "minor": 24, "patch": 0 }, + "cmakeMinimumRequired": { + "major": 3, + "minor": 24, + "patch": 0 + }, "configurePresets": [ { "name": "base", diff --git a/cmake/dependencies.cmake b/cmake/dependencies.cmake index aae2cee3..bc45a2fd 100644 --- a/cmake/dependencies.cmake +++ b/cmake/dependencies.cmake @@ -3,20 +3,22 @@ include(FetchContent) # oscpp — header-only OSC library, part of methcla's public API. # OSCPP_BUILD_TESTS defaults to PROJECT_IS_TOP_LEVEL, so tests are off when # consumed via FetchContent. -FetchContent_Declare(oscpp +FetchContent_Declare( + oscpp GIT_REPOSITORY https://github.com/kaoskorobase/oscpp.git GIT_TAG a62fe7690ce3563c997d7c9915d8cb54ff8f79b0 - FIND_PACKAGE_ARGS CONFIG -) + FIND_PACKAGE_ARGS CONFIG) FetchContent_MakeAvailable(oscpp) if(METHCLA_BUILD_TESTS) # googletest — test-only dependency - FetchContent_Declare(googletest + FetchContent_Declare( + googletest GIT_REPOSITORY https://github.com/google/googletest.git GIT_TAG v1.14.0 - FIND_PACKAGE_ARGS NAMES GTest - ) - set(INSTALL_GTEST OFF CACHE BOOL "" FORCE) + FIND_PACKAGE_ARGS NAMES GTest) + set(INSTALL_GTEST + OFF + CACHE BOOL "" FORCE) FetchContent_MakeAvailable(googletest) endif() diff --git a/docs/osc-api.md b/docs/osc-api.md index 02e9f3c3..d564b510 100644 --- a/docs/osc-api.md +++ b/docs/osc-api.md @@ -47,9 +47,9 @@ Encode a `Methcla_Time` value as a 64 bit unsigned integer for use as an OSC bun * `kMethcla_BusMappingFeedback = 0x02` Don't zero bus before reading, allowing feedback loops with a delay of one block size. - + * `kMethcla_BusMappingReplace = 0x04` - + Zero bus before reading (default). * `/synth/map/output i:node-id i:index i:bus-id i:flags` @@ -67,9 +67,9 @@ Encode a `Methcla_Time` value as a 64 bit unsigned integer for use as an OSC bun * `kMethcla_BusMappingFeedback = 0x02` Mix output with previous bus contents (default). - + * `kMethcla_BusMappingReplace = 0x04` - + Replace bus contents by output. * `/node/free` i:node-id diff --git a/examples/common/common.js b/examples/common/common.js deleted file mode 100644 index 8e231254..00000000 --- a/examples/common/common.js +++ /dev/null @@ -1,515 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -// Copyright 2011, The Chromium Authors -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// Copyright 2011, The Chromium Authors -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -// Set to true when the Document is loaded IFF "test=true" is in the query -// string. -var isTest = false; - -// Set to true when loading a "Release" NaCl module, false when loading a -// "Debug" NaCl module. -var isRelease = false; - -// Javascript module pattern: -// see http://en.wikipedia.org/wiki/Unobtrusive_JavaScript#Namespaces -// In essence, we define an anonymous function which is immediately called and -// returns a new object. The new object contains only the exported definitions; -// all other definitions in the anonymous function are inaccessible to external -// code. -var common = (function() { - - function isHostToolchain(tool) { - return tool == 'win' || tool == 'linux' || tool == 'mac'; - } - - /** - * Return the mime type for NaCl plugin. - * - * @param {string} tool The name of the toolchain, e.g. "glibc", "newlib" etc. - * @return {string} The mime-type for the kind of NaCl plugin matching - * the given toolchain. - */ - function mimeTypeForTool(tool) { - // For NaCl modules use application/x-nacl. - var mimetype = 'application/x-nacl'; - if (isHostToolchain(tool)) { - // For non-NaCl PPAPI plugins use the x-ppapi-debug/release - // mime type. - if (isRelease) - mimetype = 'application/x-ppapi-release'; - else - mimetype = 'application/x-ppapi-debug'; - } else if (tool == 'pnacl') { - mimetype = 'application/x-pnacl'; - } - return mimetype; - } - - /** - * Check if the browser supports NaCl plugins. - * - * @param {string} tool The name of the toolchain, e.g. "glibc", "newlib" etc. - * @return {bool} True if the browser supports the type of NaCl plugin - * produced by the given toolchain. - */ - function browserSupportsNaCl(tool) { - // Assume host toolchains always work with the given browser. - // The below mime-type checking might not work with - // --register-pepper-plugins. - if (isHostToolchain(tool)) { - return true; - } - var mimetype = mimeTypeForTool(tool); - return navigator.mimeTypes[mimetype] !== undefined; - } - - /** - * Inject a script into the DOM, and call a callback when it is loaded. - * - * @param {string} url The url of the script to load. - * @param {Function} onload The callback to call when the script is loaded. - * @param {Function} onerror The callback to call if the script fails to load. - */ - function injectScript(url, onload, onerror) { - var scriptEl = document.createElement('script'); - scriptEl.type = 'text/javascript'; - scriptEl.src = url; - scriptEl.onload = onload; - if (onerror) { - scriptEl.addEventListener('error', onerror, false); - } - document.head.appendChild(scriptEl); - } - - /** - * Run all tests for this example. - * - * @param {Object} moduleEl The module DOM element. - */ - function runTests(moduleEl) { - console.log('runTests()'); - common.tester = new Tester(); - - // All NaCl SDK examples are OK if the example exits cleanly; (i.e. the - // NaCl module returns 0 or calls exit(0)). - // - // Without this exception, the browser_tester thinks that the module - // has crashed. - common.tester.exitCleanlyIsOK(); - - common.tester.addAsyncTest('loaded', function(test) { - test.pass(); - }); - - if (typeof window.addTests !== 'undefined') { - window.addTests(); - } - - common.tester.waitFor(moduleEl); - common.tester.run(); - } - - /** - * Create the Native Client element as a child of the DOM element - * named "listener". - * - * @param {string} name The name of the example. - * @param {string} tool The name of the toolchain, e.g. "glibc", "newlib" etc. - * @param {string} path Directory name where .nmf file can be found. - * @param {number} width The width to create the plugin. - * @param {number} height The height to create the plugin. - * @param {Object} attrs Dictionary of attributes to set on the module. - */ - function createNaClModule(name, tool, path, width, height, attrs) { - var moduleEl = document.createElement('embed'); - moduleEl.setAttribute('name', 'nacl_module'); - moduleEl.setAttribute('id', 'nacl_module'); - moduleEl.setAttribute('width', width); - moduleEl.setAttribute('height', height); - moduleEl.setAttribute('path', path); - moduleEl.setAttribute('src', path + '/' + name + '.nmf'); - - // Add any optional arguments - if (attrs) { - for (var key in attrs) { - moduleEl.setAttribute(key, attrs[key]); - } - } - - var mimetype = mimeTypeForTool(tool); - moduleEl.setAttribute('type', mimetype); - - // The element is wrapped inside a
, which has both a 'load' - // and a 'message' event listener attached. This wrapping method is used - // instead of attaching the event listeners directly to the element - // to ensure that the listeners are active before the NaCl module 'load' - // event fires. - var listenerDiv = document.getElementById('listener'); - listenerDiv.appendChild(moduleEl); - - // Host plugins don't send a moduleDidLoad message. We'll fake it here. - var isHost = isHostToolchain(tool); - if (isHost) { - window.setTimeout(function() { - moduleEl.readyState = 1; - moduleEl.dispatchEvent(new CustomEvent('loadstart')); - moduleEl.readyState = 4; - moduleEl.dispatchEvent(new CustomEvent('load')); - moduleEl.dispatchEvent(new CustomEvent('loadend')); - }, 100); // 100 ms - } - - // This is code that is only used to test the SDK. - if (isTest) { - var loadNaClTest = function() { - injectScript('nacltest.js', function() { - runTests(moduleEl); - }); - }; - - // Try to load test.js for the example. Whether or not it exists, load - // nacltest.js. - injectScript('test.js', loadNaClTest, loadNaClTest); - } - } - - /** - * Add the default "load" and "message" event listeners to the element with - * id "listener". - * - * The "load" event is sent when the module is successfully loaded. The - * "message" event is sent when the naclModule posts a message using - * PPB_Messaging.PostMessage() (in C) or pp::Instance().PostMessage() (in - * C++). - */ - function attachDefaultListeners() { - var listenerDiv = document.getElementById('listener'); - listenerDiv.addEventListener('load', moduleDidLoad, true); - listenerDiv.addEventListener('message', handleMessage, true); - listenerDiv.addEventListener('crash', handleCrash, true); - if (typeof window.attachListeners !== 'undefined') { - window.attachListeners(); - } - } - - - /** - * Called when the Browser can not communicate with the Module - * - * This event listener is registered in attachDefaultListeners above. - */ - function handleCrash(event) { - if (common.naclModule.exitStatus == -1) { - updateStatus('CRASHED'); - } else { - updateStatus('EXITED [' + common.naclModule.exitStatus + ']'); - } - if (typeof window.handleCrash !== 'undefined') { - window.handleCrash(common.naclModule.lastError); - } - } - - /** - * Called when the NaCl module is loaded. - * - * This event listener is registered in attachDefaultListeners above. - */ - function moduleDidLoad() { - common.naclModule = document.getElementById('nacl_module'); - updateStatus('RUNNING'); - - if (typeof window.moduleDidLoad !== 'undefined') { - window.moduleDidLoad(); - } - } - - /** - * Hide the NaCl module's embed element. - * - * We don't want to hide by default; if we do, it is harder to determine that - * a plugin failed to load. Instead, call this function inside the example's - * "moduleDidLoad" function. - * - */ - function hideModule() { - // Setting common.naclModule.style.display = "None" doesn't work; the - // module will no longer be able to receive postMessages. - common.naclModule.style.height = '0'; - } - - /** - * Remove the NaCl module from the page. - */ - function removeModule() { - common.naclModule.parentNode.removeChild(common.naclModule); - common.naclModule = null; - } - - /** - * Return true when |s| starts with the string |prefix|. - * - * @param {string} s The string to search. - * @param {string} prefix The prefix to search for in |s|. - */ - function startsWith(s, prefix) { - // indexOf would search the entire string, lastIndexOf(p, 0) only checks at - // the first index. See: http://stackoverflow.com/a/4579228 - return s.lastIndexOf(prefix, 0) === 0; - } - - /** Maximum length of logMessageArray. */ - var kMaxLogMessageLength = 20; - - /** An array of messages to display in the element with id "log". */ - var logMessageArray = []; - - /** - * Add a message to an element with id "log". - * - * This function is used by the default "log:" message handler. - * - * @param {string} message The message to log. - */ - function logMessage(message) { - logMessageArray.push(message); - if (logMessageArray.length > kMaxLogMessageLength) - logMessageArray.shift(); - - document.getElementById('log').textContent = logMessageArray.join('\n'); - console.log(message); - } - - /** - */ - var defaultMessageTypes = { - 'alert': alert, - 'log': logMessage - }; - - /** - * Called when the NaCl module sends a message to JavaScript (via - * PPB_Messaging.PostMessage()) - * - * This event listener is registered in createNaClModule above. - * - * @param {Event} message_event A message event. message_event.data contains - * the data sent from the NaCl module. - */ - function handleMessage(message_event) { - if (typeof message_event.data === 'object') { - var type = message_event.data['type']; - if (type !== undefined) { - var func = defaultMessageTypes['type']; - if (func !== undefined) { - func(message_event.data); - return; - } - } - } else if (typeof message_event.data === 'string') { - logMessage(message_event.data); - return; - } - - if (typeof window.handleMessage !== 'undefined') { - window.handleMessage(message_event); - return; - } - - logMessage('Unhandled message: ' + message_event.data); - } - - /** - * Called when the DOM content has loaded; i.e. the page's document is fully - * parsed. At this point, we can safely query any elements in the document via - * document.querySelector, document.getElementById, etc. - * - * @param {string} name The name of the example. - * @param {string} tool The name of the toolchain, e.g. "glibc", "newlib" etc. - * @param {string} path Directory name where .nmf file can be found. - * @param {number} width The width to create the plugin. - * @param {number} height The height to create the plugin. - * @param {Object} attrs Optional dictionary of additional attributes. - */ - function domContentLoaded(name, tool, path, width, height, attrs) { - // If the page loads before the Native Client module loads, then set the - // status message indicating that the module is still loading. Otherwise, - // do not change the status message. - updateStatus('Page loaded.'); - if (!browserSupportsNaCl(tool)) { - updateStatus( - 'Browser does not support NaCl (' + tool + '), or NaCl is disabled'); - } else if (common.naclModule == null) { - updateStatus('Creating embed: ' + tool); - - // We use a non-zero sized embed to give Chrome space to place the bad - // plug-in graphic, if there is a problem. - width = typeof width !== 'undefined' ? width : 200; - height = typeof height !== 'undefined' ? height : 200; - attachDefaultListeners(); - createNaClModule(name, tool, path, width, height, attrs); - } else { - // It's possible that the Native Client module onload event fired - // before the page's onload event. In this case, the status message - // will reflect 'SUCCESS', but won't be displayed. This call will - // display the current message. - updateStatus('Waiting.'); - } - } - - /** Saved text to display in the element with id 'statusField'. */ - var statusText = 'NO-STATUSES'; - - /** - * Set the global status message. If the element with id 'statusField' - * exists, then set its HTML to the status message as well. - * - * @param {string} opt_message The message to set. If null or undefined, then - * set element 'statusField' to the message from the last call to - * updateStatus. - */ - function updateStatus(opt_message) { - if (opt_message) { - statusText = opt_message; - } - var statusField = document.getElementById('statusField'); - if (statusField) { - statusField.innerHTML = statusText; - } - } - - /** - * From https://developer.mozilla.org/en-US/docs/DOM/window.location - */ - function getSearchVars() { - var result = {}; - if (window.location.search.length > 1) { - var pairs = window.location.search.substr(1).split('&'); - for (var key_ix = 0; key_ix < pairs.length; key_ix++) { - var keyValue = pairs[key_ix].split('='); - result[unescape(keyValue[0])] = - keyValue.length > 1 ? unescape(keyValue[1]) : ''; - } - } - return result; - } - - // The symbols to export. - return { - /** A reference to the NaCl module, once it is loaded. */ - naclModule: null, - - attachDefaultListeners: attachDefaultListeners, - domContentLoaded: domContentLoaded, - createNaClModule: createNaClModule, - hideModule: hideModule, - removeModule: removeModule, - logMessage: logMessage, - updateStatus: updateStatus, - getSearchVars: getSearchVars - }; - -}()); - -// Listen for the DOM content to be loaded. This event is fired when parsing of -// the page's document has finished. -document.addEventListener('DOMContentLoaded', function() { - var body = document.body; - - // The data-* attributes on the body can be referenced via body.dataset. - if (body.dataset) { - var loadFunction; - if (!body.dataset.customLoad) { - loadFunction = common.domContentLoaded; - } else if (typeof window.domContentLoaded !== 'undefined') { - loadFunction = window.domContentLoaded; - } - - var searchVars = common.getSearchVars(); - - if (loadFunction) { - var toolchains = body.dataset.tools.split(' '); - var configs = body.dataset.configs.split(' '); - - var attrs = {}; - if (body.dataset.attrs) { - var attr_list = body.dataset.attrs.split(' '); - for (var key in attr_list) { - var attr = attr_list[key].split('='); - var key = attr[0]; - var value = attr[1]; - attrs[key] = value; - } - } - - var tc = toolchains.indexOf(searchVars.tc) !== -1 ? - searchVars.tc : toolchains[0]; - var config = configs.indexOf(searchVars.config) !== -1 ? - searchVars.config : configs[0]; - var pathFormat = body.dataset.path; - var path = pathFormat.replace('{tc}', tc).replace('{config}', config); - - isTest = searchVars.test === 'true'; - isRelease = path.toLowerCase().indexOf('release') != -1; - - loadFunction(body.dataset.name, tc, path, body.dataset.width, - body.dataset.height, attrs); - } - } -}); diff --git a/examples/sampler/ios/MethclaSampler.xcodeproj/project.pbxproj b/examples/sampler/ios/MethclaSampler.xcodeproj/project.pbxproj index 109c6498..6ce48f86 100644 --- a/examples/sampler/ios/MethclaSampler.xcodeproj/project.pbxproj +++ b/examples/sampler/ios/MethclaSampler.xcodeproj/project.pbxproj @@ -373,7 +373,7 @@ ARCHS = armv7; GCC_PRECOMPILE_PREFIX_HEADER = YES; GCC_PREFIX_HEADER = "MethclaSampler/MethclaSampler-Prefix.pch"; - HEADER_SEARCH_PATHS = ../libs/tinydir; + HEADER_SEARCH_PATHS = ../../../external_libraries/tinydir; INFOPLIST_FILE = "MethclaSampler/MethclaSampler-Info.plist"; IPHONEOS_DEPLOYMENT_TARGET = 5.0; PRODUCT_NAME = "$(TARGET_NAME)"; @@ -387,7 +387,7 @@ ARCHS = armv7; GCC_PRECOMPILE_PREFIX_HEADER = YES; GCC_PREFIX_HEADER = "MethclaSampler/MethclaSampler-Prefix.pch"; - HEADER_SEARCH_PATHS = ../libs/tinydir; + HEADER_SEARCH_PATHS = ../../../external_libraries/tinydir; INFOPLIST_FILE = "MethclaSampler/MethclaSampler-Info.plist"; IPHONEOS_DEPLOYMENT_TARGET = 5.0; PRODUCT_NAME = "$(TARGET_NAME)"; diff --git a/examples/sampler/ios/MethclaSampler/AppDelegate.m b/examples/sampler/ios/MethclaSampler/AppDelegate.m index a9243843..167929de 100644 --- a/examples/sampler/ios/MethclaSampler/AppDelegate.m +++ b/examples/sampler/ios/MethclaSampler/AppDelegate.m @@ -13,7 +13,8 @@ @implementation AppDelegate - (BOOL)application:(UIApplication*)application - didFinishLaunchingWithOptions:(NSDictionary*)launchOptions { + didFinishLaunchingWithOptions:(NSDictionary*)launchOptions +{ self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]]; // Override point for customization after application launch. @@ -35,7 +36,8 @@ - (BOOL)application:(UIApplication*)application return YES; } -- (void)applicationWillResignActive:(UIApplication*)application { +- (void)applicationWillResignActive:(UIApplication*)application +{ // Sent when the application is about to move from active to inactive state. // This can occur for certain types of temporary interruptions (such as an // incoming phone call or SMS message) or when the user quits the @@ -44,7 +46,8 @@ - (void)applicationWillResignActive:(UIApplication*)application { // OpenGL ES frame rates. Games should use this method to pause the game. } -- (void)applicationDidEnterBackground:(UIApplication*)application { +- (void)applicationDidEnterBackground:(UIApplication*)application +{ // Use this method to release shared resources, save user data, invalidate // timers, and store enough application state information to restore your // application to its current state in case it is terminated later. If your @@ -52,19 +55,22 @@ - (void)applicationDidEnterBackground:(UIApplication*)application { // of applicationWillTerminate: when the user quits. } -- (void)applicationWillEnterForeground:(UIApplication*)application { +- (void)applicationWillEnterForeground:(UIApplication*)application +{ // Called as part of the transition from the background to the inactive // state; here you can undo many of the changes made on entering the // background. } -- (void)applicationDidBecomeActive:(UIApplication*)application { +- (void)applicationDidBecomeActive:(UIApplication*)application +{ // Restart any tasks that were paused (or not yet started) while the // application was inactive. If the application was previously in the // background, optionally refresh the user interface. } -- (void)applicationWillTerminate:(UIApplication*)application { +- (void)applicationWillTerminate:(UIApplication*)application +{ // Called when the application is about to terminate. Save data if // appropriate. See also applicationDidEnterBackground:. } diff --git a/examples/sampler/ios/MethclaSampler/ViewController.mm b/examples/sampler/ios/MethclaSampler/ViewController.mm index a09e09de..e5ae0385 100644 --- a/examples/sampler/ios/MethclaSampler/ViewController.mm +++ b/examples/sampler/ios/MethclaSampler/ViewController.mm @@ -6,14 +6,16 @@ // Copyright (c) 2013 Samplecount. All rights reserved. // -#include - #import "ViewController.h" + #import "Engine.hpp" +#include + inline NSString* resourcePath(NSString* component) { - return [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:component]; + return [[[NSBundle mainBundle] resourcePath] + stringByAppendingPathComponent:component]; } @interface ViewController () @@ -32,12 +34,15 @@ - (void)viewDidLoad [self.view setMultipleTouchEnabled:YES]; // Set up the sound engine - try { + try + { Methcla::Examples::Sampler::Engine::Options options; options.soundFileAPI = methcla_soundfile_api_extaudiofile; options.soundDir = [resourcePath(@"sounds") UTF8String]; engine = new Methcla::Examples::Sampler::Engine(options); - } catch (std::exception& e) { + } + catch (std::exception& e) + { std::cerr << e.what() << std::endl; } } @@ -51,34 +56,37 @@ - (void)didReceiveMemoryWarning - (CGPoint)relativeLocation:(UITouch*)touch inView:(UIView*)view { const CGPoint pt = [touch locationInView:view]; - const CGSize sz = view.bounds.size; - return { .x = pt.x / sz.width, .y = pt.y / sz.height }; + const CGSize sz = view.bounds.size; + return {.x = pt.x / sz.width, .y = pt.y / sz.height}; } -- (void) touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event +- (void)touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event { - for (UITouch* touch in touches) { - const CGPoint pt = [self relativeLocation:touch inView:self.view]; - engine->startVoice(reinterpret_cast(touch), 0, pt.x); + for (UITouch* touch in touches) + { + const CGPoint pt = [self relativeLocation:touch inView:self.view]; + engine->startVoice(reinterpret_cast(touch), 0, pt.x); } } -- (void) touchesMoved:(NSSet*)touches withEvent:(UIEvent*)event +- (void)touchesMoved:(NSSet*)touches withEvent:(UIEvent*)event { - for (UITouch* touch in touches) { - const CGPoint pt = [self relativeLocation:touch inView:self.view]; + for (UITouch* touch in touches) + { + const CGPoint pt = [self relativeLocation:touch inView:self.view]; engine->updateVoice(reinterpret_cast(touch), pt.x); } } -- (void) touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event +- (void)touchesEnded:(NSSet*)touches withEvent:(UIEvent*)event { - for (UITouch* touch in touches) { - engine->stopVoice(reinterpret_cast(touch)); + for (UITouch* touch in touches) + { + engine->stopVoice(reinterpret_cast(touch)); } } -- (void) touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event +- (void)touchesCancelled:(NSSet*)touches withEvent:(UIEvent*)event { [self touchesEnded:touches withEvent:event]; } diff --git a/examples/sampler/ios/MethclaSampler/en.lproj/InfoPlist.strings b/examples/sampler/ios/MethclaSampler/en.lproj/InfoPlist.strings index 477b28ff..b92732c7 100644 --- a/examples/sampler/ios/MethclaSampler/en.lproj/InfoPlist.strings +++ b/examples/sampler/ios/MethclaSampler/en.lproj/InfoPlist.strings @@ -1,2 +1 @@ /* Localized versions of Info.plist keys */ - diff --git a/examples/sampler/libs/tinydir/tinydir.h b/examples/sampler/libs/tinydir/tinydir.h deleted file mode 100644 index 11a334cd..00000000 --- a/examples/sampler/libs/tinydir/tinydir.h +++ /dev/null @@ -1,421 +0,0 @@ -/* -Copyright (c) 2013, Cong Xu -All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are met: - -1. Redistributions of source code must retain the above copyright notice, this - list of conditions and the following disclaimer. -2. Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ -#ifndef TINYDIR_H -#define TINYDIR_H - -#include -#include -#include -#ifdef _MSC_VER -# define WIN32_LEAN_AND_MEAN -# include -# pragma warning(disable : 4996) -#else -# include -# include -#endif - -/* types */ - -#define _TINYDIR_PATH_MAX 4096 -#ifdef _MSC_VER -/* extra chars for the "\\*" mask */ -# define _TINYDIR_PATH_EXTRA 2 -#else -# define _TINYDIR_PATH_EXTRA 0 -#endif -#define _TINYDIR_FILENAME_MAX 256 - -#ifdef _MSC_VER -# define strncasecmp _strnicmp -#endif - -#ifdef _MSC_VER -# define _TINYDIR_FUNC static __inline -#else -# define _TINYDIR_FUNC static __inline__ -#endif - -typedef struct -{ - char path[_TINYDIR_PATH_MAX]; - char name[_TINYDIR_FILENAME_MAX]; - int is_dir; - int is_reg; - -#ifdef _MSC_VER -#else - struct stat _s; -#endif -} tinydir_file; - -typedef struct -{ - char path[_TINYDIR_PATH_MAX]; - int has_next; - int n_files; - - tinydir_file* _files; -#ifdef _MSC_VER - HANDLE _h; - WIN32_FIND_DATA _f; -#else - DIR* _d; - struct dirent* _e; -#endif -} tinydir_dir; - -/* declarations */ - -_TINYDIR_FUNC -int tinydir_open(tinydir_dir* dir, const char* path); -_TINYDIR_FUNC -int tinydir_open_sorted(tinydir_dir* dir, const char* path); -_TINYDIR_FUNC -void tinydir_close(tinydir_dir* dir); - -_TINYDIR_FUNC -int tinydir_next(tinydir_dir* dir); -_TINYDIR_FUNC -int tinydir_readfile(const tinydir_dir* dir, tinydir_file* file); -_TINYDIR_FUNC -int tinydir_readfile_n(const tinydir_dir* dir, tinydir_file* file, int i); -_TINYDIR_FUNC -int tinydir_open_subdir_n(tinydir_dir* dir, int i); - -_TINYDIR_FUNC -int _tinydir_file_cmp(const void* a, const void* b); - -/* definitions*/ - -_TINYDIR_FUNC -int tinydir_open(tinydir_dir* dir, const char* path) -{ - if (dir == NULL || path == NULL || strlen(path) == 0) - { - errno = EINVAL; - return -1; - } - if (strlen(path) + _TINYDIR_PATH_EXTRA >= _TINYDIR_PATH_MAX) - { - errno = ENAMETOOLONG; - return -1; - } - - /* initialise dir */ - dir->_files = NULL; -#ifdef _MSC_VER - dir->_h = INVALID_HANDLE_VALUE; -#else - dir->_d = NULL; -#endif - tinydir_close(dir); - - strcpy(dir->path, path); -#ifdef _MSC_VER - strcat(dir->path, "\\*"); - dir->_h = FindFirstFile(dir->path, &dir->_f); - dir->path[strlen(dir->path) - 2] = '\0'; - if (dir->_h == INVALID_HANDLE_VALUE) -#else - dir->_d = opendir(path); - if (dir->_d == NULL) -#endif - { - errno = ENOENT; - goto bail; - } - - /* read first file */ - dir->has_next = 1; -#ifndef _MSC_VER - dir->_e = readdir(dir->_d); - if (dir->_e == NULL) - { - dir->has_next = 0; - } -#endif - - return 0; - -bail: - tinydir_close(dir); - return -1; -} - -_TINYDIR_FUNC -int tinydir_open_sorted(tinydir_dir* dir, const char* path) -{ - if (tinydir_open(dir, path) == -1) - { - return -1; - } - - dir->n_files = 0; - while (dir->has_next) - { - tinydir_file* p_file; - dir->n_files++; - dir->_files = (tinydir_file*)realloc(dir->_files, sizeof(tinydir_file) * - dir->n_files); - if (dir->_files == NULL) - { - errno = ENOMEM; - goto bail; - } - - p_file = &dir->_files[dir->n_files - 1]; - if (tinydir_readfile(dir, p_file) == -1) - { - goto bail; - } - - if (tinydir_next(dir) == -1) - { - goto bail; - } - } - - qsort(dir->_files, dir->n_files, sizeof(tinydir_file), _tinydir_file_cmp); - - return 0; - -bail: - tinydir_close(dir); - return -1; -} - -_TINYDIR_FUNC -void tinydir_close(tinydir_dir* dir) -{ - if (dir == NULL) - { - return; - } - - memset(dir->path, 0, sizeof(dir->path)); - dir->has_next = 0; - dir->n_files = -1; - if (dir->_files != NULL) - { - free(dir->_files); - } - dir->_files = NULL; -#ifdef _MSC_VER - if (dir->_h != INVALID_HANDLE_VALUE) - { - FindClose(dir->_h); - } - dir->_h = INVALID_HANDLE_VALUE; -#else - if (dir->_d) - { - closedir(dir->_d); - } - dir->_d = NULL; - dir->_e = NULL; -#endif -} - -_TINYDIR_FUNC -int tinydir_next(tinydir_dir* dir) -{ - if (dir == NULL) - { - errno = EINVAL; - return -1; - } - if (!dir->has_next) - { - errno = ENOENT; - return -1; - } - -#ifdef _MSC_VER - if (FindNextFile(dir->_h, &dir->_f) == 0) -#else - dir->_e = readdir(dir->_d); - if (dir->_e == NULL) -#endif - { - dir->has_next = 0; -#ifdef _MSC_VER - if (GetLastError() != ERROR_SUCCESS && - GetLastError() != ERROR_NO_MORE_FILES) - { - tinydir_close(dir); - errno = EIO; - return -1; - } -#endif - } - - return 0; -} - -_TINYDIR_FUNC -int tinydir_readfile(const tinydir_dir* dir, tinydir_file* file) -{ - if (dir == NULL || file == NULL) - { - errno = EINVAL; - return -1; - } -#ifdef _MSC_VER - if (dir->_h == INVALID_HANDLE_VALUE) -#else - if (dir->_e == NULL) -#endif - { - errno = ENOENT; - return -1; - } - if (strlen(dir->path) + - strlen( -#ifdef _MSC_VER - dir->_f.cFileName -#else - dir->_e->d_name -#endif - ) + - 1 + _TINYDIR_PATH_EXTRA >= - _TINYDIR_PATH_MAX) - { - /* the path for the file will be too long */ - errno = ENAMETOOLONG; - return -1; - } - if (strlen( -#ifdef _MSC_VER - dir->_f.cFileName -#else - dir->_e->d_name -#endif - ) >= _TINYDIR_FILENAME_MAX) - { - errno = ENAMETOOLONG; - return -1; - } - - strcpy(file->path, dir->path); - strcat(file->path, "/"); - strcpy(file->name, -#ifdef _MSC_VER - dir->_f.cFileName -#else - dir->_e->d_name -#endif - ); - strcat(file->path, file->name); -#ifndef _MSC_VER - if (stat(file->path, &file->_s) == -1) - { - return -1; - } -#endif - file->is_dir = -#ifdef _MSC_VER - !!(dir->_f.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY); -#else - S_ISDIR(file->_s.st_mode); -#endif - file->is_reg = -#ifdef _MSC_VER - !!(dir->_f.dwFileAttributes & FILE_ATTRIBUTE_NORMAL) || - (!(dir->_f.dwFileAttributes & FILE_ATTRIBUTE_DEVICE) && - !(dir->_f.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) && - !(dir->_f.dwFileAttributes & FILE_ATTRIBUTE_ENCRYPTED) && -# ifdef FILE_ATTRIBUTE_INTEGRITY_STREAM - !(dir->_f.dwFileAttributes & FILE_ATTRIBUTE_INTEGRITY_STREAM) && -# endif -# ifdef FILE_ATTRIBUTE_NO_SCRUB_DATA - !(dir->_f.dwFileAttributes & FILE_ATTRIBUTE_NO_SCRUB_DATA) && -# endif - !(dir->_f.dwFileAttributes & FILE_ATTRIBUTE_OFFLINE) && - !(dir->_f.dwFileAttributes & FILE_ATTRIBUTE_TEMPORARY)); -#else - S_ISREG(file->_s.st_mode); -#endif - - return 0; -} - -_TINYDIR_FUNC -int tinydir_readfile_n(const tinydir_dir* dir, tinydir_file* file, int i) -{ - if (dir == NULL || file == NULL || i < 0) - { - errno = EINVAL; - return -1; - } - if (i >= dir->n_files) - { - errno = ENOENT; - return -1; - } - - memcpy(file, &dir->_files[i], sizeof(tinydir_file)); - - return 0; -} - -_TINYDIR_FUNC -int tinydir_open_subdir_n(tinydir_dir* dir, int i) -{ - char path[_TINYDIR_PATH_MAX]; - if (dir == NULL || i < 0) - { - errno = EINVAL; - return -1; - } - if (i >= dir->n_files || !dir->_files[i].is_dir) - { - errno = ENOENT; - return -1; - } - - strcpy(path, dir->_files[i].path); - tinydir_close(dir); - if (tinydir_open_sorted(dir, path) == -1) - { - return -1; - } - - return 0; -} - -_TINYDIR_FUNC -int _tinydir_file_cmp(const void* a, const void* b) -{ - const tinydir_file* fa = (const tinydir_file*)a; - const tinydir_file* fb = (const tinydir_file*)b; - if (fa->is_dir != fb->is_dir) - { - return -(fa->is_dir - fb->is_dir); - } - return strncasecmp(fa->name, fb->name, _TINYDIR_FILENAME_MAX); -} - -#endif diff --git a/examples/sampler/mac/MethclaSampler/AppDelegate.mm b/examples/sampler/mac/MethclaSampler/AppDelegate.mm index 0e2f1b84..9236e0c0 100644 --- a/examples/sampler/mac/MethclaSampler/AppDelegate.mm +++ b/examples/sampler/mac/MethclaSampler/AppDelegate.mm @@ -7,51 +7,55 @@ // #import "AppDelegate.h" + #import "Engine.hpp" #include #include + #include using namespace Methcla::Examples::Sampler; -static NSArray * openFiles() +static NSArray* openFiles() { - NSOpenPanel * panel = [NSOpenPanel openPanel]; + NSOpenPanel* panel = [NSOpenPanel openPanel]; [panel setAllowsMultipleSelection:YES]; [panel setCanChooseDirectories:NO]; [panel setCanChooseFiles:YES]; - [panel setAllowedFileTypes: [NSArray arrayWithObjects:@"aif",@"aiff",@"mp3",@"wav",nil]]; + [panel setAllowedFileTypes:[NSArray arrayWithObjects:@"aif", @"aiff", + @"mp3", @"wav", nil]]; [panel setFloatingPanel:YES]; NSInteger result = [panel runModal]; return result == NSOKButton ? [panel URLs] : nil; } static const std::vector keys = { - 122,97,113,120,115,119,99,100,101,118,102,114,98,103,116,110,104,121,109,106,117,44,107,105,46,108,111,47,59,112 -}; + 122, 97, 113, 120, 115, 119, 99, 100, 101, 118, 102, 114, 98, 103, 116, + 110, 104, 121, 109, 106, 117, 44, 107, 105, 46, 108, 111, 47, 59, 112}; -static const std::vector rates = { 0.25, 0.5, 0.75, 0.9, 1.0, 1.1, 1.25, 1.5, 2 }; +static const std::vector rates = {0.25, 0.5, 0.75, 0.9, 1.0, + 1.1, 1.25, 1.5, 2}; static long keyToIndex(unichar key) { -// switch (key) { -// case 122: return 0; -// case 120: return 1; -// case 99: return 2; -// case 118: return 3; -// case 98: return 4; -// case 97: return 5; -// case 115: return 6; -// case 100: return 7; -// case 102: return 8; -// case 103: return 9; -// case 113: return 10; -// case 119: return 11; -// case 101: return 12; -// case 114: return 13; -// case 116: return 14; -// } + // switch (key) { + // case 122: return 0; + // case 120: return 1; + // case 99: return 2; + // case 118: return 3; + // case 98: return 4; + // case 97: return 5; + // case 115: return 6; + // case 100: return 7; + // case 102: return 8; + // case 103: return 9; + // case 113: return 10; + // case 119: return 11; + // case 101: return 12; + // case 114: return 13; + // case 116: return 14; + // } auto it = std::find(keys.begin(), keys.end(), key); return it == keys.end() ? -1 : it - keys.begin(); } @@ -74,38 +78,45 @@ - (BOOL)acceptsFirstResponder { return YES; } -- (void)keyDown:(NSEvent *)theEvent +- (void)keyDown:(NSEvent*)theEvent { - if (![theEvent isARepeat]) { + if (![theEvent isARepeat]) + { NSString* chars = [theEvent charactersIgnoringModifiers]; - if ([chars length] == 1) { + if ([chars length] == 1) + { unichar key = [chars characterAtIndex:0]; if (key >= 49 && key <= 57) { - rate = rates[key-49]; + rate = rates[key - 49]; std::cout << "Playback rate set to " << rate << std::endl; } else { long index = keyToIndex(key); -// NSLog(@"keyDown: key=%u index%d", key, index); -// std::cout << key << ","; - if (index >= 0) { - engine->startVoice(static_cast(index), index, 0.2, rate); + // NSLog(@"keyDown: key=%u index%d", key, index); + // std::cout << key << ","; + if (index >= 0) + { + engine->startVoice(static_cast(index), index, 0.2, + rate); } } } } } -- (void)keyUp:(NSEvent *)theEvent +- (void)keyUp:(NSEvent*)theEvent { - if (![theEvent isARepeat]) { + if (![theEvent isARepeat]) + { NSString* chars = [theEvent charactersIgnoringModifiers]; - if ([chars length] == 1) { + if ([chars length] == 1) + { unichar key = [chars characterAtIndex:0]; -// NSLog(@"keyUp: %u", key); + // NSLog(@"keyUp: %u", key); int index = keyToIndex(key); - if (index >= 0) { + if (index >= 0) + { engine->stopVoice(static_cast(index)); } } @@ -115,7 +126,8 @@ - (void)keyUp:(NSEvent *)theEvent inline NSString* resourcePath(NSString* component) { - return [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:component]; + return [[[NSBundle mainBundle] resourcePath] + stringByAppendingPathComponent:component]; } @interface AppDelegate () @@ -125,7 +137,7 @@ @interface AppDelegate () @end @implementation AppDelegate -- (void)applicationDidFinishLaunching:(NSNotification *)aNotification +- (void)applicationDidFinishLaunching:(NSNotification*)aNotification { Engine::Options options; options.engineOptions.audioDriver.bufferSize = 128; @@ -140,16 +152,20 @@ - (void)applicationDidFinishLaunching:(NSNotification *)aNotification } // Set up the sound engine - try { + try + { // Initialize and configure the audio engine -// options.soundDir = [resourcePath(@"sounds") UTF8String]; + // options.soundDir = [resourcePath(@"sounds") UTF8String]; engine = new Engine(options); - } catch (std::exception& e) { + } + catch (std::exception& e) + { std::cerr << e.what() << std::endl; } // Set up a KeyboardView as first responder - KeyboardView* view = [[KeyboardView alloc] initWithFrame:NSMakeRect(100, 100, 100, 100)]; + KeyboardView* view = + [[KeyboardView alloc] initWithFrame:NSMakeRect(100, 100, 100, 100)]; [view setEngine:engine]; [view setWantsLayer:YES]; view.layer.backgroundColor = [[NSColor yellowColor] CGColor]; diff --git a/examples/sampler/mac/MethclaSampler/en.lproj/InfoPlist.strings b/examples/sampler/mac/MethclaSampler/en.lproj/InfoPlist.strings index 477b28ff..b92732c7 100644 --- a/examples/sampler/mac/MethclaSampler/en.lproj/InfoPlist.strings +++ b/examples/sampler/mac/MethclaSampler/en.lproj/InfoPlist.strings @@ -1,2 +1 @@ /* Localized versions of Info.plist keys */ - diff --git a/examples/sampler/mac/MethclaSamplerOSX.xcodeproj/project.pbxproj b/examples/sampler/mac/MethclaSamplerOSX.xcodeproj/project.pbxproj index 2f135c1b..af10d4f7 100644 --- a/examples/sampler/mac/MethclaSamplerOSX.xcodeproj/project.pbxproj +++ b/examples/sampler/mac/MethclaSamplerOSX.xcodeproj/project.pbxproj @@ -366,7 +366,7 @@ GCC_WARN_64_TO_32_BIT_CONVERSION = YES; HEADER_SEARCH_PATHS = ( ../../../include, - ../libs/tinydir, + ../../../external_libraries/tinydir, ); INFOPLIST_FILE = "MethclaSampler/MethclaSampler-Info.plist"; LIBRARY_SEARCH_PATHS = ( @@ -397,7 +397,7 @@ GCC_WARN_64_TO_32_BIT_CONVERSION = YES; HEADER_SEARCH_PATHS = ( ../../../include, - ../libs/tinydir, + ../../../external_libraries/tinydir, ); INFOPLIST_FILE = "MethclaSampler/MethclaSampler-Info.plist"; LIBRARY_SEARCH_PATHS = ( diff --git a/examples/sampler/src/Engine.cpp b/examples/sampler/src/Engine.cpp index 10309bc2..60b91890 100644 --- a/examples/sampler/src/Engine.cpp +++ b/examples/sampler/src/Engine.cpp @@ -143,7 +143,10 @@ Engine::~Engine() delete m_engine; } -size_t Engine::numSounds() const { return m_sounds.size(); } +size_t Engine::numSounds() const +{ + return m_sounds.size(); +} void Engine::useDisk(bool flag) { diff --git a/examples/sampler/src/Engine.hpp b/examples/sampler/src/Engine.hpp index 082e4a98..40e061c7 100644 --- a/examples/sampler/src/Engine.hpp +++ b/examples/sampler/src/Engine.hpp @@ -28,9 +28,15 @@ namespace Methcla { namespace Examples { namespace Sampler { public: Sound(const Methcla::Engine& engine, const std::string& path); - const std::string& path() const { return m_path; } + const std::string& path() const + { + return m_path; + } - float duration() const { return m_duration; } + float duration() const + { + return m_duration; + } private: std::string m_path; @@ -48,7 +54,10 @@ namespace Methcla { namespace Examples { namespace Sampler { std::pow(outMax / outMin, (x - inMin) / (inMax - inMin)); } - template T dbamp(T db) { return std::pow(T(10), db / T(20)); } + template T dbamp(T db) + { + return std::pow(T(10), db / T(20)); + } class Engine { @@ -82,7 +91,10 @@ namespace Methcla { namespace Examples { namespace Sampler { void stopVoice(VoiceId voice); private: - Methcla::Engine& engine() { return *m_engine; } + Methcla::Engine& engine() + { + return *m_engine; + } private: std::vector m_sounds; diff --git a/examples/thADDeus/android/AndroidManifest.xml b/examples/thADDeus/android/AndroidManifest.xml index 7dc8d23e..98473f31 100644 --- a/examples/thADDeus/android/AndroidManifest.xml +++ b/examples/thADDeus/android/AndroidManifest.xml @@ -23,4 +23,4 @@ - + diff --git a/examples/thADDeus/ios/Methcla/AppDelegate.mm b/examples/thADDeus/ios/Methcla/AppDelegate.mm index e7f63e72..034ab69e 100644 --- a/examples/thADDeus/ios/Methcla/AppDelegate.mm +++ b/examples/thADDeus/ios/Methcla/AppDelegate.mm @@ -1,11 +1,11 @@ // Copyright 2012-2013 Samplecount S.L. -// +// // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at -// +// // http://www.apache.org/licenses/LICENSE-2.0 -// +// // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -18,45 +18,67 @@ @implementation AppDelegate -- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions +- (BOOL)application:(UIApplication*)application + didFinishLaunchingWithOptions:(NSDictionary*)launchOptions { - self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]]; + self.window = + [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]]; // Override point for customization after application launch. - if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) { - self.viewController = [[ViewController alloc] initWithNibName:@"ViewController_iPhone" bundle:nil]; - } else { - self.viewController = [[ViewController alloc] initWithNibName:@"ViewController_iPad" bundle:nil]; + if ([[UIDevice currentDevice] userInterfaceIdiom] == + UIUserInterfaceIdiomPhone) + { + self.viewController = + [[ViewController alloc] initWithNibName:@"ViewController_iPhone" + bundle:nil]; + } + else + { + self.viewController = + [[ViewController alloc] initWithNibName:@"ViewController_iPad" + bundle:nil]; } self.window.rootViewController = self.viewController; [self.window makeKeyAndVisible]; return YES; } -- (void)applicationWillResignActive:(UIApplication *)application +- (void)applicationWillResignActive:(UIApplication*)application { - // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. - // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. + // Sent when the application is about to move from active to inactive state. + // This can occur for certain types of temporary interruptions (such as an + // incoming phone call or SMS message) or when the user quits the + // application and it begins the transition to the background state. Use + // this method to pause ongoing tasks, disable timers, and throttle down + // OpenGL ES frame rates. Games should use this method to pause the game. } -- (void)applicationDidEnterBackground:(UIApplication *)application +- (void)applicationDidEnterBackground:(UIApplication*)application { - // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. - // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. + // Use this method to release shared resources, save user data, invalidate + // timers, and store enough application state information to restore your + // application to its current state in case it is terminated later. If your + // application supports background execution, this method is called instead + // of applicationWillTerminate: when the user quits. } -- (void)applicationWillEnterForeground:(UIApplication *)application +- (void)applicationWillEnterForeground:(UIApplication*)application { - // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. + // Called as part of the transition from the background to the inactive + // state; here you can undo many of the changes made on entering the + // background. } -- (void)applicationDidBecomeActive:(UIApplication *)application +- (void)applicationDidBecomeActive:(UIApplication*)application { - // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. + // Restart any tasks that were paused (or not yet started) while the + // application was inactive. If the application was previously in the + // background, optionally refresh the user interface. } -- (void)applicationWillTerminate:(UIApplication *)application +- (void)applicationWillTerminate:(UIApplication*)application { - // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. + // Called when the application is about to terminate. Save data if + // appropriate. See also applicationDidEnterBackground:. } @end diff --git a/examples/thADDeus/ios/Methcla/Shaders/Shader.fsh b/examples/thADDeus/ios/Methcla/Shaders/Shader.fsh index 55c39d5f..aec394c6 100644 --- a/examples/thADDeus/ios/Methcla/Shaders/Shader.fsh +++ b/examples/thADDeus/ios/Methcla/Shaders/Shader.fsh @@ -1,11 +1,11 @@ // Copyright 2012-2013 Samplecount S.L. -// +// // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at -// +// // http://www.apache.org/licenses/LICENSE-2.0 -// +// // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. diff --git a/examples/thADDeus/ios/Methcla/Shaders/Shader.vsh b/examples/thADDeus/ios/Methcla/Shaders/Shader.vsh index fc3616bd..30a581fa 100644 --- a/examples/thADDeus/ios/Methcla/Shaders/Shader.vsh +++ b/examples/thADDeus/ios/Methcla/Shaders/Shader.vsh @@ -1,11 +1,11 @@ // Copyright 2012-2013 Samplecount S.L. -// +// // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at -// +// // http://www.apache.org/licenses/LICENSE-2.0 -// +// // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -25,10 +25,10 @@ void main() vec3 eyeNormal = normalize(normalMatrix * normal); vec3 lightPosition = vec3(0.0, 0.0, 1.0); vec4 diffuseColor = vec4(0.4, 0.4, 1.0, 1.0); - + float nDotVP = max(0.0, dot(eyeNormal, normalize(lightPosition))); - + colorVarying = diffuseColor * nDotVP; - + gl_Position = modelViewProjectionMatrix * position; } diff --git a/examples/thADDeus/ios/Methcla/ViewController.mm b/examples/thADDeus/ios/Methcla/ViewController.mm index cc176900..1675bc7c 100644 --- a/examples/thADDeus/ios/Methcla/ViewController.mm +++ b/examples/thADDeus/ios/Methcla/ViewController.mm @@ -1,11 +1,11 @@ // Copyright 2012-2013 Samplecount S.L. -// +// // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at -// +// // http://www.apache.org/licenses/LICENSE-2.0 -// +// // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -13,10 +13,12 @@ // limitations under the License. #import "ViewController.h" + #include "Engine.h" + #include -#define BUFFER_OFFSET(i) ((char *)NULL + (i)) +#define BUFFER_OFFSET(i) ((char*)NULL + (i)) // Uniform index. enum @@ -35,92 +37,80 @@ NUM_ATTRIBUTES }; -GLfloat gCubeVertexData[216] = -{ +GLfloat gCubeVertexData[216] = { // Data layout for each line below is: // positionX, positionY, positionZ, normalX, normalY, normalZ, - 0.5f, -0.5f, -0.5f, 1.0f, 0.0f, 0.0f, - 0.5f, 0.5f, -0.5f, 1.0f, 0.0f, 0.0f, - 0.5f, -0.5f, 0.5f, 1.0f, 0.0f, 0.0f, - 0.5f, -0.5f, 0.5f, 1.0f, 0.0f, 0.0f, - 0.5f, 0.5f, -0.5f, 1.0f, 0.0f, 0.0f, - 0.5f, 0.5f, 0.5f, 1.0f, 0.0f, 0.0f, - - 0.5f, 0.5f, -0.5f, 0.0f, 1.0f, 0.0f, - -0.5f, 0.5f, -0.5f, 0.0f, 1.0f, 0.0f, - 0.5f, 0.5f, 0.5f, 0.0f, 1.0f, 0.0f, - 0.5f, 0.5f, 0.5f, 0.0f, 1.0f, 0.0f, - -0.5f, 0.5f, -0.5f, 0.0f, 1.0f, 0.0f, - -0.5f, 0.5f, 0.5f, 0.0f, 1.0f, 0.0f, - - -0.5f, 0.5f, -0.5f, -1.0f, 0.0f, 0.0f, - -0.5f, -0.5f, -0.5f, -1.0f, 0.0f, 0.0f, - -0.5f, 0.5f, 0.5f, -1.0f, 0.0f, 0.0f, - -0.5f, 0.5f, 0.5f, -1.0f, 0.0f, 0.0f, - -0.5f, -0.5f, -0.5f, -1.0f, 0.0f, 0.0f, - -0.5f, -0.5f, 0.5f, -1.0f, 0.0f, 0.0f, - - -0.5f, -0.5f, -0.5f, 0.0f, -1.0f, 0.0f, - 0.5f, -0.5f, -0.5f, 0.0f, -1.0f, 0.0f, - -0.5f, -0.5f, 0.5f, 0.0f, -1.0f, 0.0f, - -0.5f, -0.5f, 0.5f, 0.0f, -1.0f, 0.0f, - 0.5f, -0.5f, -0.5f, 0.0f, -1.0f, 0.0f, - 0.5f, -0.5f, 0.5f, 0.0f, -1.0f, 0.0f, - - 0.5f, 0.5f, 0.5f, 0.0f, 0.0f, 1.0f, - -0.5f, 0.5f, 0.5f, 0.0f, 0.0f, 1.0f, - 0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 1.0f, - 0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 1.0f, - -0.5f, 0.5f, 0.5f, 0.0f, 0.0f, 1.0f, - -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 1.0f, - - 0.5f, -0.5f, -0.5f, 0.0f, 0.0f, -1.0f, - -0.5f, -0.5f, -0.5f, 0.0f, 0.0f, -1.0f, - 0.5f, 0.5f, -0.5f, 0.0f, 0.0f, -1.0f, - 0.5f, 0.5f, -0.5f, 0.0f, 0.0f, -1.0f, - -0.5f, -0.5f, -0.5f, 0.0f, 0.0f, -1.0f, - -0.5f, 0.5f, -0.5f, 0.0f, 0.0f, -1.0f -}; - -@interface ViewController () { + 0.5f, -0.5f, -0.5f, 1.0f, 0.0f, 0.0f, 0.5f, 0.5f, -0.5f, + 1.0f, 0.0f, 0.0f, 0.5f, -0.5f, 0.5f, 1.0f, 0.0f, 0.0f, + 0.5f, -0.5f, 0.5f, 1.0f, 0.0f, 0.0f, 0.5f, 0.5f, -0.5f, + 1.0f, 0.0f, 0.0f, 0.5f, 0.5f, 0.5f, 1.0f, 0.0f, 0.0f, + + 0.5f, 0.5f, -0.5f, 0.0f, 1.0f, 0.0f, -0.5f, 0.5f, -0.5f, + 0.0f, 1.0f, 0.0f, 0.5f, 0.5f, 0.5f, 0.0f, 1.0f, 0.0f, + 0.5f, 0.5f, 0.5f, 0.0f, 1.0f, 0.0f, -0.5f, 0.5f, -0.5f, + 0.0f, 1.0f, 0.0f, -0.5f, 0.5f, 0.5f, 0.0f, 1.0f, 0.0f, + + -0.5f, 0.5f, -0.5f, -1.0f, 0.0f, 0.0f, -0.5f, -0.5f, -0.5f, + -1.0f, 0.0f, 0.0f, -0.5f, 0.5f, 0.5f, -1.0f, 0.0f, 0.0f, + -0.5f, 0.5f, 0.5f, -1.0f, 0.0f, 0.0f, -0.5f, -0.5f, -0.5f, + -1.0f, 0.0f, 0.0f, -0.5f, -0.5f, 0.5f, -1.0f, 0.0f, 0.0f, + + -0.5f, -0.5f, -0.5f, 0.0f, -1.0f, 0.0f, 0.5f, -0.5f, -0.5f, + 0.0f, -1.0f, 0.0f, -0.5f, -0.5f, 0.5f, 0.0f, -1.0f, 0.0f, + -0.5f, -0.5f, 0.5f, 0.0f, -1.0f, 0.0f, 0.5f, -0.5f, -0.5f, + 0.0f, -1.0f, 0.0f, 0.5f, -0.5f, 0.5f, 0.0f, -1.0f, 0.0f, + + 0.5f, 0.5f, 0.5f, 0.0f, 0.0f, 1.0f, -0.5f, 0.5f, 0.5f, + 0.0f, 0.0f, 1.0f, 0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 1.0f, + 0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 1.0f, -0.5f, 0.5f, 0.5f, + 0.0f, 0.0f, 1.0f, -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 1.0f, + + 0.5f, -0.5f, -0.5f, 0.0f, 0.0f, -1.0f, -0.5f, -0.5f, -0.5f, + 0.0f, 0.0f, -1.0f, 0.5f, 0.5f, -0.5f, 0.0f, 0.0f, -1.0f, + 0.5f, 0.5f, -0.5f, 0.0f, 0.0f, -1.0f, -0.5f, -0.5f, -0.5f, + 0.0f, 0.0f, -1.0f, -0.5f, 0.5f, -0.5f, 0.0f, 0.0f, -1.0f}; + +@interface ViewController () +{ GLuint _program; - + GLKMatrix4 _modelViewProjectionMatrix; GLKMatrix3 _normalMatrix; - float _rotation; - + float _rotation; + GLuint _vertexArray; GLuint _vertexBuffer; } -@property (strong, nonatomic) EAGLContext *context; -@property (strong, nonatomic) GLKBaseEffect *effect; +@property(strong, nonatomic) EAGLContext* context; +@property(strong, nonatomic) GLKBaseEffect* effect; - (void)setupGL; - (void)tearDownGL; - (BOOL)loadShaders; -- (BOOL)compileShader:(GLuint *)shader type:(GLenum)type file:(NSString *)file; +- (BOOL)compileShader:(GLuint*)shader type:(GLenum)type file:(NSString*)file; - (BOOL)linkProgram:(GLuint)prog; - (BOOL)validateProgram:(GLuint)prog; @end @implementation ViewController { - Methcla::Engine* engine; + Methcla::Engine* engine; NSMutableDictionary* synths; } - (void)viewDidLoad { [super viewDidLoad]; - + self.context = [[EAGLContext alloc] initWithAPI:kEAGLRenderingAPIOpenGLES2]; - if (!self.context) { + if (!self.context) + { NSLog(@"Failed to create ES context"); } - - GLKView *view = (GLKView *)self.view; + + GLKView* view = (GLKView*)self.view; view.context = self.context; view.drawableDepthFormat = GLKViewDrawableDepthFormat24; @@ -130,33 +120,40 @@ - (void)viewDidLoad [self.view setMultipleTouchEnabled:YES]; // Set up sound engine - try { + try + { // Initialize and configure the audio session engine = makeEngine(); -// m_engine->start(); -// } catch (boost::exception& e) { -// if (OSStatus const* err = boost::get_error_info(e)) { -// std::cerr << -// [[[NSError errorWithDomain: NSOSStatusErrorDomain -// code: *err -// userInfo: nil] localizedDescription] UTF8String] << "\n"; -// } else { -// std::cerr << diagnostic_information(e) << "\n"; -// } - } catch (std::exception& e) { + // m_engine->start(); + // } catch (boost::exception& e) { + // if (OSStatus const* err = + // boost::get_error_info(e)) { + // std::cerr << + // [[[NSError errorWithDomain: NSOSStatusErrorDomain + // code: *err + // userInfo: nil] localizedDescription] + // UTF8String] << "\n"; + // } else { + // std::cerr << diagnostic_information(e) << "\n"; + // } + } + catch (std::exception& e) + { std::cerr << e.what() << std::endl; } - if (!synths) { + if (!synths) + { synths = [[NSMutableDictionary alloc] init]; } } - (void)dealloc -{ +{ [self tearDownGL]; - - if ([EAGLContext currentContext] == self.context) { + + if ([EAGLContext currentContext] == self.context) + { [EAGLContext setCurrentContext:nil]; } } @@ -165,12 +162,14 @@ - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; - if ([self isViewLoaded] && ([[self view] window] == nil)) { + if ([self isViewLoaded] && ([[self view] window] == nil)) + { self.view = nil; - + [self tearDownGL]; - - if ([EAGLContext currentContext] == self.context) { + + if ([EAGLContext currentContext] == self.context) + { [EAGLContext setCurrentContext:nil]; } self.context = nil; @@ -182,40 +181,44 @@ - (void)didReceiveMemoryWarning - (void)setupGL { [EAGLContext setCurrentContext:self.context]; - + [self loadShaders]; - + self.effect = [[GLKBaseEffect alloc] init]; self.effect.light0.enabled = GL_TRUE; self.effect.light0.diffuseColor = GLKVector4Make(1.0f, 0.4f, 0.4f, 1.0f); - + glEnable(GL_DEPTH_TEST); - + glGenVertexArraysOES(1, &_vertexArray); glBindVertexArrayOES(_vertexArray); - + glGenBuffers(1, &_vertexBuffer); glBindBuffer(GL_ARRAY_BUFFER, _vertexBuffer); - glBufferData(GL_ARRAY_BUFFER, sizeof(gCubeVertexData), gCubeVertexData, GL_STATIC_DRAW); - + glBufferData(GL_ARRAY_BUFFER, sizeof(gCubeVertexData), gCubeVertexData, + GL_STATIC_DRAW); + glEnableVertexAttribArray(GLKVertexAttribPosition); - glVertexAttribPointer(GLKVertexAttribPosition, 3, GL_FLOAT, GL_FALSE, 24, BUFFER_OFFSET(0)); + glVertexAttribPointer(GLKVertexAttribPosition, 3, GL_FLOAT, GL_FALSE, 24, + BUFFER_OFFSET(0)); glEnableVertexAttribArray(GLKVertexAttribNormal); - glVertexAttribPointer(GLKVertexAttribNormal, 3, GL_FLOAT, GL_FALSE, 24, BUFFER_OFFSET(12)); - + glVertexAttribPointer(GLKVertexAttribNormal, 3, GL_FLOAT, GL_FALSE, 24, + BUFFER_OFFSET(12)); + glBindVertexArrayOES(0); } - (void)tearDownGL { [EAGLContext setCurrentContext:self.context]; - + glDeleteBuffers(1, &_vertexBuffer); glDeleteVertexArraysOES(1, &_vertexArray); - + self.effect = nil; - - if (_program) { + + if (_program) + { glDeleteProgram(_program); _program = 0; } @@ -228,50 +231,51 @@ - (void)update #if 0 float aspect = fabsf(self.view.bounds.size.width / self.view.bounds.size.height); GLKMatrix4 projectionMatrix = GLKMatrix4MakePerspective(GLKMathDegreesToRadians(65.0f), aspect, 0.1f, 100.0f); - + self.effect.transform.projectionMatrix = projectionMatrix; - + GLKMatrix4 baseModelViewMatrix = GLKMatrix4MakeTranslation(0.0f, 0.0f, -4.0f); baseModelViewMatrix = GLKMatrix4Rotate(baseModelViewMatrix, _rotation, 0.0f, 1.0f, 0.0f); - + // Compute the model view matrix for the object rendered with GLKit GLKMatrix4 modelViewMatrix = GLKMatrix4MakeTranslation(0.0f, 0.0f, -1.5f); modelViewMatrix = GLKMatrix4Rotate(modelViewMatrix, _rotation, 1.0f, 1.0f, 1.0f); modelViewMatrix = GLKMatrix4Multiply(baseModelViewMatrix, modelViewMatrix); - + self.effect.transform.modelviewMatrix = modelViewMatrix; - + // Compute the model view matrix for the object rendered with ES2 modelViewMatrix = GLKMatrix4MakeTranslation(0.0f, 0.0f, 1.5f); modelViewMatrix = GLKMatrix4Rotate(modelViewMatrix, _rotation, 1.0f, 1.0f, 1.0f); modelViewMatrix = GLKMatrix4Multiply(baseModelViewMatrix, modelViewMatrix); - + _normalMatrix = GLKMatrix3InvertAndTranspose(GLKMatrix4GetMatrix3(modelViewMatrix), NULL); - + _modelViewProjectionMatrix = GLKMatrix4Multiply(projectionMatrix, modelViewMatrix); - + _rotation += self.timeSinceLastUpdate * 0.5f; #endif } -- (void)glkView:(GLKView *)view drawInRect:(CGRect)rect +- (void)glkView:(GLKView*)view drawInRect:(CGRect)rect { glClearColor(0.65f, 0.65f, 0.65f, 1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); - + glBindVertexArrayOES(_vertexArray); - + // Render the object with GLKit [self.effect prepareToDraw]; - + glDrawArrays(GL_TRIANGLES, 0, 36); - + // Render the object again with ES2 glUseProgram(_program); - - glUniformMatrix4fv(uniforms[UNIFORM_MODELVIEWPROJECTION_MATRIX], 1, 0, _modelViewProjectionMatrix.m); + + glUniformMatrix4fv(uniforms[UNIFORM_MODELVIEWPROJECTION_MATRIX], 1, 0, + _modelViewProjectionMatrix.m); glUniformMatrix3fv(uniforms[UNIFORM_NORMAL_MATRIX], 1, 0, _normalMatrix.m); - + glDrawArrays(GL_TRIANGLES, 0, 36); } @@ -279,106 +283,127 @@ - (void)glkView:(GLKView *)view drawInRect:(CGRect)rect - (BOOL)loadShaders { - GLuint vertShader, fragShader; + GLuint vertShader, fragShader; NSString *vertShaderPathname, *fragShaderPathname; - + // Create shader program. _program = glCreateProgram(); - + // Create and compile vertex shader. - vertShaderPathname = [[NSBundle mainBundle] pathForResource:@"Shader" ofType:@"vsh"]; - if (![self compileShader:&vertShader type:GL_VERTEX_SHADER file:vertShaderPathname]) { + vertShaderPathname = [[NSBundle mainBundle] pathForResource:@"Shader" + ofType:@"vsh"]; + if (![self compileShader:&vertShader + type:GL_VERTEX_SHADER + file:vertShaderPathname]) + { NSLog(@"Failed to compile vertex shader"); return NO; } - + // Create and compile fragment shader. - fragShaderPathname = [[NSBundle mainBundle] pathForResource:@"Shader" ofType:@"fsh"]; - if (![self compileShader:&fragShader type:GL_FRAGMENT_SHADER file:fragShaderPathname]) { + fragShaderPathname = [[NSBundle mainBundle] pathForResource:@"Shader" + ofType:@"fsh"]; + if (![self compileShader:&fragShader + type:GL_FRAGMENT_SHADER + file:fragShaderPathname]) + { NSLog(@"Failed to compile fragment shader"); return NO; } - + // Attach vertex shader to program. glAttachShader(_program, vertShader); - + // Attach fragment shader to program. glAttachShader(_program, fragShader); - + // Bind attribute locations. // This needs to be done prior to linking. glBindAttribLocation(_program, GLKVertexAttribPosition, "position"); glBindAttribLocation(_program, GLKVertexAttribNormal, "normal"); - + // Link program. - if (![self linkProgram:_program]) { + if (![self linkProgram:_program]) + { NSLog(@"Failed to link program: %d", _program); - - if (vertShader) { + + if (vertShader) + { glDeleteShader(vertShader); vertShader = 0; } - if (fragShader) { + if (fragShader) + { glDeleteShader(fragShader); fragShader = 0; } - if (_program) { + if (_program) + { glDeleteProgram(_program); _program = 0; } - + return NO; } - + // Get uniform locations. - uniforms[UNIFORM_MODELVIEWPROJECTION_MATRIX] = glGetUniformLocation(_program, "modelViewProjectionMatrix"); - uniforms[UNIFORM_NORMAL_MATRIX] = glGetUniformLocation(_program, "normalMatrix"); - + uniforms[UNIFORM_MODELVIEWPROJECTION_MATRIX] = + glGetUniformLocation(_program, "modelViewProjectionMatrix"); + uniforms[UNIFORM_NORMAL_MATRIX] = + glGetUniformLocation(_program, "normalMatrix"); + // Release vertex and fragment shaders. - if (vertShader) { + if (vertShader) + { glDetachShader(_program, vertShader); glDeleteShader(vertShader); } - if (fragShader) { + if (fragShader) + { glDetachShader(_program, fragShader); glDeleteShader(fragShader); } - + return YES; } -- (BOOL)compileShader:(GLuint *)shader type:(GLenum)type file:(NSString *)file +- (BOOL)compileShader:(GLuint*)shader type:(GLenum)type file:(NSString*)file { - GLint status; - const GLchar *source; - - source = (GLchar *)[[NSString stringWithContentsOfFile:file encoding:NSUTF8StringEncoding error:nil] UTF8String]; - if (!source) { + GLint status; + const GLchar* source; + + source = (GLchar*)[[NSString stringWithContentsOfFile:file + encoding:NSUTF8StringEncoding + error:nil] UTF8String]; + if (!source) + { NSLog(@"Failed to load vertex shader"); return NO; } - + *shader = glCreateShader(type); glShaderSource(*shader, 1, &source, NULL); glCompileShader(*shader); - + #if defined(DEBUG) GLint logLength; glGetShaderiv(*shader, GL_INFO_LOG_LENGTH, &logLength); - if (logLength > 0) { - GLchar *log = (GLchar *)malloc(logLength); + if (logLength > 0) + { + GLchar* log = (GLchar*)malloc(logLength); glGetShaderInfoLog(*shader, logLength, &logLength, log); NSLog(@"Shader compile log:\n%s", log); free(log); } #endif - + glGetShaderiv(*shader, GL_COMPILE_STATUS, &status); - if (status == 0) { + if (status == 0) + { glDeleteShader(*shader); return NO; } - + return YES; } @@ -386,52 +411,56 @@ - (BOOL)linkProgram:(GLuint)prog { GLint status; glLinkProgram(prog); - + #if defined(DEBUG) GLint logLength; glGetProgramiv(prog, GL_INFO_LOG_LENGTH, &logLength); - if (logLength > 0) { - GLchar *log = (GLchar *)malloc(logLength); + if (logLength > 0) + { + GLchar* log = (GLchar*)malloc(logLength); glGetProgramInfoLog(prog, logLength, &logLength, log); NSLog(@"Program link log:\n%s", log); free(log); } #endif - + glGetProgramiv(prog, GL_LINK_STATUS, &status); - if (status == 0) { + if (status == 0) + { return NO; } - + return YES; } - (BOOL)validateProgram:(GLuint)prog { GLint logLength, status; - + glValidateProgram(prog); glGetProgramiv(prog, GL_INFO_LOG_LENGTH, &logLength); - if (logLength > 0) { - GLchar *log = (GLchar *)malloc(logLength); + if (logLength > 0) + { + GLchar* log = (GLchar*)malloc(logLength); glGetProgramInfoLog(prog, logLength, &logLength, log); NSLog(@"Program validate log:\n%s", log); free(log); } - + glGetProgramiv(prog, GL_VALIDATE_STATUS, &status); - if (status == 0) { + if (status == 0) + { return NO; } - + return YES; } - (CGPoint)relativeLocation:(UITouch*)touch inView:(UIView*)view { const CGPoint pt = [touch locationInView:view]; - const CGSize sz = view.bounds.size; - return { .x = pt.x / sz.width, .y = pt.y / sz.height }; + const CGSize sz = view.bounds.size; + return {.x = pt.x / sz.width, .y = pt.y / sz.height}; } struct SynthParams @@ -443,59 +472,67 @@ - (CGPoint)relativeLocation:(UITouch*)touch inView:(UIView*)view - (SynthParams)synthParamsForTouch:(UITouch*)touch { const CGPoint pt = [self relativeLocation:touch inView:self.view]; - return { - .freq = (1.f-pt.y) * 900.f + 100.f, - .amp = pt.x - }; + return {.freq = (1.f - pt.y) * 900.f + 100.f, .amp = pt.x}; } static Methcla_Time kLatency = 0.05; -- (void) touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event +- (void)touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event { -// NSLog(@"%@ %f", event, self.view.bounds.size.height); + // NSLog(@"%@ %f", event, self.view.bounds.size.height); - for (UITouch* touch in touches) { - SynthParams ps = [self synthParamsForTouch:touch]; + for (UITouch* touch in touches) + { + SynthParams ps = [self synthParamsForTouch:touch]; Methcla::SynthId synth; engine->bundle(Methcla::immediately, [&](Methcla::Request& request) { - synth = request.synth(METHCLA_PLUGINS_SINE_URI, engine->root(), { ps.freq, 0.05 }); - request.mapOutput(synth, 0, Methcla::AudioBusId(0), Methcla::kBusMappingExternal); - request.mapOutput(synth, 0, Methcla::AudioBusId(1), Methcla::kBusMappingExternal); - request.bundle(engine->currentTime() + kLatency, [&](Methcla::Request& request) { - request.activate(synth); - }); + synth = request.synth(METHCLA_PLUGINS_SINE_URI, engine->root(), + {ps.freq, 0.05}); + request.mapOutput(synth, 0, Methcla::AudioBusId(0), + Methcla::kBusMappingExternal); + request.mapOutput(synth, 0, Methcla::AudioBusId(1), + Methcla::kBusMappingExternal); + request.bundle( + engine->currentTime() + kLatency, + [&](Methcla::Request& request) { request.activate(synth); }); }); -// std::cout << "Synth " << synth << " started: freq=" << ps.freq << " amp=" << ps.amp << std::endl; + // std::cout << "Synth " << synth << " started: freq=" << ps.freq + // << " amp=" << ps.amp << std::endl; [synths setObject:[NSNumber numberWithLong:(long)synth.id()] - forKey:[NSValue valueWithPointer:(const void*)touch]]; + forKey:[NSValue valueWithPointer:(const void*)touch]]; } } -- (void) touchesMoved:(NSSet*)touches withEvent:(UIEvent*)event +- (void)touchesMoved:(NSSet*)touches withEvent:(UIEvent*)event { -// NSLog(@"%@", event); + // NSLog(@"%@", event); - for (UITouch* touch in touches) { - Methcla::SynthId synth([[synths objectForKey:[NSValue valueWithPointer:(const void*)touch]] longValue]); + for (UITouch* touch in touches) + { + Methcla::SynthId synth( + [[synths objectForKey:[NSValue valueWithPointer:(const void*)touch]] + longValue]); SynthParams ps = [self synthParamsForTouch:touch]; engine->set(synth, 0, ps.freq); -// std::cout << "Synth " << synth << ": freq=" << ps.freq << " amp=" << ps.amp << std::endl; + // std::cout << "Synth " << synth << ": freq=" << ps.freq << " + // amp=" << ps.amp << std::endl; } } -- (void) touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event +- (void)touchesEnded:(NSSet*)touches withEvent:(UIEvent*)event { - for (UITouch* touch in touches) { - Methcla::SynthId synth([[synths objectForKey:[NSValue valueWithPointer:(const void*)touch]] longValue]); - engine->bundle(engine->currentTime() + kLatency, [&](Methcla::Request& request){ - request.free(synth); - }); -// std::cout << "Synth " << synth << " stopped" << std::endl; + for (UITouch* touch in touches) + { + Methcla::SynthId synth( + [[synths objectForKey:[NSValue valueWithPointer:(const void*)touch]] + longValue]); + engine->bundle(engine->currentTime() + kLatency, + [&](Methcla::Request& request) { request.free(synth); }); + // std::cout << "Synth " << synth << " stopped" << std::endl; } } -- (void) touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event +- (void)touchesCancelled:(NSSet*)touches withEvent:(UIEvent*)event { [self touchesEnded:touches withEvent:event]; } diff --git a/examples/thADDeus/ios/Methcla/en.lproj/InfoPlist.strings b/examples/thADDeus/ios/Methcla/en.lproj/InfoPlist.strings index 477b28ff..b92732c7 100644 --- a/examples/thADDeus/ios/Methcla/en.lproj/InfoPlist.strings +++ b/examples/thADDeus/ios/Methcla/en.lproj/InfoPlist.strings @@ -1,2 +1 @@ /* Localized versions of Info.plist keys */ - diff --git a/examples/thADDeus/ios/Methcla/main.mm b/examples/thADDeus/ios/Methcla/main.mm index 4e22b445..c17f32f0 100644 --- a/examples/thADDeus/ios/Methcla/main.mm +++ b/examples/thADDeus/ios/Methcla/main.mm @@ -1,24 +1,26 @@ // Copyright 2012-2013 Samplecount S.L. -// +// // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at -// +// // http://www.apache.org/licenses/LICENSE-2.0 -// +// // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. -#import - #import "AppDelegate.h" -int main(int argc, char *argv[]) +#import + +int main(int argc, char* argv[]) { - @autoreleasepool { - return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class])); + @autoreleasepool + { + return UIApplicationMain(argc, argv, nil, + NSStringFromClass([AppDelegate class])); } } diff --git a/examples/thADDeus/src/synth.cpp b/examples/thADDeus/src/synth.cpp index 1ccb8726..24425d3e 100644 --- a/examples/thADDeus/src/synth.cpp +++ b/examples/thADDeus/src/synth.cpp @@ -33,9 +33,15 @@ thaddeus::Engine::~Engine() delete m_engine; } -void thaddeus::Engine::start() { m_engine->start(); } +void thaddeus::Engine::start() +{ + m_engine->start(); +} -void thaddeus::Engine::stop() { m_engine->stop(); } +void thaddeus::Engine::stop() +{ + m_engine->stop(); +} void thaddeus::Engine::startVoice(VoiceId voice, float freq, float amp) { diff --git a/faust/architecture/synth.cpp b/faust/architecture/synth.cpp index b297df36..67880313 100644 --- a/faust/architecture/synth.cpp +++ b/faust/architecture/synth.cpp @@ -87,11 +87,16 @@ class ControlSpecAllocator : public UI // Layout widgets - virtual void openFrameBox(const char* label) {} - virtual void openTabBox(const char* label) {} - virtual void openHorizontalBox(const char* label) {} - virtual void openVerticalBox(const char* label) {} - virtual void closeBox() {} + virtual void openFrameBox(const char* label) + {} + virtual void openTabBox(const char* label) + {} + virtual void openHorizontalBox(const char* label) + {} + virtual void openVerticalBox(const char* label) + {} + virtual void closeBox() + {} // Active widgets @@ -240,14 +245,22 @@ class ControlAllocator : public UI {} // Layout widgets - virtual void openFrameBox(const char* label) {} - virtual void openTabBox(const char* label) {} - virtual void openHorizontalBox(const char* label) {} - virtual void openVerticalBox(const char* label) {} - virtual void closeBox() {} + virtual void openFrameBox(const char* label) + {} + virtual void openTabBox(const char* label) + {} + virtual void openHorizontalBox(const char* label) + {} + virtual void openVerticalBox(const char* label) + {} + virtual void closeBox() + {} // Active widgets - virtual void addButton(const char*, float* zone) { addControlInput(zone); } + virtual void addButton(const char*, float* zone) + { + addControlInput(zone); + } virtual void addToggleButton(const char*, float* zone) { addControlInput(zone); @@ -292,7 +305,8 @@ class ControlAllocator : public UI } // Metadata - virtual void declare(float*, const char*, const char*) {} + virtual void declare(float*, const char*, const char*) + {} private: void addControlInput(float* zone) @@ -333,8 +347,14 @@ class MethclaFaustSynth : public MethclaSynth m_dsp.compute(numFrames, inputs, outputs); } - float* controlInput(size_t index) { return m_controlInputs[index]; } - float* controlOutput(size_t index) { return m_controlOutputs[index]; } + float* controlInput(size_t index) + { + return m_controlInputs[index]; + } + float* controlOutput(size_t index) + { + return m_controlOutputs[index]; + } private: FAUSTCLASS m_dsp; diff --git a/include/methcla/detail.hpp b/include/methcla/detail.hpp index b50d9593..88bc2ea7 100644 --- a/include/methcla/detail.hpp +++ b/include/methcla/detail.hpp @@ -30,11 +30,20 @@ namespace Methcla { namespace detail { : m_id(other.m_id) {} - T id() const { return m_id; } + T id() const + { + return m_id; + } - bool operator==(const D& other) const { return m_id == other.m_id; } + bool operator==(const D& other) const + { + return m_id == other.m_id; + } - bool operator!=(const D& other) const { return m_id != other.m_id; } + bool operator!=(const D& other) const + { + return m_id != other.m_id; + } private: T m_id; @@ -73,7 +82,10 @@ namespace Methcla { namespace detail { } } - inline static void checkReturnCode(Methcla_Error err) { throwError(err); } + inline static void checkReturnCode(Methcla_Error err) + { + throwError(err); + } template T combineFlags(T a, T b) { diff --git a/include/methcla/detail/result.hpp b/include/methcla/detail/result.hpp index 9375fd2d..fee71190 100644 --- a/include/methcla/detail/result.hpp +++ b/include/methcla/detail/result.hpp @@ -164,7 +164,10 @@ namespace Methcla { namespace detail { } } - void get() { wait(); } + void get() + { + wait(); + } }; }} // namespace Methcla::detail diff --git a/include/methcla/engine.h b/include/methcla/engine.h index 0eb75ece..e98e265b 100644 --- a/include/methcla/engine.h +++ b/include/methcla/engine.h @@ -91,7 +91,7 @@ typedef struct Methcla_PacketHandler typedef struct Methcla_EngineOptions Methcla_EngineOptions; METHCLA_EXPORT Methcla_Error - methcla_engine_options_new(Methcla_EngineOptions** engine_options); +methcla_engine_options_new(Methcla_EngineOptions** engine_options); METHCLA_EXPORT void methcla_engine_options_free(Methcla_EngineOptions* engine_options); @@ -187,7 +187,7 @@ METHCLA_EXPORT Methcla_Time methcla_engine_current_time(Methcla_Engine* engine); //* Send an OSC packet to the engine. METHCLA_EXPORT Methcla_Error - methcla_engine_send(Methcla_Engine* engine, const Methcla_OSCPacket* packet); +methcla_engine_send(Methcla_Engine* engine, const Methcla_OSCPacket* packet); //* Open a sound file. METHCLA_EXPORT Methcla_Error methcla_engine_soundfile_open( diff --git a/include/methcla/engine.hpp b/include/methcla/engine.hpp index 256f1a91..165143b6 100644 --- a/include/methcla/engine.hpp +++ b/include/methcla/engine.hpp @@ -326,7 +326,7 @@ namespace Methcla { while (!m_freeList.empty()) { void* ptr = m_freeList.front(); - delete[](char*) ptr; + delete[] (char*)ptr; m_freeList.pop_front(); } } diff --git a/include/methcla/file.hpp b/include/methcla/file.hpp index 5016b726..fa57182f 100644 --- a/include/methcla/file.hpp +++ b/include/methcla/file.hpp @@ -45,9 +45,15 @@ namespace Methcla { file_format = info.file_format; } - int64_t samples() const { return channels * frames; } + int64_t samples() const + { + return channels * frames; + } - double duration() const { return (double)frames / (double)samplerate; } + double duration() const + { + return (double)frames / (double)samplerate; + } }; class SoundFile @@ -126,9 +132,15 @@ namespace Methcla { methcla_soundfile_close(m_file); } - operator bool() const { return m_file != nullptr; } + operator bool() const + { + return m_file != nullptr; + } - const SoundFileInfo& info() const { return m_info; } + const SoundFileInfo& info() const + { + return m_info; + } void close() { @@ -171,4 +183,4 @@ namespace Methcla { }; } // namespace Methcla -#endif // METHCLA_FILE_HPP_INCLUDED \ No newline at end of file +#endif // METHCLA_FILE_HPP_INCLUDED diff --git a/include/methcla/platform/rtaudio.hpp b/include/methcla/platform/rtaudio.hpp index a25e167b..8d216216 100644 --- a/include/methcla/platform/rtaudio.hpp +++ b/include/methcla/platform/rtaudio.hpp @@ -18,6 +18,6 @@ #include METHCLA_EXPORT Methcla_AudioDriver* - methcla_rtaudio_driver_new(const Methcla_AudioDriverOptions* options); +methcla_rtaudio_driver_new(const Methcla_AudioDriverOptions* options); #endif // METHCLA_PLATFORM_RTAUDIO_HPP_INCLUDED diff --git a/include/methcla/plugins/soundfile_api_extaudiofile.h b/include/methcla/plugins/soundfile_api_extaudiofile.h index 56bf96fe..f5130b0c 100644 --- a/include/methcla/plugins/soundfile_api_extaudiofile.h +++ b/include/methcla/plugins/soundfile_api_extaudiofile.h @@ -19,6 +19,6 @@ #include METHCLA_EXPORT Methcla_Library* - methcla_soundfile_api_extaudiofile(Methcla_Host*, const char*); +methcla_soundfile_api_extaudiofile(Methcla_Host*, const char*); #endif // METHCLA_SOUNDFILEAPI_EXTAUDIOFILE_H_INCLUDED diff --git a/platform/CMakeLists.txt b/platform/CMakeLists.txt index 7326ce90..a94e4b24 100644 --- a/platform/CMakeLists.txt +++ b/platform/CMakeLists.txt @@ -2,10 +2,6 @@ if(METHCLA_ENABLE_RTAUDIO) add_subdirectory(rtaudio) else() add_library(driver_dummy OBJECT DummyPlatform.cpp) - target_include_directories(driver_dummy PRIVATE - ../include - ../src - ) + target_include_directories(driver_dummy PRIVATE ../include ../src) methcla_target_warnings(driver_dummy) endif() - diff --git a/platform/DummyPlatform.cpp b/platform/DummyPlatform.cpp index 324b8e81..609e8da6 100644 --- a/platform/DummyPlatform.cpp +++ b/platform/DummyPlatform.cpp @@ -1,8 +1,8 @@ #include "Methcla/Audio/IO/DummyDriver.hpp" #include "Methcla/Platform.hpp" -Methcla::Audio::IO::Driver* -Methcla::Platform::defaultAudioDriver(Methcla::Audio::IO::Driver::Options options) +Methcla::Audio::IO::Driver* Methcla::Platform::defaultAudioDriver( + Methcla::Audio::IO::Driver::Options options) { return new Methcla::Audio::IO::DummyDriver(options); } diff --git a/platform/android/Methcla/Audio/IO/OpenSLESDriver.hpp b/platform/android/Methcla/Audio/IO/OpenSLESDriver.hpp index fb7dcae1..e370ac38 100644 --- a/platform/android/Methcla/Audio/IO/OpenSLESDriver.hpp +++ b/platform/android/Methcla/Audio/IO/OpenSLESDriver.hpp @@ -30,10 +30,22 @@ namespace Methcla { namespace Audio { namespace IO { OpenSLESDriver(Options options); virtual ~OpenSLESDriver(); - virtual double sampleRate() const override { return m_sampleRate; } - virtual size_t numInputs() const override { return m_numInputs; } - virtual size_t numOutputs() const override { return m_numOutputs; } - virtual size_t bufferSize() const override { return m_bufferSize; } + virtual double sampleRate() const override + { + return m_sampleRate; + } + virtual size_t numInputs() const override + { + return m_numInputs; + } + virtual size_t numOutputs() const override + { + return m_numOutputs; + } + virtual size_t bufferSize() const override + { + return m_bufferSize; + } virtual void start() override; virtual void stop() override; diff --git a/platform/android/opensl_io.c b/platform/android/opensl_io.c index 47757609..a62e368c 100644 --- a/platform/android/opensl_io.c +++ b/platform/android/opensl_io.c @@ -19,6 +19,8 @@ #include "opensl_io.h" +#include +#include #include #include #include @@ -27,471 +29,530 @@ #include #include -#include -#include - #define LOGI(...) \ - __android_log_print(ANDROID_LOG_INFO, "opensl_io", __VA_ARGS__) + __android_log_print(ANDROID_LOG_INFO, "opensl_io", __VA_ARGS__) #define LOGW(...) \ - __android_log_print(ANDROID_LOG_WARN, "opensl_io", __VA_ARGS__) + __android_log_print(ANDROID_LOG_WARN, "opensl_io", __VA_ARGS__) -#define INITIAL_DELAY 4 +#define INITIAL_DELAY 4 -struct _opensl_stream { - SLObjectItf engineObject; - SLEngineItf engineEngine; +struct _opensl_stream +{ + SLObjectItf engineObject; + SLEngineItf engineEngine; - SLObjectItf outputMixObject; + SLObjectItf outputMixObject; - SLObjectItf playerObject; - SLPlayItf playerPlay; - SLAndroidSimpleBufferQueueItf playerBufferQueue; + SLObjectItf playerObject; + SLPlayItf playerPlay; + SLAndroidSimpleBufferQueueItf playerBufferQueue; - SLObjectItf recorderObject; - SLRecordItf recorderRecord; - SLAndroidSimpleBufferQueueItf recorderBufferQueue; + SLObjectItf recorderObject; + SLRecordItf recorderRecord; + SLAndroidSimpleBufferQueueItf recorderBufferQueue; - int sampleRate; - int inputChannels; - int outputChannels; + int sampleRate; + int inputChannels; + int outputChannels; - int callbackBufferFrames; - int totalBufferFrames; + int callbackBufferFrames; + int totalBufferFrames; - short *inputBuffer; - short *outputBuffer; - short *dummyBuffer; + short* inputBuffer; + short* outputBuffer; + short* dummyBuffer; - int inputIndex; - int outputIndex; - int readIndex; - int initialReadIndex; + int inputIndex; + int outputIndex; + int readIndex; + int initialReadIndex; - int isRunning; + int isRunning; - void *context; - opensl_process_t callback; + void* context; + opensl_process_t callback; - struct timespec inputTime; - int intervals; - double thresholdMillis; + struct timespec inputTime; + int intervals; + double thresholdMillis; - sem_t semReady; - int callbacks; + sem_t semReady; + int callbacks; }; inline static size_t inputBufferSize(OPENSL_STREAM* p) { - return p->totalBufferFrames * p->inputChannels; + return p->totalBufferFrames * p->inputChannels; } inline static size_t outputBufferSize(OPENSL_STREAM* p) { - return p->totalBufferFrames * p->outputChannels; + return p->totalBufferFrames * p->outputChannels; } -static double time_diff_millis(struct timespec *a, struct timespec *b) +static double time_diff_millis(struct timespec* a, struct timespec* b) { - return (a->tv_sec - b->tv_sec) * 1e3 + (a->tv_nsec - b->tv_nsec) * 1e-6; + return (a->tv_sec - b->tv_sec) * 1e3 + (a->tv_nsec - b->tv_nsec) * 1e-6; } -static void recorderCallback(SLAndroidSimpleBufferQueueItf bq, void *context) +static void recorderCallback(SLAndroidSimpleBufferQueueItf bq, void* context) { - OPENSL_STREAM *p = (OPENSL_STREAM *) context; - if (p->intervals < INITIAL_DELAY) { - struct timespec t; - clock_gettime(CLOCK_MONOTONIC, &t); - if (p->inputTime.tv_sec + p->inputTime.tv_nsec > 0) { - double dt = time_diff_millis(&t, &p->inputTime); - if (dt > p->thresholdMillis) { - __sync_bool_compare_and_swap( - &p->intervals, p->intervals, p->intervals + 1); - if (p->intervals < INITIAL_DELAY) { - p->initialReadIndex = p->inputIndex; + OPENSL_STREAM* p = (OPENSL_STREAM*)context; + if (p->intervals < INITIAL_DELAY) + { + struct timespec t; + clock_gettime(CLOCK_MONOTONIC, &t); + if (p->inputTime.tv_sec + p->inputTime.tv_nsec > 0) + { + double dt = time_diff_millis(&t, &p->inputTime); + if (dt > p->thresholdMillis) + { + __sync_bool_compare_and_swap(&p->intervals, p->intervals, + p->intervals + 1); + if (p->intervals < INITIAL_DELAY) + { + p->initialReadIndex = p->inputIndex; + } + } } - } + p->inputTime.tv_sec = t.tv_sec; + p->inputTime.tv_nsec = t.tv_nsec; } - p->inputTime.tv_sec = t.tv_sec; - p->inputTime.tv_nsec = t.tv_nsec; - } - p->inputIndex = (p->inputIndex + p->callbackBufferFrames) % - p->totalBufferFrames; - (*bq)->Enqueue(bq, p->inputBuffer + p->inputIndex * p->inputChannels, - p->callbackBufferFrames * p->inputChannels * sizeof(short)); + p->inputIndex = + (p->inputIndex + p->callbackBufferFrames) % p->totalBufferFrames; + (*bq)->Enqueue(bq, p->inputBuffer + p->inputIndex * p->inputChannels, + p->callbackBufferFrames * p->inputChannels * sizeof(short)); } -static void playerCallback(SLAndroidSimpleBufferQueueItf bq, void *context) +static void playerCallback(SLAndroidSimpleBufferQueueItf bq, void* context) { - OPENSL_STREAM *p = (OPENSL_STREAM *) context; - if (p->callbacks < 2) { - if (++p->callbacks == 2) { - sem_post(&p->semReady); // Start reading input on the second invocation. + OPENSL_STREAM* p = (OPENSL_STREAM*)context; + if (p->callbacks < 2) + { + if (++p->callbacks == 2) + { + sem_post( + &p->semReady); // Start reading input on the second invocation. + } + } + if (p->readIndex < 0 && + __sync_fetch_and_or(&p->intervals, 0) == INITIAL_DELAY) + { + p->readIndex = p->initialReadIndex; // Start reading input when ready. + } + if (p->readIndex >= 0) + { // Render with input if available. + p->callback(p->context, p->sampleRate, p->callbackBufferFrames, + p->inputChannels, + p->inputBuffer + p->readIndex * p->inputChannels, + p->outputChannels, + p->outputBuffer + p->outputIndex * p->outputChannels); + p->readIndex = + (p->readIndex + p->callbackBufferFrames) % p->totalBufferFrames; } - } - if (p->readIndex < 0 && - __sync_fetch_and_or(&p->intervals, 0) == INITIAL_DELAY) { - p->readIndex = p->initialReadIndex; // Start reading input when ready. - } - if (p->readIndex >= 0) { // Render with input if available. - p->callback(p->context, p->sampleRate, p->callbackBufferFrames, - p->inputChannels, - p->inputBuffer + p->readIndex * p->inputChannels, - p->outputChannels, - p->outputBuffer + p->outputIndex * p->outputChannels); - p->readIndex = (p->readIndex + p->callbackBufferFrames) % - p->totalBufferFrames; - } else { // Render with empty input when input is not yet availabe. - p->callback(p->context, p->sampleRate, p->callbackBufferFrames, - p->inputChannels, - p->dummyBuffer, - p->outputChannels, - p->outputBuffer + p->outputIndex * p->outputChannels); - } - (*bq)->Enqueue(bq, p->outputBuffer + p->outputIndex * p->outputChannels, - p->callbackBufferFrames * p->outputChannels * sizeof(short)); - p->outputIndex = (p->outputIndex + p->callbackBufferFrames) % - p->totalBufferFrames; + else + { // Render with empty input when input is not yet availabe. + p->callback(p->context, p->sampleRate, p->callbackBufferFrames, + p->inputChannels, p->dummyBuffer, p->outputChannels, + p->outputBuffer + p->outputIndex * p->outputChannels); + } + (*bq)->Enqueue(bq, p->outputBuffer + p->outputIndex * p->outputChannels, + p->callbackBufferFrames * p->outputChannels * sizeof(short)); + p->outputIndex = + (p->outputIndex + p->callbackBufferFrames) % p->totalBufferFrames; } static SLresult convertSampleRate(SLuint32 sampleRate, SLuint32* outSampleRate) { - // Only return supported sample rates, see $NDK/docs/opensles/index.html - switch (sampleRate) { - case 8000: - *outSampleRate = SL_SAMPLINGRATE_8; - return SL_RESULT_SUCCESS; - case 11025: - *outSampleRate = SL_SAMPLINGRATE_11_025; - return SL_RESULT_SUCCESS; - case 12000: - *outSampleRate = SL_SAMPLINGRATE_12; - return SL_RESULT_SUCCESS; - case 16000: - *outSampleRate = SL_SAMPLINGRATE_16; - return SL_RESULT_SUCCESS; - case 22050: - *outSampleRate = SL_SAMPLINGRATE_22_05; - return SL_RESULT_SUCCESS; - case 24000: - *outSampleRate = SL_SAMPLINGRATE_24; - return SL_RESULT_SUCCESS; - case 32000: - *outSampleRate = SL_SAMPLINGRATE_32; - return SL_RESULT_SUCCESS; - case 44100: - *outSampleRate = SL_SAMPLINGRATE_44_1; - return SL_RESULT_SUCCESS; - case 48000: - *outSampleRate = SL_SAMPLINGRATE_48; - return SL_RESULT_SUCCESS; - } - return SL_RESULT_PARAMETER_INVALID; + // Only return supported sample rates, see $NDK/docs/opensles/index.html + switch (sampleRate) + { + case 8000: + *outSampleRate = SL_SAMPLINGRATE_8; + return SL_RESULT_SUCCESS; + case 11025: + *outSampleRate = SL_SAMPLINGRATE_11_025; + return SL_RESULT_SUCCESS; + case 12000: + *outSampleRate = SL_SAMPLINGRATE_12; + return SL_RESULT_SUCCESS; + case 16000: + *outSampleRate = SL_SAMPLINGRATE_16; + return SL_RESULT_SUCCESS; + case 22050: + *outSampleRate = SL_SAMPLINGRATE_22_05; + return SL_RESULT_SUCCESS; + case 24000: + *outSampleRate = SL_SAMPLINGRATE_24; + return SL_RESULT_SUCCESS; + case 32000: + *outSampleRate = SL_SAMPLINGRATE_32; + return SL_RESULT_SUCCESS; + case 44100: + *outSampleRate = SL_SAMPLINGRATE_44_1; + return SL_RESULT_SUCCESS; + case 48000: + *outSampleRate = SL_SAMPLINGRATE_48; + return SL_RESULT_SUCCESS; + } + return SL_RESULT_PARAMETER_INVALID; } -static SLresult openSLCreateEngine(OPENSL_STREAM *p) +static SLresult openSLCreateEngine(OPENSL_STREAM* p) { - const SLuint32 engineIIDCount = 1; - const SLInterfaceID engineIIDs[] = {SL_IID_ENGINE}; - const SLboolean engineReqs[] = {SL_BOOLEAN_TRUE}; + const SLuint32 engineIIDCount = 1; + const SLInterfaceID engineIIDs[] = {SL_IID_ENGINE}; + const SLboolean engineReqs[] = {SL_BOOLEAN_TRUE}; - SLresult result = slCreateEngine(&p->engineObject, 0, NULL, - engineIIDCount, engineIIDs, engineReqs); - if (result != SL_RESULT_SUCCESS) return result; + SLresult result = slCreateEngine(&p->engineObject, 0, NULL, engineIIDCount, + engineIIDs, engineReqs); + if (result != SL_RESULT_SUCCESS) + return result; - result = (*p->engineObject)->Realize(p->engineObject, SL_BOOLEAN_FALSE); - if (result != SL_RESULT_SUCCESS) return result; + result = (*p->engineObject)->Realize(p->engineObject, SL_BOOLEAN_FALSE); + if (result != SL_RESULT_SUCCESS) + return result; - return (*p->engineObject)->GetInterface( - p->engineObject, SL_IID_ENGINE, &p->engineEngine); + return (*p->engineObject) + ->GetInterface(p->engineObject, SL_IID_ENGINE, &p->engineEngine); } -static SLresult openSLRecOpen(OPENSL_STREAM *p, SLuint32 sr) +static SLresult openSLRecOpen(OPENSL_STREAM* p, SLuint32 sr) { - // enforce (temporary?) bounds on channel numbers) - if (p->inputChannels > 2) { - return SL_RESULT_PARAMETER_INVALID; - } - - SLDataLocator_IODevice loc_dev = - {SL_DATALOCATOR_IODEVICE, SL_IODEVICE_AUDIOINPUT, - SL_DEFAULTDEVICEID_AUDIOINPUT, NULL}; - SLDataSource audioSrc = {&loc_dev, NULL}; // source: microphone - - int mics; - if (p->inputChannels > 1) { - // Yes, we're using speaker macros for mic config. It's okay, really. - mics = SL_SPEAKER_FRONT_LEFT | SL_SPEAKER_FRONT_RIGHT; - } else { - mics = SL_SPEAKER_FRONT_CENTER; - } - SLDataLocator_AndroidSimpleBufferQueue loc_bq = - {SL_DATALOCATOR_ANDROIDSIMPLEBUFFERQUEUE, 1}; - SLDataFormat_PCM format_pcm = - {SL_DATAFORMAT_PCM, p->inputChannels, sr, SL_PCMSAMPLEFORMAT_FIXED_16, - SL_PCMSAMPLEFORMAT_FIXED_16, mics, SL_BYTEORDER_LITTLEENDIAN}; - SLDataSink audioSnk = {&loc_bq, &format_pcm}; // sink: buffer queue - - // create audio recorder (requires the RECORD_AUDIO permission) - const SLInterfaceID id[1] = {SL_IID_ANDROIDSIMPLEBUFFERQUEUE}; - const SLboolean req[1] = {SL_BOOLEAN_TRUE}; - SLresult result = (*p->engineEngine)->CreateAudioRecorder( - p->engineEngine, &p->recorderObject, &audioSrc, &audioSnk, 1, id, req); - if (SL_RESULT_SUCCESS != result) return result; - - result = (*p->recorderObject)->Realize(p->recorderObject, SL_BOOLEAN_FALSE); - if (SL_RESULT_SUCCESS != result) return result; - - result = (*p->recorderObject)->GetInterface(p->recorderObject, - SL_IID_RECORD, &p->recorderRecord); - if (SL_RESULT_SUCCESS != result) return result; - - result = (*p->recorderObject)->GetInterface( - p->recorderObject, SL_IID_ANDROIDSIMPLEBUFFERQUEUE, - &p->recorderBufferQueue); - if (SL_RESULT_SUCCESS != result) return result; - - result = (*p->recorderBufferQueue)->RegisterCallback( - p->recorderBufferQueue, recorderCallback, p); - return result; + // enforce (temporary?) bounds on channel numbers) + if (p->inputChannels > 2) + { + return SL_RESULT_PARAMETER_INVALID; + } + + SLDataLocator_IODevice loc_dev = {SL_DATALOCATOR_IODEVICE, + SL_IODEVICE_AUDIOINPUT, + SL_DEFAULTDEVICEID_AUDIOINPUT, NULL}; + SLDataSource audioSrc = {&loc_dev, NULL}; // source: microphone + + int mics; + if (p->inputChannels > 1) + { + // Yes, we're using speaker macros for mic config. It's okay, really. + mics = SL_SPEAKER_FRONT_LEFT | SL_SPEAKER_FRONT_RIGHT; + } + else + { + mics = SL_SPEAKER_FRONT_CENTER; + } + SLDataLocator_AndroidSimpleBufferQueue loc_bq = { + SL_DATALOCATOR_ANDROIDSIMPLEBUFFERQUEUE, 1}; + SLDataFormat_PCM format_pcm = {SL_DATAFORMAT_PCM, + p->inputChannels, + sr, + SL_PCMSAMPLEFORMAT_FIXED_16, + SL_PCMSAMPLEFORMAT_FIXED_16, + mics, + SL_BYTEORDER_LITTLEENDIAN}; + SLDataSink audioSnk = {&loc_bq, &format_pcm}; // sink: buffer queue + + // create audio recorder (requires the RECORD_AUDIO permission) + const SLInterfaceID id[1] = {SL_IID_ANDROIDSIMPLEBUFFERQUEUE}; + const SLboolean req[1] = {SL_BOOLEAN_TRUE}; + SLresult result = + (*p->engineEngine) + ->CreateAudioRecorder(p->engineEngine, &p->recorderObject, + &audioSrc, &audioSnk, 1, id, req); + if (SL_RESULT_SUCCESS != result) + return result; + + result = (*p->recorderObject)->Realize(p->recorderObject, SL_BOOLEAN_FALSE); + if (SL_RESULT_SUCCESS != result) + return result; + + result = (*p->recorderObject) + ->GetInterface(p->recorderObject, SL_IID_RECORD, + &p->recorderRecord); + if (SL_RESULT_SUCCESS != result) + return result; + + result = + (*p->recorderObject) + ->GetInterface(p->recorderObject, SL_IID_ANDROIDSIMPLEBUFFERQUEUE, + &p->recorderBufferQueue); + if (SL_RESULT_SUCCESS != result) + return result; + + result = + (*p->recorderBufferQueue) + ->RegisterCallback(p->recorderBufferQueue, recorderCallback, p); + return result; } -static SLresult openSLPlayOpen(OPENSL_STREAM *p, SLuint32 sr) +static SLresult openSLPlayOpen(OPENSL_STREAM* p, SLuint32 sr) { - // enforce (temporary?) bounds on channel numbers) - if (p->outputChannels > 2) { - return SL_RESULT_PARAMETER_INVALID; - } - - const SLuint32 mixIIDCount = 0; - const SLInterfaceID mixIIDs[] = {}; - const SLboolean mixReqs[] = {}; - SLresult result = (*p->engineEngine)->CreateOutputMix( - p->engineEngine, &p->outputMixObject, mixIIDCount, mixIIDs, mixReqs); - if (result != SL_RESULT_SUCCESS) return result; - - result = (*p->outputMixObject)->Realize( - p->outputMixObject, SL_BOOLEAN_FALSE); - if (result != SL_RESULT_SUCCESS) return result; - - SLDataFormat_PCM format_pcm; - memset(&format_pcm, 0, sizeof(format_pcm)); - format_pcm.formatType = SL_DATAFORMAT_PCM; - format_pcm.numChannels = p->outputChannels; - format_pcm.samplesPerSec = sr; - format_pcm.bitsPerSample = SL_PCMSAMPLEFORMAT_FIXED_16; - format_pcm.containerSize = SL_PCMSAMPLEFORMAT_FIXED_16; - format_pcm.channelMask = p->outputChannels > 1 - ? SL_SPEAKER_FRONT_LEFT | SL_SPEAKER_FRONT_RIGHT - : SL_SPEAKER_FRONT_CENTER; - format_pcm.endianness = SL_BYTEORDER_LITTLEENDIAN; - - SLDataLocator_AndroidSimpleBufferQueue loc_bufq; - memset(&loc_bufq, 0, sizeof(loc_bufq)); - loc_bufq.locatorType = SL_DATALOCATOR_ANDROIDSIMPLEBUFFERQUEUE; - loc_bufq.numBuffers = 1; - - SLDataSource audioSrc; - memset(&audioSrc, 0, sizeof(audioSrc)); - audioSrc.pLocator = &loc_bufq; - audioSrc.pFormat = &format_pcm; - - SLDataLocator_OutputMix loc_outmix; - memset(&loc_outmix, 0, sizeof(loc_outmix)); - loc_outmix.locatorType = SL_DATALOCATOR_OUTPUTMIX; - loc_outmix.outputMix = p->outputMixObject; - - SLDataSink audioSnk; - memset(&audioSnk, 0, sizeof(audioSnk)); - audioSnk.pLocator = &loc_outmix; - audioSnk.pFormat = NULL; - - // create audio player - const SLuint32 playIIDCount = 2; - const SLInterfaceID playIIDs[] = {SL_IID_PLAY,SL_IID_ANDROIDSIMPLEBUFFERQUEUE}; - const SLboolean playReqs[] = {SL_BOOLEAN_TRUE,SL_BOOLEAN_TRUE}; - result = (*p->engineEngine)->CreateAudioPlayer( - p->engineEngine, &p->playerObject, &audioSrc, &audioSnk, - playIIDCount, playIIDs, playReqs); - if (result != SL_RESULT_SUCCESS) return result; - - result = (*p->playerObject)->Realize(p->playerObject, SL_BOOLEAN_FALSE); - if (result != SL_RESULT_SUCCESS) return result; - - result = (*p->playerObject)->GetInterface( - p->playerObject, SL_IID_PLAY, &p->playerPlay); - if (result != SL_RESULT_SUCCESS) return result; - - result = (*p->playerObject)->GetInterface( - p->playerObject, SL_IID_ANDROIDSIMPLEBUFFERQUEUE, - &p->playerBufferQueue); - if (result != SL_RESULT_SUCCESS) return result; - - result = (*p->playerBufferQueue)->RegisterCallback( - p->playerBufferQueue, playerCallback, p); - return result; + // enforce (temporary?) bounds on channel numbers) + if (p->outputChannels > 2) + { + return SL_RESULT_PARAMETER_INVALID; + } + + const SLuint32 mixIIDCount = 0; + const SLInterfaceID mixIIDs[] = {}; + const SLboolean mixReqs[] = {}; + SLresult result = + (*p->engineEngine) + ->CreateOutputMix(p->engineEngine, &p->outputMixObject, mixIIDCount, + mixIIDs, mixReqs); + if (result != SL_RESULT_SUCCESS) + return result; + + result = + (*p->outputMixObject)->Realize(p->outputMixObject, SL_BOOLEAN_FALSE); + if (result != SL_RESULT_SUCCESS) + return result; + + SLDataFormat_PCM format_pcm; + memset(&format_pcm, 0, sizeof(format_pcm)); + format_pcm.formatType = SL_DATAFORMAT_PCM; + format_pcm.numChannels = p->outputChannels; + format_pcm.samplesPerSec = sr; + format_pcm.bitsPerSample = SL_PCMSAMPLEFORMAT_FIXED_16; + format_pcm.containerSize = SL_PCMSAMPLEFORMAT_FIXED_16; + format_pcm.channelMask = + p->outputChannels > 1 ? SL_SPEAKER_FRONT_LEFT | SL_SPEAKER_FRONT_RIGHT + : SL_SPEAKER_FRONT_CENTER; + format_pcm.endianness = SL_BYTEORDER_LITTLEENDIAN; + + SLDataLocator_AndroidSimpleBufferQueue loc_bufq; + memset(&loc_bufq, 0, sizeof(loc_bufq)); + loc_bufq.locatorType = SL_DATALOCATOR_ANDROIDSIMPLEBUFFERQUEUE; + loc_bufq.numBuffers = 1; + + SLDataSource audioSrc; + memset(&audioSrc, 0, sizeof(audioSrc)); + audioSrc.pLocator = &loc_bufq; + audioSrc.pFormat = &format_pcm; + + SLDataLocator_OutputMix loc_outmix; + memset(&loc_outmix, 0, sizeof(loc_outmix)); + loc_outmix.locatorType = SL_DATALOCATOR_OUTPUTMIX; + loc_outmix.outputMix = p->outputMixObject; + + SLDataSink audioSnk; + memset(&audioSnk, 0, sizeof(audioSnk)); + audioSnk.pLocator = &loc_outmix; + audioSnk.pFormat = NULL; + + // create audio player + const SLuint32 playIIDCount = 2; + const SLInterfaceID playIIDs[] = {SL_IID_PLAY, + SL_IID_ANDROIDSIMPLEBUFFERQUEUE}; + const SLboolean playReqs[] = {SL_BOOLEAN_TRUE, SL_BOOLEAN_TRUE}; + result = + (*p->engineEngine) + ->CreateAudioPlayer(p->engineEngine, &p->playerObject, &audioSrc, + &audioSnk, playIIDCount, playIIDs, playReqs); + if (result != SL_RESULT_SUCCESS) + return result; + + result = (*p->playerObject)->Realize(p->playerObject, SL_BOOLEAN_FALSE); + if (result != SL_RESULT_SUCCESS) + return result; + + result = (*p->playerObject) + ->GetInterface(p->playerObject, SL_IID_PLAY, &p->playerPlay); + if (result != SL_RESULT_SUCCESS) + return result; + + result = + (*p->playerObject) + ->GetInterface(p->playerObject, SL_IID_ANDROIDSIMPLEBUFFERQUEUE, + &p->playerBufferQueue); + if (result != SL_RESULT_SUCCESS) + return result; + + result = (*p->playerBufferQueue) + ->RegisterCallback(p->playerBufferQueue, playerCallback, p); + return result; } -static void openSLDestroyEngine(OPENSL_STREAM *p) +static void openSLDestroyEngine(OPENSL_STREAM* p) { - if (p->playerObject) { - (*p->playerObject)->Destroy(p->playerObject); - } - if (p->recorderObject) { - (*p->recorderObject)->Destroy(p->recorderObject); - } - if (p->outputMixObject) { - (*p->outputMixObject)->Destroy(p->outputMixObject); - } - if (p->engineObject) { - (*p->engineObject)->Destroy(p->engineObject); - } + if (p->playerObject) + { + (*p->playerObject)->Destroy(p->playerObject); + } + if (p->recorderObject) + { + (*p->recorderObject)->Destroy(p->recorderObject); + } + if (p->outputMixObject) + { + (*p->outputMixObject)->Destroy(p->outputMixObject); + } + if (p->engineObject) + { + (*p->engineObject)->Destroy(p->engineObject); + } } -OPENSL_STREAM *opensl_open( - int sampleRate, int inChans, int outChans, int callbackBufferFrames, - opensl_process_t proc, void *context) +OPENSL_STREAM* opensl_open(int sampleRate, int inChans, int outChans, + int callbackBufferFrames, opensl_process_t proc, + void* context) { - if (sampleRate <= 0) - return NULL; - if (inChans < 0) - return NULL; - if (outChans <= 0) - return NULL; - if (callbackBufferFrames <= 0) - return NULL; - if (proc == NULL) - return NULL; - - SLuint32 srmillihz; - SLresult result = convertSampleRate(sampleRate, &srmillihz); - if (result != SL_RESULT_SUCCESS) - return NULL; - - OPENSL_STREAM *p = (OPENSL_STREAM *) calloc(1, sizeof(OPENSL_STREAM)); - if (!p) { - return NULL; - } - - sem_init(&p->semReady, 0, 0); - - p->callback = proc; - p->context = context; - p->isRunning = 0; - - p->inputBuffer = NULL; - p->outputBuffer = NULL; - p->dummyBuffer = NULL; - p->callbackBufferFrames = callbackBufferFrames; - - // Half the buffer duration in milliseconds. - p->thresholdMillis = 500.0 * callbackBufferFrames / sampleRate; - - p->totalBufferFrames = - (sampleRate / callbackBufferFrames) * callbackBufferFrames; - - p->inputChannels = inChans; - p->outputChannels = outChans; - p->sampleRate = sampleRate; - - if (openSLCreateEngine(p) != SL_RESULT_SUCCESS) { - opensl_close(p); - return NULL; - } - - if (p->inputChannels > 0) { - if (!(openSLRecOpen(p, srmillihz) == SL_RESULT_SUCCESS && - (p->inputBuffer = (short *) calloc(inputBufferSize(p), sizeof(short))) && - (p->dummyBuffer = (short *) calloc(callbackBufferFrames * p->inputChannels, - sizeof(short))))) { - opensl_close(p); - return NULL; + if (sampleRate <= 0) + return NULL; + if (inChans < 0) + return NULL; + if (outChans <= 0) + return NULL; + if (callbackBufferFrames <= 0) + return NULL; + if (proc == NULL) + return NULL; + + SLuint32 srmillihz; + SLresult result = convertSampleRate(sampleRate, &srmillihz); + if (result != SL_RESULT_SUCCESS) + return NULL; + + OPENSL_STREAM* p = (OPENSL_STREAM*)calloc(1, sizeof(OPENSL_STREAM)); + if (!p) + { + return NULL; + } + + sem_init(&p->semReady, 0, 0); + + p->callback = proc; + p->context = context; + p->isRunning = 0; + + p->inputBuffer = NULL; + p->outputBuffer = NULL; + p->dummyBuffer = NULL; + p->callbackBufferFrames = callbackBufferFrames; + + // Half the buffer duration in milliseconds. + p->thresholdMillis = 500.0 * callbackBufferFrames / sampleRate; + + p->totalBufferFrames = + (sampleRate / callbackBufferFrames) * callbackBufferFrames; + + p->inputChannels = inChans; + p->outputChannels = outChans; + p->sampleRate = sampleRate; + + if (openSLCreateEngine(p) != SL_RESULT_SUCCESS) + { + opensl_close(p); + return NULL; } - } - if (p->outputChannels > 0) { - if (!(openSLPlayOpen(p, srmillihz) == SL_RESULT_SUCCESS && - (p->outputBuffer = (short *) calloc(outputBufferSize(p), sizeof(short))))) { - opensl_close(p); - return NULL; + if (p->inputChannels > 0) + { + if (!(openSLRecOpen(p, srmillihz) == SL_RESULT_SUCCESS && + (p->inputBuffer = + (short*)calloc(inputBufferSize(p), sizeof(short))) && + (p->dummyBuffer = (short*)calloc( + callbackBufferFrames * p->inputChannels, sizeof(short))))) + { + opensl_close(p); + return NULL; + } } - } - return p; + if (p->outputChannels > 0) + { + if (!(openSLPlayOpen(p, srmillihz) == SL_RESULT_SUCCESS && + (p->outputBuffer = + (short*)calloc(outputBufferSize(p), sizeof(short))))) + { + opensl_close(p); + return NULL; + } + } + + return p; } -void opensl_close(OPENSL_STREAM *p) +void opensl_close(OPENSL_STREAM* p) { - opensl_pause(p); - openSLDestroyEngine(p); - sem_destroy(&p->semReady); - free(p->inputBuffer); - free(p->outputBuffer); - free(p->dummyBuffer); - free(p); + opensl_pause(p); + openSLDestroyEngine(p); + sem_destroy(&p->semReady); + free(p->inputBuffer); + free(p->outputBuffer); + free(p->dummyBuffer); + free(p); } -int opensl_is_running(OPENSL_STREAM *p) +int opensl_is_running(OPENSL_STREAM* p) { - return p->isRunning; + return p->isRunning; } -int opensl_start(OPENSL_STREAM *p) +int opensl_start(OPENSL_STREAM* p) { - if (p->isRunning) { - return 0; // Already running. - } + if (p->isRunning) + { + return 0; // Already running. + } - while (!sem_trywait(&p->semReady)); // Clear semaphore, just in case. + while (!sem_trywait(&p->semReady)) + ; // Clear semaphore, just in case. - p->inputIndex = 0; - p->outputIndex = 0; - p->readIndex = -1; - p->initialReadIndex = 0; + p->inputIndex = 0; + p->outputIndex = 0; + p->readIndex = -1; + p->initialReadIndex = 0; - p->inputTime.tv_sec = 0; - p->inputTime.tv_nsec = 0; - p->intervals = 0; - p->callbacks = 0; + p->inputTime.tv_sec = 0; + p->inputTime.tv_nsec = 0; + p->intervals = 0; + p->callbacks = 0; - if (p->outputChannels > 0) { - memset(p->outputBuffer, 0, outputBufferSize(p) * sizeof(short)); - } + if (p->outputChannels > 0) + { + memset(p->outputBuffer, 0, outputBufferSize(p) * sizeof(short)); + } - if ((*p->playerPlay)->SetPlayState(p->playerPlay, - SL_PLAYSTATE_PLAYING) != SL_RESULT_SUCCESS) { - opensl_pause(p); - return -1; - } - LOGI("Starting player queue."); - playerCallback(p->playerBufferQueue, p); - - if (p->recorderRecord) { - memset(p->inputBuffer, 0, inputBufferSize(p) * sizeof(short)); - sem_wait(&p->semReady); - if ((*p->recorderRecord)->SetRecordState(p->recorderRecord, - SL_RECORDSTATE_RECORDING) != SL_RESULT_SUCCESS) { - opensl_pause(p); - return -1; + if ((*p->playerPlay)->SetPlayState(p->playerPlay, SL_PLAYSTATE_PLAYING) != + SL_RESULT_SUCCESS) + { + opensl_pause(p); + return -1; + } + LOGI("Starting player queue."); + playerCallback(p->playerBufferQueue, p); + + if (p->recorderRecord) + { + memset(p->inputBuffer, 0, inputBufferSize(p) * sizeof(short)); + sem_wait(&p->semReady); + if ((*p->recorderRecord) + ->SetRecordState(p->recorderRecord, SL_RECORDSTATE_RECORDING) != + SL_RESULT_SUCCESS) + { + opensl_pause(p); + return -1; + } + LOGI("Starting recorder queue."); + recorderCallback(p->recorderBufferQueue, p); } - LOGI("Starting recorder queue."); - recorderCallback(p->recorderBufferQueue, p); - } - p->isRunning = 1; - return 0; + p->isRunning = 1; + return 0; } -void opensl_pause(OPENSL_STREAM *p) +void opensl_pause(OPENSL_STREAM* p) { - if (p->isRunning) { - if (p->recorderRecord) { - (*p->recorderBufferQueue)->Clear(p->recorderBufferQueue); - (*p->recorderRecord)->SetRecordState(p->recorderRecord, - SL_RECORDSTATE_STOPPED); + if (p->isRunning) + { + if (p->recorderRecord) + { + (*p->recorderBufferQueue)->Clear(p->recorderBufferQueue); + (*p->recorderRecord) + ->SetRecordState(p->recorderRecord, SL_RECORDSTATE_STOPPED); + } + (*p->playerBufferQueue)->Clear(p->playerBufferQueue); + (*p->playerPlay)->SetPlayState(p->playerPlay, SL_PLAYSTATE_STOPPED); + p->isRunning = 0; } - (*p->playerBufferQueue)->Clear(p->playerBufferQueue); - (*p->playerPlay)->SetPlayState(p->playerPlay, - SL_PLAYSTATE_STOPPED); - p->isRunning = 0; - } } diff --git a/platform/ios/Methcla/Audio/IO/RemoteIODriver.cpp b/platform/ios/Methcla/Audio/IO/RemoteIODriver.cpp index 8a133147..fde95b14 100644 --- a/platform/ios/Methcla/Audio/IO/RemoteIODriver.cpp +++ b/platform/ios/Methcla/Audio/IO/RemoteIODriver.cpp @@ -506,7 +506,10 @@ Methcla_Time RemoteIODriver::currentTime() CAHostTimeBase::GetInverseFrequency(); } -AudioUnit RemoteIODriver::audioUnit() { return m_rioUnit; } +AudioUnit RemoteIODriver::audioUnit() +{ + return m_rioUnit; +} Driver* Methcla::Platform::defaultAudioDriver(Driver::Options options) { diff --git a/platform/ios/Methcla/Audio/IO/RemoteIODriver.hpp b/platform/ios/Methcla/Audio/IO/RemoteIODriver.hpp index f7e78843..cb8d4241 100644 --- a/platform/ios/Methcla/Audio/IO/RemoteIODriver.hpp +++ b/platform/ios/Methcla/Audio/IO/RemoteIODriver.hpp @@ -26,10 +26,22 @@ namespace Methcla { namespace Audio { namespace IO { RemoteIODriver(Options options, bool initializeAudioSession = true); virtual ~RemoteIODriver(); - virtual double sampleRate() const override { return m_sampleRate; } - virtual size_t numInputs() const override { return m_numInputs; } - virtual size_t numOutputs() const override { return m_numOutputs; } - virtual size_t bufferSize() const override { return m_bufferSize; } + virtual double sampleRate() const override + { + return m_sampleRate; + } + virtual size_t numInputs() const override + { + return m_numInputs; + } + virtual size_t numOutputs() const override + { + return m_numOutputs; + } + virtual size_t bufferSize() const override + { + return m_bufferSize; + } virtual Methcla_Time currentTime() override; diff --git a/platform/jack/Methcla/Audio/IO/JackDriver.cpp b/platform/jack/Methcla/Audio/IO/JackDriver.cpp index 62544186..e8acdd9b 100644 --- a/platform/jack/Methcla/Audio/IO/JackDriver.cpp +++ b/platform/jack/Methcla/Audio/IO/JackDriver.cpp @@ -159,9 +159,15 @@ int JackDriver::processCallback(jack_nframes_t nframes, void* arg) return 0; } -void JackDriver::start() { jack_activate(m_jackClient); } +void JackDriver::start() +{ + jack_activate(m_jackClient); +} -void JackDriver::stop() { jack_deactivate(m_jackClient); } +void JackDriver::stop() +{ + jack_deactivate(m_jackClient); +} Driver* Methcla::Platform::defaultAudioDriver(Driver::Options options) { diff --git a/platform/jack/Methcla/Audio/IO/JackDriver.hpp b/platform/jack/Methcla/Audio/IO/JackDriver.hpp index 856b78eb..af2626c9 100644 --- a/platform/jack/Methcla/Audio/IO/JackDriver.hpp +++ b/platform/jack/Methcla/Audio/IO/JackDriver.hpp @@ -28,10 +28,22 @@ namespace Methcla { namespace Audio { namespace IO { JackDriver(Options options); virtual ~JackDriver(); - virtual double sampleRate() const override { return m_sampleRate; } - virtual size_t numInputs() const override { return m_numInputs; } - virtual size_t numOutputs() const override { return m_numOutputs; } - virtual size_t bufferSize() const override { return m_bufferSize; } + virtual double sampleRate() const override + { + return m_sampleRate; + } + virtual size_t numInputs() const override + { + return m_numInputs; + } + virtual size_t numOutputs() const override + { + return m_numOutputs; + } + virtual size_t bufferSize() const override + { + return m_bufferSize; + } virtual void start() override; virtual void stop() override; diff --git a/platform/rtaudio/CMakeLists.txt b/platform/rtaudio/CMakeLists.txt index 96fb973b..b86f2141 100644 --- a/platform/rtaudio/CMakeLists.txt +++ b/platform/rtaudio/CMakeLists.txt @@ -2,26 +2,16 @@ find_package(PkgConfig) pkg_check_modules(rtaudio rtaudio REQUIRED IMPORTED_TARGET) -add_library(driver_rtaudio OBJECT - Methcla/Audio/IO/RtAudioDriver.cpp -) +add_library(driver_rtaudio OBJECT Methcla/Audio/IO/RtAudioDriver.cpp) -target_include_directories(driver_rtaudio - PRIVATE - . - ../../include - ../../src -) +target_include_directories(driver_rtaudio PRIVATE . ../../include ../../src) -target_include_directories(driver_rtaudio SYSTEM PRIVATE - ../../external_libraries/boost -) +target_include_directories(driver_rtaudio SYSTEM + PRIVATE ../../external_libraries/boost) -target_link_libraries(driver_rtaudio - PUBLIC - PkgConfig::rtaudio - PRIVATE - oscpp::oscpp -) +target_link_libraries( + driver_rtaudio + PUBLIC PkgConfig::rtaudio + PRIVATE oscpp::oscpp) methcla_target_warnings(driver_rtaudio) diff --git a/platform/rtaudio/Methcla/Audio/IO/RtAudioDriver.cpp b/platform/rtaudio/Methcla/Audio/IO/RtAudioDriver.cpp index b5957d93..1f4d7297 100644 --- a/platform/rtaudio/Methcla/Audio/IO/RtAudioDriver.cpp +++ b/platform/rtaudio/Methcla/Audio/IO/RtAudioDriver.cpp @@ -55,27 +55,30 @@ RtAudioDriver::RtAudioDriver(Options options) } else if (*options.numInputs > 0) { - const auto available = std::max( - 0u, m_audio.getDeviceInfo(iParams.deviceId).inputChannels); + const auto available = + std::max(0u, m_audio.getDeviceInfo(iParams.deviceId).inputChannels); // clamp to number of available channels - iParams.nChannels = std::min(static_cast(*options.numInputs), available); + iParams.nChannels = + std::min(static_cast(*options.numInputs), available); if (0 < iParams.nChannels) iParamsPtr = &iParams; } oParams.deviceId = m_audio.getDefaultOutputDevice(); - oParams.nChannels = options.numOutputs.has_value() - ? static_cast(*options.numOutputs) - : m_audio.getDeviceInfo(oParams.deviceId).outputChannels; + oParams.nChannels = + options.numOutputs.has_value() + ? static_cast(*options.numOutputs) + : m_audio.getDeviceInfo(oParams.deviceId).outputChannels; const unsigned int sampleRate = options.sampleRate.value_or(44100); - unsigned int bufferFrames = static_cast(options.bufferSize.value_or(kDefaultBufferSize)); + unsigned int bufferFrames = static_cast( + options.bufferSize.value_or(kDefaultBufferSize)); RtAudio::StreamOptions streamOptions; streamOptions.flags = RTAUDIO_MINIMIZE_LATENCY | RTAUDIO_SCHEDULE_REALTIME; const RtAudioErrorType err = m_audio.openStream( - &oParams, iParamsPtr, RTAUDIO_FLOAT32, sampleRate, - &bufferFrames, processCallback, this, &streamOptions); + &oParams, iParamsPtr, RTAUDIO_FLOAT32, sampleRate, &bufferFrames, + processCallback, this, &streamOptions); if (err != RTAUDIO_NO_ERROR) throw std::runtime_error("RtAudioDriver: Failed to open audio stream"); m_sampleRate = m_audio.getStreamSampleRate(); diff --git a/plugins/CMakeLists.txt b/plugins/CMakeLists.txt index 31405b4d..afa02589 100644 --- a/plugins/CMakeLists.txt +++ b/plugins/CMakeLists.txt @@ -1,55 +1,50 @@ function(add_methcla_plugin name source) set(target "methcla_plugin_${name}") add_library(${target} MODULE ${source}) - set_target_properties(${target} PROPERTIES - PREFIX "" - LIBRARY_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/plugins" - ) - target_include_directories(${target} PRIVATE - $ - ) + set_target_properties( + ${target} PROPERTIES PREFIX "" LIBRARY_OUTPUT_DIRECTORY + "${CMAKE_BINARY_DIR}/plugins") + target_include_directories( + ${target} + PRIVATE $) target_link_libraries(${target} PRIVATE oscpp::oscpp) methcla_target_warnings(${target}) install(TARGETS ${target} - LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}/methcla/plugins) - if (source MATCHES ".*\\.c$") - target_compile_options(${target} PRIVATE - "$<$:-Wno-unused-parameter>" - "$<$:-Wno-unused-parameter>" - "$<$:-Wno-unused-parameter>" - ) + LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}/methcla/plugins) + if(source MATCHES ".*\\.c$") + target_compile_options( + ${target} + PRIVATE "$<$:-Wno-unused-parameter>" + "$<$:-Wno-unused-parameter>" + "$<$:-Wno-unused-parameter>") endif() endfunction() -foreach(source IN ITEMS - disksampler.cpp - node_control.cpp - patch_cable.cpp - sampler.cpp - sine.c - soundfile_api_dummy.cpp -) +foreach(source IN ITEMS disksampler.cpp node_control.cpp patch_cable.cpp + sampler.cpp sine.c soundfile_api_dummy.cpp) get_filename_component(name ${source} NAME_WE) add_methcla_plugin(${name} ${source}) endforeach() -if (APPLE) +if(APPLE) find_library(CoreFoundation_LIB CoreFoundation REQUIRED) find_library(AudioToolbox_LIB AudioToolbox REQUIRED) - add_methcla_plugin(soundfile_api_extaudiofile soundfile_api_extaudiofile.cpp) - target_link_libraries(methcla_plugin_soundfile_api_extaudiofile PRIVATE - ${CoreFoundation_LIB} - ${AudioToolbox_LIB} - ) -endif () + add_methcla_plugin(soundfile_api_extaudiofile + soundfile_api_extaudiofile.cpp) + target_link_libraries(methcla_plugin_soundfile_api_extaudiofile + PRIVATE ${CoreFoundation_LIB} ${AudioToolbox_LIB}) +endif() find_package(PkgConfig) -if (PkgConfig_FOUND) +if(PkgConfig_FOUND) pkg_check_modules(sndfile IMPORTED_TARGET sndfile) - if (sndfile_FOUND) - add_methcla_plugin(soundfile_api_libsndfile soundfile_api_libsndfile.cpp) - target_link_libraries(methcla_plugin_soundfile_api_libsndfile PRIVATE PkgConfig::sndfile) - else () - message(STATUS "libsndfile not found — skipping soundfile_api_libsndfile") - endif () -endif () + if(sndfile_FOUND) + add_methcla_plugin(soundfile_api_libsndfile + soundfile_api_libsndfile.cpp) + target_link_libraries(methcla_plugin_soundfile_api_libsndfile + PRIVATE PkgConfig::sndfile) + else() + message( + STATUS "libsndfile not found — skipping soundfile_api_libsndfile") + endif() +endif() diff --git a/plugins/disksampler.cpp b/plugins/disksampler.cpp index f50cf0a1..82dfeb54 100644 --- a/plugins/disksampler.cpp +++ b/plugins/disksampler.cpp @@ -813,7 +813,8 @@ inline size_t resample(float* out0, float* out1, size_t numFrames, bufferPhase += rate; filePhase += rate; - if constexpr (wrapPhase) { + if constexpr (wrapPhase) + { if (bufferPhase >= maxBufferPhase) bufferPhase -= maxBufferPhase; } @@ -954,8 +955,7 @@ static void process(Methcla_World* world, Methcla_Synth* synth, { case kIdle: case kFilling: - case kFinishing: - { + case kFinishing: { const size_t numFramesProduced = withInterp ? process_disk_interp(world, self, numFrames, amp, rate, @@ -1017,9 +1017,9 @@ static const Methcla_SynthDef kDiskSamplerDef = { static Methcla_Library kDiskSamplerLibrary = {nullptr, nullptr}; -METHCLA_EXPORT Methcla_Library* METHCLA_PLUGIN_LOAD( - methcla_plugins_disksampler)(Methcla_Host* host, - const char* /* bundlePath */) +METHCLA_EXPORT Methcla_Library* +METHCLA_PLUGIN_LOAD(methcla_plugins_disksampler)(Methcla_Host* host, + const char* /* bundlePath */) { methcla_host_register_synthdef(host, &kDiskSamplerDef); return &kDiskSamplerLibrary; diff --git a/plugins/node_control.cpp b/plugins/node_control.cpp index 9ba353e3..010961d2 100644 --- a/plugins/node_control.cpp +++ b/plugins/node_control.cpp @@ -279,9 +279,10 @@ class ExponentialFade const Methcla_SynthDef*, const ExponentialFadeOptions& options) : m_state(kRunning) - , m_numFramesLeft(static_cast(std::llround(options.duration * world.sampleRate()))) - , m_growth(static_cast(std::pow(options.endLevel / options.startLevel, - 1.0 / m_numFramesLeft))) + , m_numFramesLeft(static_cast( + std::llround(options.duration * world.sampleRate()))) + , m_growth(static_cast(std::pow( + options.endLevel / options.startLevel, 1.0 / m_numFramesLeft))) , m_level(options.startLevel) { std::fill(m_ports, m_ports + ExponentialFadePorts::numPorts(), nullptr); @@ -341,9 +342,9 @@ static StaticSynthDef channelDist(1, 2); std::uniform_int_distribution framesDist(static_cast(0.1 * 44100), - static_cast(10 * 44100)); + static_cast(10 * 44100)); SoundFileHandle* handle = (SoundFileHandle*)malloc(sizeof(SoundFileHandle)); if (handle == nullptr) @@ -177,8 +177,8 @@ static Methcla_Error soundfile_open(Methcla_SoundFileAPI* /*api*/, static Methcla_SoundFileAPI kSoundFileAPI = {nullptr, nullptr, soundfile_open}; METHCLA_EXPORT Methcla_Library* - METHCLA_PLUGIN_LOAD(methcla_soundfile_api_dummy)(Methcla_Host* host, - const char*) +METHCLA_PLUGIN_LOAD(methcla_soundfile_api_dummy)(Methcla_Host* host, + const char*) { methcla_host_register_soundfile_api(host, &kSoundFileAPI); return nullptr; diff --git a/plugins/soundfile_api_extaudiofile.cpp b/plugins/soundfile_api_extaudiofile.cpp index 316a29a8..a159175b 100644 --- a/plugins/soundfile_api_extaudiofile.cpp +++ b/plugins/soundfile_api_extaudiofile.cpp @@ -424,8 +424,8 @@ Methcla_Error soundfile_open(Methcla_SoundFileAPI*, const char* path, static Methcla_SoundFileAPI kSoundFileAPI = {nullptr, nullptr, soundfile_open}; METHCLA_EXPORT Methcla_Library* - METHCLA_PLUGIN_LOAD(methcla_soundfile_api_extaudiofile)(Methcla_Host* host, - const char*) +METHCLA_PLUGIN_LOAD(methcla_soundfile_api_extaudiofile)(Methcla_Host* host, + const char*) { methcla_host_register_soundfile_api(host, &kSoundFileAPI); return nullptr; diff --git a/plugins/soundfile_api_libsndfile.cpp b/plugins/soundfile_api_libsndfile.cpp index f0a1e64e..ef631ba7 100644 --- a/plugins/soundfile_api_libsndfile.cpp +++ b/plugins/soundfile_api_libsndfile.cpp @@ -201,8 +201,8 @@ static Methcla_Error soundfile_open(Methcla_SoundFileAPI*, const char* path, static Methcla_SoundFileAPI kSoundFileAPI = {nullptr, nullptr, soundfile_open}; METHCLA_EXPORT Methcla_Library* - METHCLA_PLUGIN_LOAD(methcla_soundfile_api_libsndfile)(Methcla_Host* host, - const char*) +METHCLA_PLUGIN_LOAD(methcla_soundfile_api_libsndfile)(Methcla_Host* host, + const char*) { methcla_host_register_soundfile_api(host, &kSoundFileAPI); return nullptr; diff --git a/scripts/release.py b/scripts/release.py index b1e6993a..8bf95e2b 100755 --- a/scripts/release.py +++ b/scripts/release.py @@ -12,7 +12,9 @@ def run(cmd): def get_output(cmd): - return subprocess.run(cmd, check=True, capture_output=True, text=True).stdout.strip() + return subprocess.run( + cmd, check=True, capture_output=True, text=True + ).stdout.strip() def github_url(): diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index 519360d4..c34d318f 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -46,15 +46,18 @@ set(sources Methcla/Utility/MessageQueueInterface.hpp Methcla/Utility/Semaphore.cpp Methcla/Utility/Semaphore.hpp - Methcla/Utility/WorkerInterface.hpp -) + Methcla/Utility/WorkerInterface.hpp) add_library(methcla ${sources}) -target_sources(methcla PUBLIC - FILE_SET HEADERS - BASE_DIRS ${METHCLA_SOURCE_DIR}/include - FILES +target_sources( + methcla + PUBLIC + FILE_SET + HEADERS + BASE_DIRS + ${METHCLA_SOURCE_DIR}/include + FILES ${METHCLA_SOURCE_DIR}/include/methcla/common.h ${METHCLA_SOURCE_DIR}/include/methcla/detail.hpp ${METHCLA_SOURCE_DIR}/include/methcla/detail/result.hpp @@ -76,23 +79,22 @@ target_sources(methcla PUBLIC ${METHCLA_SOURCE_DIR}/include/methcla/plugins/soundfile_api_dummy.h ${METHCLA_SOURCE_DIR}/include/methcla/plugins/soundfile_api_extaudiofile.h ${METHCLA_SOURCE_DIR}/include/methcla/plugins/soundfile_api_libsndfile.h - ${METHCLA_SOURCE_DIR}/include/methcla/types.h -) + ${METHCLA_SOURCE_DIR}/include/methcla/types.h) -target_include_directories(methcla PUBLIC - $ - $ -) +target_include_directories( + methcla PUBLIC $ + $) -install(TARGETS methcla EXPORT methclaTargets +install( + TARGETS methcla + EXPORT methclaTargets ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR} - FILE_SET HEADERS DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}) + FILE_SET HEADERS + DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}) -target_include_directories(methcla PRIVATE - ${CMAKE_CURRENT_SOURCE_DIR} - ${CMAKE_CURRENT_BINARY_DIR} - ../external_libraries -) +target_include_directories( + methcla PRIVATE ${CMAKE_CURRENT_SOURCE_DIR} ${CMAKE_CURRENT_BINARY_DIR} + ../external_libraries) if(METHCLA_ENABLE_RTAUDIO) set(methcla_driver driver_rtaudio) @@ -100,22 +102,23 @@ else() set(methcla_driver driver_dummy) endif() -target_link_libraries(methcla +target_link_libraries( + methcla PUBLIC oscpp::oscpp - PRIVATE - $ - $ - $ - $) + PRIVATE $ $ + $ $) -# GCC false positives triggered by third-party headers (boost::lockfree, tinydir) -target_compile_options(methcla PRIVATE - "$<$:-Wno-array-bounds;-Wno-stringop-overflow;-Wno-restrict>" +# GCC false positives triggered by third-party headers (boost::lockfree, +# tinydir) +target_compile_options( + methcla + PRIVATE + "$<$:-Wno-array-bounds;-Wno-stringop-overflow;-Wno-restrict>" ) -if (LINUX) +if(LINUX) target_link_libraries(methcla PUBLIC atomic dl pthread) -endif () +endif() methcla_target_warnings(methcla) diff --git a/src/Methcla/API.cpp b/src/Methcla/API.cpp index c5ec1cc1..5faf834b 100644 --- a/src/Methcla/API.cpp +++ b/src/Methcla/API.cpp @@ -73,10 +73,14 @@ Methcla::Audio::IO::Driver::Options Methcla::API::convertOptions(const Methcla_AudioDriverOptions* options) { Methcla::Audio::IO::Driver::Options result; - if (options->sample_rate) result.sampleRate = static_cast(*options->sample_rate); - if (options->num_inputs) result.numInputs = *options->num_inputs; - if (options->num_outputs) result.numOutputs = *options->num_outputs; - if (options->buffer_size) result.bufferSize = *options->buffer_size; + if (options->sample_rate) + result.sampleRate = static_cast(*options->sample_rate); + if (options->num_inputs) + result.numInputs = *options->num_inputs; + if (options->num_outputs) + result.numOutputs = *options->num_outputs; + if (options->buffer_size) + result.bufferSize = *options->buffer_size; return result; } @@ -155,7 +159,8 @@ struct Methcla_Engine m_driver = std::unique_ptr(driver); m_driver->driver()->setProcessCallback(processCallback, this); - engineOptions.sampleRate = static_cast(m_driver->driver()->sampleRate()); + engineOptions.sampleRate = + static_cast(m_driver->driver()->sampleRate()); engineOptions.blockSize = m_driver->driver()->bufferSize(); engineOptions.numHardwareInputChannels = m_driver->driver()->numInputs(); @@ -328,7 +333,7 @@ METHCLA_EXPORT Methcla_Error methcla_default_audio_driver( } METHCLA_EXPORT Methcla_Error - methcla_engine_options_new(Methcla_EngineOptions** engine_options) +methcla_engine_options_new(Methcla_EngineOptions** engine_options) { if (engine_options == nullptr) return methcla_error_new(kMethcla_ArgumentError); @@ -522,7 +527,7 @@ METHCLA_EXPORT Methcla_Time methcla_engine_current_time(Methcla_Engine* engine) } METHCLA_EXPORT Methcla_Error - methcla_engine_send(Methcla_Engine* engine, const Methcla_OSCPacket* packet) +methcla_engine_send(Methcla_Engine* engine, const Methcla_OSCPacket* packet) { if (engine == nullptr) return methcla_error_new(kMethcla_ArgumentError); diff --git a/src/Methcla/API.hpp b/src/Methcla/API.hpp index a912b539..2cdf6157 100644 --- a/src/Methcla/API.hpp +++ b/src/Methcla/API.hpp @@ -32,4 +32,4 @@ namespace Methcla { namespace API { Methcla::Audio::IO::Driver* getDriver(Methcla_Engine* engine); }} // namespace Methcla::API -#endif // METHCLA_API_HPP_INCLUDED \ No newline at end of file +#endif // METHCLA_API_HPP_INCLUDED diff --git a/src/Methcla/Audio/AudioBus.cpp b/src/Methcla/Audio/AudioBus.cpp index cc776310..321ebd54 100644 --- a/src/Methcla/Audio/AudioBus.cpp +++ b/src/Methcla/Audio/AudioBus.cpp @@ -23,7 +23,8 @@ AudioBus::AudioBus(sample_t* data, Epoch epoch) , m_data(data) {} -AudioBus::~AudioBus() {} +AudioBus::~AudioBus() +{} ExternalAudioBus::ExternalAudioBus(Epoch epoch) : AudioBus(nullptr, epoch) @@ -33,4 +34,7 @@ InternalAudioBus::InternalAudioBus(size_t numFrames, Epoch epoch) : AudioBus(allocAlignedOf(kSIMDAlignment, numFrames), epoch) {} -InternalAudioBus::~InternalAudioBus() { Methcla::Memory::freeAligned(data()); } +InternalAudioBus::~InternalAudioBus() +{ + Methcla::Memory::freeAligned(data()); +} diff --git a/src/Methcla/Audio/AudioBus.hpp b/src/Methcla/Audio/AudioBus.hpp index 8b59074e..3412c1ea 100644 --- a/src/Methcla/Audio/AudioBus.hpp +++ b/src/Methcla/Audio/AudioBus.hpp @@ -49,14 +49,26 @@ namespace Methcla { namespace Audio { // Lock& lock() { return m_lock; } - const Epoch& epoch() const { return m_epoch; } + const Epoch& epoch() const + { + return m_epoch; + } - void setEpoch(const Epoch& epoch) { m_epoch = epoch; } + void setEpoch(const Epoch& epoch) + { + m_epoch = epoch; + } - sample_t* data() { return m_data; } + sample_t* data() + { + return m_data; + } protected: - void setData(sample_t* data) { m_data = data; } + void setData(sample_t* data) + { + m_data = data; + } private: // Lock m_lock; @@ -68,7 +80,10 @@ namespace Methcla { namespace Audio { { public: ExternalAudioBus(Epoch epoch); - void setData(sample_t* data) { AudioBus::setData(data); } + void setData(sample_t* data) + { + AudioBus::setData(data); + } }; class InternalAudioBus : public AudioBus diff --git a/src/Methcla/Audio/DSP.c b/src/Methcla/Audio/DSP.c index 779e13c8..16eeaf1a 100644 --- a/src/Methcla/Audio/DSP.c +++ b/src/Methcla/Audio/DSP.c @@ -2,7 +2,8 @@ void accumulate(float* restrict a, const float* restrict b, int n) { - for (int i=0; i < n; i++) { + for (int i = 0; i < n; i++) + { a[i] += b[i]; } } diff --git a/src/Methcla/Audio/Engine.cpp b/src/Methcla/Audio/Engine.cpp index b71f99ec..da999088 100644 --- a/src/Methcla/Audio/Engine.cpp +++ b/src/Methcla/Audio/Engine.cpp @@ -125,8 +125,9 @@ namespace { std::string toLower(const std::string& s) { std::string result(s); - std::transform(result.begin(), result.end(), result.begin(), - [](unsigned char c) { return static_cast(std::tolower(c)); }); + std::transform( + result.begin(), result.end(), result.begin(), + [](unsigned char c) { return static_cast(std::tolower(c)); }); return result; } @@ -201,14 +202,14 @@ namespace { } METHCLA_C_LINKAGE size_t - methcla_api_world_block_size(const Methcla_World* world) + methcla_api_world_block_size(const Methcla_World* world) { assert(world && world->handle); return static_cast(world->handle)->blockSize(); } METHCLA_C_LINKAGE Methcla_Time - methcla_api_world_current_time(const Methcla_World* world) + methcla_api_world_current_time(const Methcla_World* world) { assert(world != nullptr); assert(world->handle != nullptr); diff --git a/src/Methcla/Audio/EngineImpl.cpp b/src/Methcla/Audio/EngineImpl.cpp index 9a0601d6..d14694d6 100644 --- a/src/Methcla/Audio/EngineImpl.cpp +++ b/src/Methcla/Audio/EngineImpl.cpp @@ -27,12 +27,12 @@ #include #include -#include -#include - #include #include +#include +#include + using namespace Methcla; using namespace Methcla::Audio; using Methcla::Memory::RTMemoryManager; @@ -140,8 +140,7 @@ static inline void addNodeToTarget(Node* target, Node* node, { switch (nodePlacement) { - case kMethcla_NodePlacementHeadOfGroup: - { + case kMethcla_NodePlacementHeadOfGroup: { Group* group = dynamic_cast(target); if (group != nullptr) { @@ -155,8 +154,7 @@ static inline void addNodeToTarget(Node* target, Node* node, } } break; - case kMethcla_NodePlacementTailOfGroup: - { + case kMethcla_NodePlacementTailOfGroup: { Group* group = dynamic_cast(target); if (group != nullptr) { @@ -566,7 +564,8 @@ void EnvironmentImpl::processMessage(Methcla_EngineLogFlags logFlags, }); } - synth->mapInput(static_cast(index), AudioBusId(busId), flags); + synth->mapInput(static_cast(index), + AudioBusId(busId), flags); } else if (msg == "/synth/map/output") { @@ -607,7 +606,8 @@ void EnvironmentImpl::processMessage(Methcla_EngineLogFlags logFlags, }); } - synth->mapOutput(static_cast(index), AudioBusId(busId), flags); + synth->mapOutput(static_cast(index), + AudioBusId(busId), flags); } else if (msg == "/synth/property/doneFlags/set") { diff --git a/src/Methcla/Audio/Group.cpp b/src/Methcla/Audio/Group.cpp index 6fe106be..0d27137e 100644 --- a/src/Methcla/Audio/Group.cpp +++ b/src/Methcla/Audio/Group.cpp @@ -19,13 +19,13 @@ using namespace Methcla::Audio; -#define METHCLA_ASSERT_NODE_IS_BLANK(node) \ - assert(node != nullptr); \ - assert(node->m_parent == nullptr); \ - assert(node->m_prev == nullptr); \ +#define METHCLA_ASSERT_NODE_IS_BLANK(node) \ + assert(node != nullptr); \ + assert(node->m_parent == nullptr); \ + assert(node->m_prev == nullptr); \ assert(node->m_next == nullptr); -#define METHCLA_ASSERT_NODE_IS_LINKED(node) \ +#define METHCLA_ASSERT_NODE_IS_LINKED(node) \ assert(m_first != nullptr); \ assert(m_last != nullptr); \ assert(node != nullptr); \ @@ -40,7 +40,10 @@ Group::Group(Environment& env, NodeId nodeId) , m_last(nullptr) {} -Group::~Group() { freeAll(); } +Group::~Group() +{ + freeAll(); +} Group* Group::construct(Environment& env, NodeId nodeId) { diff --git a/src/Methcla/Audio/Group.hpp b/src/Methcla/Audio/Group.hpp index e7262c67..9f6c5a8a 100644 --- a/src/Methcla/Audio/Group.hpp +++ b/src/Methcla/Audio/Group.hpp @@ -22,14 +22,29 @@ namespace Methcla { namespace Audio { class Group : public Node { public: - const Node* first() const { return m_first; } - Node* first() { return m_first; } - const Node* last() const { return m_last; } - Node* last() { return m_last; } + const Node* first() const + { + return m_first; + } + Node* first() + { + return m_first; + } + const Node* last() const + { + return m_last; + } + Node* last() + { + return m_last; + } static Group* construct(Environment& env, NodeId nodeId); - virtual bool isGroup() const override { return true; } + virtual bool isGroup() const override + { + return true; + } bool isEmpty() const; diff --git a/src/Methcla/Audio/IO/Driver.cpp b/src/Methcla/Audio/IO/Driver.cpp index f0411d9a..3c879824 100644 --- a/src/Methcla/Audio/IO/Driver.cpp +++ b/src/Methcla/Audio/IO/Driver.cpp @@ -3,9 +3,13 @@ using namespace Methcla::Audio::IO; using Methcla::Audio::sample_t; -Driver::Driver(Options) { setProcessCallback(nullptr, nullptr); } +Driver::Driver(Options) +{ + setProcessCallback(nullptr, nullptr); +} -Driver::~Driver() {} +Driver::~Driver() +{} void Driver::setProcessCallback(ProcessCallback callback, void* data) { @@ -21,4 +25,7 @@ void Driver::process(Methcla_Time currentTime, size_t numFrames, outputs); } -Methcla_Time Driver::currentTime() { return 0.; } +Methcla_Time Driver::currentTime() +{ + return 0.; +} diff --git a/src/Methcla/Audio/IO/DummyDriver.hpp b/src/Methcla/Audio/IO/DummyDriver.hpp index 55a6deee..89ccc1f4 100644 --- a/src/Methcla/Audio/IO/DummyDriver.hpp +++ b/src/Methcla/Audio/IO/DummyDriver.hpp @@ -33,10 +33,22 @@ namespace Methcla { namespace Audio { namespace IO { DummyDriver(Options options); virtual ~DummyDriver(); - virtual double sampleRate() const override { return m_sampleRate; } - virtual size_t numInputs() const override { return m_numInputs; } - virtual size_t numOutputs() const override { return m_numOutputs; } - virtual size_t bufferSize() const override { return m_bufferSize; } + virtual double sampleRate() const override + { + return m_sampleRate; + } + virtual size_t numInputs() const override + { + return m_numInputs; + } + virtual size_t numOutputs() const override + { + return m_numOutputs; + } + virtual size_t bufferSize() const override + { + return m_bufferSize; + } virtual void start() override; virtual void stop() override; diff --git a/src/Methcla/Audio/MultiChannelBuffer.hpp b/src/Methcla/Audio/MultiChannelBuffer.hpp index e1f55a94..2fcbac9c 100644 --- a/src/Methcla/Audio/MultiChannelBuffer.hpp +++ b/src/Methcla/Audio/MultiChannelBuffer.hpp @@ -31,17 +31,35 @@ namespace Methcla { namespace Audio { , m_data(makeBuffers(m_numChannels, m_numFrames)) {} - ~MultiChannelBuffer() { freeBuffers(m_numChannels, m_data); } + ~MultiChannelBuffer() + { + freeBuffers(m_numChannels, m_data); + } - size_t numChannels() const { return m_numChannels; } + size_t numChannels() const + { + return m_numChannels; + } - size_t numFrames() const { return m_numFrames; } + size_t numFrames() const + { + return m_numFrames; + } - size_t numSamples() const { return numChannels() * numFrames(); } + size_t numSamples() const + { + return numChannels() * numFrames(); + } - Methcla_AudioSample* const* data() { return m_data; } + Methcla_AudioSample* const* data() + { + return m_data; + } - const Methcla_AudioSample* const* data() const { return m_data; } + const Methcla_AudioSample* const* data() const + { + return m_data; + } void deinterleave(const Methcla_AudioSample* src, size_t srcFrames) { @@ -114,5 +132,5 @@ namespace Methcla { namespace Audio { Methcla_AudioSample** m_data; }; -}} // namespace Methcla::Audio +}} // namespace Methcla::Audio #endif // METHCLA_AUDIO_MULTICHANNELBUFFER_HPP_INCLUDED diff --git a/src/Methcla/Audio/Node.cpp b/src/Methcla/Audio/Node.cpp index 8c337521..6f80f9b8 100644 --- a/src/Methcla/Audio/Node.cpp +++ b/src/Methcla/Audio/Node.cpp @@ -63,7 +63,8 @@ void Node::free() pEnv->rtMem().free(this); } -void Node::doProcess(size_t) {} +void Node::doProcess(size_t) +{} inline static void setDoneFreeSelf(Node* node) { diff --git a/src/Methcla/Audio/Resource.hpp b/src/Methcla/Audio/Resource.hpp index 11536178..914ac499 100644 --- a/src/Methcla/Audio/Resource.hpp +++ b/src/Methcla/Audio/Resource.hpp @@ -51,7 +51,10 @@ namespace Methcla { namespace Audio { return m_refs; } - inline void retain() { m_refs++; } + inline void retain() + { + m_refs++; + } inline void release() { @@ -62,9 +65,13 @@ namespace Methcla { namespace Audio { } protected: - virtual ~Reference() {} + virtual ~Reference() + {} - virtual void free() { delete this; } + virtual void free() + { + delete this; + } private: int m_refs; @@ -82,11 +89,20 @@ namespace Methcla { namespace Audio { {} /// Access environment. - const Environment& env() const { return m_env; } - Environment& env() { return m_env; } + const Environment& env() const + { + return m_env; + } + Environment& env() + { + return m_env; + } /// Return unique id. - Id id() const { return m_id; } + Id id() const + { + return m_id; + } private: Environment& m_env; @@ -110,7 +126,10 @@ namespace Methcla { namespace Audio { ResourceMap(const ResourceMap&) = delete; ResourceMap& operator=(const ResourceMap&) = delete; - size_t size() const { return m_elems.size(); } + size_t size() const + { + return m_elems.size(); + } bool contains(Id id) const { @@ -142,7 +161,10 @@ namespace Methcla { namespace Audio { } } - void remove(Id id) { m_elems[id] = nullptr; } + void remove(Id id) + { + m_elems[id] = nullptr; + } Pointer lookup(Id id) { diff --git a/src/Methcla/Audio/Synth.cpp b/src/Methcla/Audio/Synth.cpp index 67225c51..9205fb9d 100644 --- a/src/Methcla/Audio/Synth.cpp +++ b/src/Methcla/Audio/Synth.cpp @@ -52,12 +52,10 @@ Synth::Synth(Environment& env, NodeId nodeId, const SynthDef& synthDef, m_audioBuffers = kBufferAlignment.align(audioBuffers); // Validate alignment - assert( - Alignment::isAligned(std::alignment_of::value, - (uintptr_t)m_audioInputConnections)); - assert( - Alignment::isAligned(std::alignment_of::value, - (uintptr_t)m_audioOutputConnections)); + assert(Alignment::isAligned(std::alignment_of::value, + (uintptr_t)m_audioInputConnections)); + assert(Alignment::isAligned(std::alignment_of::value, + (uintptr_t)m_audioOutputConnections)); assert(Alignment::isAligned(std::alignment_of::value, (uintptr_t)m_controlBuffers)); assert(kBufferAlignment.isAligned(m_audioBuffers)); @@ -176,15 +174,15 @@ void Synth::connectPorts(const Methcla_SynthOptions* synthOptions, Methcla_PortCount controlOutputIndex = 0; Methcla_PortCount audioInputIndex = 0; Methcla_PortCount audioOutputIndex = 0; - for (Methcla_PortCount i = 0; m_synthDef.portDescriptor(synthOptions, i, &port); i++) + for (Methcla_PortCount i = 0; + m_synthDef.portDescriptor(synthOptions, i, &port); i++) { switch (port.type) { case kMethcla_ControlPort: switch (port.direction) { - case kMethcla_Input: - { + case kMethcla_Input: { // Initialize with control value m_controlBuffers[controlInputIndex] = controls.next(); @@ -193,8 +191,7 @@ void Synth::connectPorts(const Methcla_SynthOptions* synthOptions, controlInputIndex++; }; break; - case kMethcla_Output: - { + case kMethcla_Output: { sample_t* buffer = &m_controlBuffers[numControlInputs() + controlOutputIndex]; @@ -207,8 +204,7 @@ void Synth::connectPorts(const Methcla_SynthOptions* synthOptions, case kMethcla_AudioPort: switch (port.direction) { - case kMethcla_Input: - { + case kMethcla_Input: { new (&m_audioInputConnections[audioInputIndex]) AudioInputConnection(audioInputIndex); sample_t* buffer = m_audioBuffers + @@ -218,8 +214,7 @@ void Synth::connectPorts(const Methcla_SynthOptions* synthOptions, audioInputIndex++; }; break; - case kMethcla_Output: - { + case kMethcla_Output: { new (&m_audioOutputConnections[audioOutputIndex]) AudioOutputConnection(audioOutputIndex); sample_t* buffer = @@ -361,7 +356,8 @@ void Synth::doProcess(size_t numFrames) } else if (m_flags.state == kStateActivating) { - const size_t sampleOffset = static_cast(std::floor(m_sampleOffset)); + const size_t sampleOffset = + static_cast(std::floor(m_sampleOffset)); assert(m_sampleOffset < (double)numFrames && sampleOffset < numFrames); const size_t remainingFrames = numFrames - sampleOffset; diff --git a/src/Methcla/Audio/Synth.hpp b/src/Methcla/Audio/Synth.hpp index 85df1faf..a9714a15 100644 --- a/src/Methcla/Audio/Synth.hpp +++ b/src/Methcla/Audio/Synth.hpp @@ -55,7 +55,10 @@ namespace Methcla { namespace Audio { , m_bus(nullptr) {} - Methcla_PortCount index() const { return m_index; } + Methcla_PortCount index() const + { + return m_index; + } bool connect(Bus* bus, Methcla_BusMappingFlags flags) { @@ -70,8 +73,14 @@ namespace Methcla { namespace Audio { } protected: - Methcla_BusMappingFlags flags() const { return m_flags; } - Bus* bus() { return m_bus; } + Methcla_BusMappingFlags flags() const + { + return m_flags; + } + Bus* bus() + { + return m_bus; + } }; class AudioInputConnection : public Connection @@ -177,20 +186,32 @@ namespace Methcla { namespace Audio { // Convert Methcla_Synth to Synth. static Synth* fromSynth(Methcla_Synth* synth); - virtual bool isSynth() const override { return true; } + virtual bool isSynth() const override + { + return true; + } //* Return this synth's SynthDef. - const SynthDef& synthDef() const { return m_synthDef; } + const SynthDef& synthDef() const + { + return m_synthDef; + } //* Return number of audio inputs. - Methcla_PortCount numAudioInputs() const { return m_numAudioInputs; } + Methcla_PortCount numAudioInputs() const + { + return m_numAudioInputs; + } //* Map input to bus. void mapInput(Methcla_PortCount input, const AudioBusId& busId, Methcla_BusMappingFlags flags); //* Return number of audio outputs. - Methcla_PortCount numAudioOutputs() const { return m_numAudioOutputs; } + Methcla_PortCount numAudioOutputs() const + { + return m_numAudioOutputs; + } //* Map output to bus. void mapOutput(Methcla_PortCount output, const AudioBusId& busId, @@ -227,7 +248,10 @@ namespace Methcla { namespace Audio { void activate(double sampleOffset = 0.); /// Sample offset for sample accurate synth scheduling. - float sampleOffset() const { return static_cast(m_sampleOffset); } + float sampleOffset() const + { + return static_cast(m_sampleOffset); + } private: enum State diff --git a/src/Methcla/Audio/SynthDef.cpp b/src/Methcla/Audio/SynthDef.cpp index 02a3e374..11dc2f77 100644 --- a/src/Methcla/Audio/SynthDef.cpp +++ b/src/Methcla/Audio/SynthDef.cpp @@ -64,8 +64,8 @@ SynthDef::configure(OSCPP::Server::ArgStream options) const } bool SynthDef::portDescriptor(const Methcla_SynthOptions* options, - Methcla_PortCount index, - Methcla_PortDescriptor* port) const + Methcla_PortCount index, + Methcla_PortDescriptor* port) const { return m_descriptor->port_descriptor(options, index, port); } diff --git a/src/Methcla/Audio/SynthDef.hpp b/src/Methcla/Audio/SynthDef.hpp index 92c74b9f..88c77b08 100644 --- a/src/Methcla/Audio/SynthDef.hpp +++ b/src/Methcla/Audio/SynthDef.hpp @@ -58,8 +58,8 @@ namespace Methcla { namespace Audio { //* Return port descriptor at index. bool portDescriptor(const Methcla_SynthOptions* options, - Methcla_PortCount index, - Methcla_PortDescriptor* port) const; + Methcla_PortCount index, + Methcla_PortDescriptor* port) const; void construct(Methcla_World* world, const Methcla_SynthOptions* options, diff --git a/src/Methcla/Exception.hpp b/src/Methcla/Exception.hpp index eeeae280..6cd067be 100644 --- a/src/Methcla/Exception.hpp +++ b/src/Methcla/Exception.hpp @@ -36,7 +36,10 @@ namespace Methcla { , m_message(message) {} - Methcla_ErrorCode errorCode() const noexcept { return m_code; } + Methcla_ErrorCode errorCode() const noexcept + { + return m_code; + } const char* errorMessage() const noexcept { @@ -44,7 +47,10 @@ namespace Methcla { : m_message.c_str(); } - const char* what() const noexcept override { return errorMessage(); } + const char* what() const noexcept override + { + return errorMessage(); + } }; } // namespace Methcla diff --git a/src/Methcla/Faust.hpp b/src/Methcla/Faust.hpp index fd653399..f3050068 100644 --- a/src/Methcla/Faust.hpp +++ b/src/Methcla/Faust.hpp @@ -30,7 +30,8 @@ namespace Faust { class UI { public: - virtual ~UI() {} + virtual ~UI() + {} // -- widget's layouts @@ -68,7 +69,8 @@ namespace Faust { // -- metadata declarations - virtual void declare(float*, const char*, const char*) {} + virtual void declare(float*, const char*, const char*) + {} }; class dsp @@ -77,7 +79,8 @@ namespace Faust { int fSamplingFreq; public: - virtual ~dsp() {} + virtual ~dsp() + {} virtual int getNumInputs() = 0; virtual int getNumOutputs() = 0; diff --git a/src/Methcla/Memory.cpp b/src/Methcla/Memory.cpp index 4cb90296..b8829d67 100644 --- a/src/Methcla/Memory.cpp +++ b/src/Methcla/Memory.cpp @@ -36,7 +36,10 @@ void* Methcla::Memory::alloc(size_t size) return ptr; } -void Methcla::Memory::free(void* ptr) noexcept { std::free(ptr); } +void Methcla::Memory::free(void* ptr) noexcept +{ + std::free(ptr); +} void* Methcla::Memory::allocAligned(Alignment align, size_t size) { diff --git a/src/Methcla/Platform.hpp b/src/Methcla/Platform.hpp index b7fafebe..bc4bc3bd 100644 --- a/src/Methcla/Platform.hpp +++ b/src/Methcla/Platform.hpp @@ -24,4 +24,4 @@ namespace Methcla { namespace Platform { Audio::IO::Driver* defaultAudioDriver(Audio::IO::Driver::Options options); }} // namespace Methcla::Platform -#endif // METHCLA_PLATFORM_HPP_INCLUDED \ No newline at end of file +#endif // METHCLA_PLATFORM_HPP_INCLUDED diff --git a/src/Methcla/Plugin/LoaderPosix.cpp b/src/Methcla/Plugin/LoaderPosix.cpp index 83b58387..2b8e8554 100644 --- a/src/Methcla/Plugin/LoaderPosix.cpp +++ b/src/Methcla/Plugin/LoaderPosix.cpp @@ -86,8 +86,7 @@ namespace { if (splitExtension(path) == kPluginExtension) { clear_dlerror(); - void* handle = - dlopen(path.c_str(), RTLD_NOW | RTLD_LOCAL); + void* handle = dlopen(path.c_str(), RTLD_NOW | RTLD_LOCAL); if (handle == nullptr) { check_dlerror(); diff --git a/src/Methcla/Plugin/Manager.cpp b/src/Methcla/Plugin/Manager.cpp index 42dafb0b..0758eacd 100644 --- a/src/Methcla/Plugin/Manager.cpp +++ b/src/Methcla/Plugin/Manager.cpp @@ -1,9 +1,9 @@ #include "Methcla/Plugin/Manager.hpp" -#include - #include +#include + using namespace Methcla::Plugin; Manager::Library::Library(Methcla_Library* lib, diff --git a/src/Methcla/Utility/MessageQueue.hpp b/src/Methcla/Utility/MessageQueue.hpp index 4a8a36c1..0fbb6e3f 100644 --- a/src/Methcla/Utility/MessageQueue.hpp +++ b/src/Methcla/Utility/MessageQueue.hpp @@ -53,12 +53,15 @@ namespace Methcla { namespace Utility { throw std::runtime_error("Message queue overflow"); } - bool next(T& msg) override { return m_queue.pop(msg); } + bool next(T& msg) override + { + return m_queue.pop(msg); + } private: typedef methcla_boost::lockfree::spsc_queue Queue; - Queue m_queue; - std::mutex m_mutex; + Queue m_queue; + std::mutex m_mutex; }; template class Transport @@ -68,7 +71,8 @@ namespace Methcla { namespace Utility { : m_queue(queueSize) , m_needsLock(needsLock) {} - virtual ~Transport() {} + virtual ~Transport() + {} Transport(const Transport&) = delete; Transport& operator=(const Transport&) = delete; @@ -98,11 +102,20 @@ namespace Methcla { namespace Utility { protected: typedef methcla_boost::lockfree::spsc_queue Queue; - Queue& queue() { return m_queue; } + Queue& queue() + { + return m_queue; + } - bool needsLock() const { return m_needsLock; } + bool needsLock() const + { + return m_needsLock; + } - std::mutex& mutex() { return m_mutex; } + std::mutex& mutex() + { + return m_mutex; + } void sendCommand(const Command& cmd) { @@ -172,7 +185,10 @@ namespace Methcla { namespace Utility { } } - bool dequeue(Command& cmd) override { return this->queue().pop(cmd); } + bool dequeue(Command& cmd) override + { + return this->queue().pop(cmd); + } }; template class Worker : public WorkerInterface @@ -187,21 +203,34 @@ namespace Methcla { namespace Utility { Worker(const Worker&) = delete; Worker& operator=(const Worker&) = delete; - size_t maxCapacity() const { return m_queueSize; } + size_t maxCapacity() const + { + return m_queueSize; + } - void sendToWorker(const Command& cmd) override { m_toWorker.send(cmd); } + void sendToWorker(const Command& cmd) override + { + m_toWorker.send(cmd); + } void sendFromWorker(const Command& cmd) override { m_fromWorker.send(cmd); } - void perform() override { m_fromWorker.performAll(); } + void perform() override + { + m_fromWorker.performAll(); + } protected: - void work() { m_toWorker.performOne(); } + void work() + { + m_toWorker.performOne(); + } - virtual void signalWorker() {} + virtual void signalWorker() + {} private: size_t m_queueSize; @@ -222,7 +251,10 @@ namespace Methcla { namespace Utility { } } - ~WorkerThread() { stop(); } + ~WorkerThread() + { + stop(); + } void stop() override { @@ -262,7 +294,10 @@ namespace Methcla { namespace Utility { } } - virtual void signalWorker() override { m_sem.post(); } + virtual void signalWorker() override + { + m_sem.post(); + } private: Semaphore m_sem; diff --git a/src/Methcla/Utility/MessageQueueInterface.hpp b/src/Methcla/Utility/MessageQueueInterface.hpp index 8a34eb14..1887068d 100644 --- a/src/Methcla/Utility/MessageQueueInterface.hpp +++ b/src/Methcla/Utility/MessageQueueInterface.hpp @@ -19,7 +19,8 @@ namespace Methcla { namespace Utility { template class MessageQueueInterface { public: - virtual ~MessageQueueInterface() {} + virtual ~MessageQueueInterface() + {} virtual void send(const Message& msg) = 0; virtual bool next(Message& msg) = 0; }; diff --git a/src/Methcla/Utility/Semaphore.cpp b/src/Methcla/Utility/Semaphore.cpp index 5dd52799..28365d25 100644 --- a/src/Methcla/Utility/Semaphore.cpp +++ b/src/Methcla/Utility/Semaphore.cpp @@ -63,7 +63,10 @@ Semaphore::~Semaphore() delete m_impl; } -void Semaphore::post() { zix_sem_post(m_impl); } +void Semaphore::post() +{ + zix_sem_post(m_impl); +} void Semaphore::wait() { @@ -71,7 +74,10 @@ void Semaphore::wait() check(status); } -bool Semaphore::tryWait() { return zix_sem_try_wait(m_impl); } +bool Semaphore::tryWait() +{ + return zix_sem_try_wait(m_impl); +} #else // !METHCLA_USE_CV_SEMAPHORE # include @@ -132,13 +138,25 @@ namespace Methcla { namespace Utility { m_impl = new detail::SemaphoreImpl(initial); } - Semaphore::~Semaphore() { delete m_impl; } + Semaphore::~Semaphore() + { + delete m_impl; + } - void Semaphore::post() { m_impl->post(); } + void Semaphore::post() + { + m_impl->post(); + } - void Semaphore::wait() { m_impl->wait(); } + void Semaphore::wait() + { + m_impl->wait(); + } - bool Semaphore::tryWait() { return m_impl->tryWait(); } + bool Semaphore::tryWait() + { + return m_impl->tryWait(); + } }} // namespace Methcla::Utility diff --git a/src/Methcla/Utility/WorkerInterface.hpp b/src/Methcla/Utility/WorkerInterface.hpp index 74fca5d9..9f1c57c9 100644 --- a/src/Methcla/Utility/WorkerInterface.hpp +++ b/src/Methcla/Utility/WorkerInterface.hpp @@ -19,9 +19,10 @@ namespace Methcla { namespace Utility { template class WorkerInterface { public: - virtual ~WorkerInterface() {} + virtual ~WorkerInterface() + {} - virtual void stop(){}; + virtual void stop() {}; virtual void sendToWorker(const Command& cmd) = 0; virtual void sendFromWorker(const Command& cmd) = 0; diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 4e21b4ae..173c9680 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -1,66 +1,45 @@ if(METHCLA_BUILD_TESTS) -# ============================================================================= -# Plugin directories + # ============================================================================= + # Plugin directories -set(PLUGIN_DIRECTORIES - "\"${CMAKE_BINARY_DIR}/plugins\"" - "\"${CMAKE_CURRENT_BINARY_DIR}/plugins\"") -string(REPLACE ";" "," PLUGIN_DIRECTORIES "${PLUGIN_DIRECTORIES}") + set(PLUGIN_DIRECTORIES "\"${CMAKE_BINARY_DIR}/plugins\"" + "\"${CMAKE_CURRENT_BINARY_DIR}/plugins\"") + string(REPLACE ";" "," PLUGIN_DIRECTORIES "${PLUGIN_DIRECTORIES}") -configure_file(config.cpp.in config.cpp) + configure_file(config.cpp.in config.cpp) -target_compile_options(gtest PRIVATE - -Wno-missing-field-initializers - -Wno-unused-const-variable -) + target_compile_options(gtest PRIVATE -Wno-missing-field-initializers + -Wno-unused-const-variable) -# ============================================================================= -# methcla_tests + # ============================================================================= + # methcla_tests -add_executable(methcla_tests - test_runner_console.cpp - methcla_tests.cpp -) + add_executable(methcla_tests test_runner_console.cpp methcla_tests.cpp) -target_include_directories(methcla_tests PRIVATE - ../src -) -target_include_directories(methcla_tests SYSTEM PRIVATE - ../external_libraries/boost -) + target_include_directories(methcla_tests PRIVATE ../src) + target_include_directories(methcla_tests SYSTEM + PRIVATE ../external_libraries/boost) -target_link_libraries(methcla_tests PRIVATE - GTest::gtest - methcla -) -methcla_target_warnings(methcla_tests) + target_link_libraries(methcla_tests PRIVATE GTest::gtest methcla) + methcla_target_warnings(methcla_tests) -add_test(methcla_tests methcla_tests) + add_test(methcla_tests methcla_tests) -# ============================================================================= -# methcla_engine_tests + # ============================================================================= + # methcla_engine_tests -add_executable(methcla_engine_tests - test_runner_console.cpp - methcla_engine_tests.cpp - ${CMAKE_CURRENT_BINARY_DIR}/config.cpp -) + add_executable( + methcla_engine_tests test_runner_console.cpp methcla_engine_tests.cpp + ${CMAKE_CURRENT_BINARY_DIR}/config.cpp) -target_include_directories(methcla_engine_tests PRIVATE - . - ../src -) -target_include_directories(methcla_engine_tests SYSTEM PRIVATE - ../external_libraries/boost -) + target_include_directories(methcla_engine_tests PRIVATE . ../src) + target_include_directories(methcla_engine_tests SYSTEM + PRIVATE ../external_libraries/boost) -target_link_libraries(methcla_engine_tests PRIVATE - GTest::gtest - methcla -) -methcla_target_warnings(methcla_engine_tests) + target_link_libraries(methcla_engine_tests PRIVATE GTest::gtest methcla) + methcla_target_warnings(methcla_engine_tests) -add_test(methcla_engine_tests methcla_engine_tests) + add_test(methcla_engine_tests methcla_engine_tests) endif() # METHCLA_BUILD_TESTS diff --git a/tests/android/AndroidManifest.xml b/tests/android/AndroidManifest.xml index 983231aa..418c436c 100644 --- a/tests/android/AndroidManifest.xml +++ b/tests/android/AndroidManifest.xml @@ -18,4 +18,4 @@ - + diff --git a/tests/android/ant.properties b/tests/android/ant.properties index b0971e89..73031c7a 100644 --- a/tests/android/ant.properties +++ b/tests/android/ant.properties @@ -14,4 +14,3 @@ # 'key.store' for the location of your keystore and # 'key.alias' for the name of the key to use. # The password will be asked during the build when you use the 'release' target. - diff --git a/tests/consumers/add_subdirectory/main.c b/tests/consumers/add_subdirectory/main.c index 4bf7b24d..21559a4f 100644 --- a/tests/consumers/add_subdirectory/main.c +++ b/tests/consumers/add_subdirectory/main.c @@ -1,7 +1,9 @@ #include + #include -int main(void) { +int main(void) +{ printf("methcla version: %s\n", methcla_version()); return 0; } diff --git a/tests/consumers/find_package/main.c b/tests/consumers/find_package/main.c index 4bf7b24d..21559a4f 100644 --- a/tests/consumers/find_package/main.c +++ b/tests/consumers/find_package/main.c @@ -1,7 +1,9 @@ #include + #include -int main(void) { +int main(void) +{ printf("methcla version: %s\n", methcla_version()); return 0; } diff --git a/tests/methcla_tests.cpp b/tests/methcla_tests.cpp index 137afe5d..8127a7fa 100644 --- a/tests/methcla_tests.cpp +++ b/tests/methcla_tests.cpp @@ -47,7 +47,8 @@ std::string Methcla::Tests::outputFile(const std::string& name) namespace test_Methcla_Utility_Worker { struct Command { - void perform() {} + void perform() + {} }; }; // namespace test_Methcla_Utility_Worker diff --git a/tests/methcla_tests.hpp b/tests/methcla_tests.hpp index c90cb8cb..a5a65122 100644 --- a/tests/methcla_tests.hpp +++ b/tests/methcla_tests.hpp @@ -31,11 +31,11 @@ #include "gtest/gtest.h" -#define PRINTF(...) \ - do \ - { \ - printf("[ ] "); \ - printf(__VA_ARGS__); \ +#define PRINTF(...) \ + do \ + { \ + printf("[ ] "); \ + printf(__VA_ARGS__); \ } while (0) #define TEST_COUT Methcla::Tests::TestCout() @@ -121,4 +121,4 @@ namespace Methcla { namespace Tests { } }} // namespace Methcla::Tests -#endif // METHCLA_TESTS_HPP_INCLUDED \ No newline at end of file +#endif // METHCLA_TESTS_HPP_INCLUDED diff --git a/tests/plugins/test-support.cpp b/tests/plugins/test-support.cpp index 1d36d14d..c9f663dd 100644 --- a/tests/plugins/test-support.cpp +++ b/tests/plugins/test-support.cpp @@ -33,7 +33,10 @@ namespace { class TestStatsOptions { - void addStat(TestStatsType type) { m_stats[m_numStats++] = type; } + void addStat(TestStatsType type) + { + m_stats[m_numStats++] = type; + } public: TestStatsOptions(OSCPP::Server::ArgStream args) @@ -68,7 +71,10 @@ namespace { public: typedef size_t Port; - static constexpr size_t numPorts() { return 2; } + static constexpr size_t numPorts() + { + return 2; + } static Methcla_PortDescriptor descriptor(Port port) { @@ -104,9 +110,15 @@ namespace { } } - TestStatsType type() const { return kTestStat_MaxAbsAmp; } + TestStatsType type() const + { + return kTestStat_MaxAbsAmp; + } - float result() const { return m_result; } + float result() const + { + return m_result; + } }; class TestStats @@ -215,8 +227,8 @@ namespace { }; // namespace METHCLA_EXPORT const Methcla_Library* - methcla_plugins_test_support(const Methcla_Host* host, - const char* /* bundlePath */) +methcla_plugins_test_support(const Methcla_Host* host, + const char* /* bundlePath */) { kTestStatsDef(host, METHCLA_PLUGINS_TEST_STATS_URI); return &library; diff --git a/tests/plugins/test-support.h b/tests/plugins/test-support.h index 55fb4e58..b7552c65 100644 --- a/tests/plugins/test-support.h +++ b/tests/plugins/test-support.h @@ -20,7 +20,7 @@ #include METHCLA_EXPORT const Methcla_Library* - methcla_plugins_test_support(const Methcla_Host*, const char*); +methcla_plugins_test_support(const Methcla_Host*, const char*); #define METHCLA_PLUGINS_TEST_STATS_URI METHCLA_PLUGINS_URI "/test/stats" #define METHCLA_TEST_STATS_OUTPUT_PREFIX "{TEST_STATS}" diff --git a/tests/pnacl/example.js b/tests/pnacl/example.js deleted file mode 100644 index 85f965f2..00000000 --- a/tests/pnacl/example.js +++ /dev/null @@ -1,42 +0,0 @@ -// From common.js - -// Listen for the DOM content to be loaded. This event is fired when -// parsing of the page's document has finished. -document.addEventListener('DOMContentLoaded', function() { - var body = document.body; - var listenerDiv = document.getElementById('listener'); - listenerDiv.addEventListener('load', moduleDidLoad, true); - listenerDiv.addEventListener('message', handleMessage, true); - listenerDiv.addEventListener('crash', handleCrash, true); -}) - -var naclModule; - -function updateStatus(opt_message) { - if (opt_message) { - statusText = opt_message; - } - var statusField = document.getElementById('statusField'); - if (statusField) { - statusField.innerHTML = statusText; - } -} - -function moduleDidLoad() { - naclModule = document.getElementById('nacl_module'); - updateStatus('RUNNING'); - naclModule.postMessage('yo'); -} - -function handleMessage(message) { - var logEl = document.getElementById('log'); - logEl.textContent += message.data; -} - -function handleCrash(event) { - if (naclModule.exitStatus == -1) { - updateStatus('CRASHED'); - } else { - updateStatus('EXITED [' + naclModule.exitStatus + ']'); - } -} diff --git a/tests/pnacl/icon128.png b/tests/pnacl/icon128.png deleted file mode 100644 index 4d7b8efd..00000000 Binary files a/tests/pnacl/icon128.png and /dev/null differ diff --git a/tests/pnacl/icon16.png b/tests/pnacl/icon16.png deleted file mode 100644 index 363ddf8e..00000000 Binary files a/tests/pnacl/icon16.png and /dev/null differ diff --git a/tests/pnacl/index.html b/tests/pnacl/index.html deleted file mode 100644 index 14c52c1c..00000000 --- a/tests/pnacl/index.html +++ /dev/null @@ -1,24 +0,0 @@ - - - - - Methcla PNaCl test - - - - -
- Testfest! -
- -
- -
- -
-
-
-
diff --git a/tests/pnacl/manifest.json b/tests/pnacl/manifest.json
deleted file mode 100644
index 0c64ad03..00000000
--- a/tests/pnacl/manifest.json
+++ /dev/null
@@ -1,15 +0,0 @@
-{
-  "name": "Methcla Tests",
-  "manifest_version": 2,
-  "description": "Methcla tests for PNaCl",
-  "version": "0.1",
-  "icons": {
-    "16": "icon16.png",
-    "128": "icon128.png"
-  },
-  "app": {
-    "launch": {
-      "local_path": "index.html"
-    }
-  }
-}
diff --git a/tools/dumposcfile/dumposcfile.cpp b/tools/dumposcfile/dumposcfile.cpp
index 07f3d04d..c831b4b8 100644
--- a/tools/dumposcfile/dumposcfile.cpp
+++ b/tools/dumposcfile/dumposcfile.cpp
@@ -33,7 +33,8 @@ int main(int argc, const char* const* argv)
             int32_t rawSize;
             if (fread(&rawSize, sizeof(rawSize), 1, file) != 1)
                 break;
-            const size_t size = static_cast(OSCPP::convert32(rawSize));
+            const size_t size = static_cast(
+                OSCPP::convert32(rawSize));
             if (buffer.size() < size)
                 buffer.resize(size);
             const size_t n = fread(buffer.data(), 1, size, file);