Skip to content
Snippets Groups Projects

Compare revisions

Changes are shown as if the source revision was being merged into the target revision. Learn more about comparing revisions.

Source

Select target project
No results found
Select Git revision
  • main
  • blm_dev_chan
  • release/1.4.0
  • widgets_draw
  • return_of_melodic_demo
  • task_cleanup
  • mixer2
  • dx/fb-save-restore
  • dx/dldldld
  • fpletz/flake
  • dx/jacksense-headset-mic-only
  • release/1.3.0
  • fil3s-limit-filesize
  • allow-reloading-sunmenu
  • wifi-json-error-handling
  • app_text_viewer
  • shoegaze-fps
  • media_has_video_has_audio
  • fil3s-media
  • more-accurate-battery
  • sector_size_512
  • led_fix_fix
  • w1f1-in-sim
  • py_only_update_fps_overlay_when_changing
  • gr33nhouse-improvements
  • restore_blit
  • store_delta_ms_and_ins_as_class_members
  • always-have-a-wifi-instance
  • smaller_gradient_lut
  • pippin/more-accurate-battery
  • dx/hint-hint
  • pippin/ctx_sprite_sheet_support
  • 89-apps-should-be-able-to-specify-if-they-want-wifi-to-be-disabled-when-entering-them
  • q3k/render-to-texture
  • pippin/tune_ctx_config_update_from_upstream
  • pippin/tcp_redirect_hack
  • pippin/make_empty_drawlists_skip_render_and_blit
  • moon2_migrate_apps
  • release/1.2.0
  • release/1.1.1
  • release/1.1.0
  • sec/auto-nick
  • rahix/flow3rseeds
  • sec/blinky
  • pippin/uhm_flash_access_bust
  • release/1.0.0
  • pressable_bugfix
  • schneider/application-remove-name
  • anon/webflasher
  • pippin/display-python-errors-on-display
  • schneider/recovery
  • schneider/bhi581
  • anon/update-sim
  • ci-1690580595
  • iggy/stemming_merge
  • schneider/factory_test
  • iggy/stemming
  • ch3/bl00mbox_docs
  • audio_input
  • anon/gpndemo
  • wip-docs
  • sdkconfig-spiram-tinyusb
  • history-rewrite
  • wip-tinyusb
  • audio_io
  • 9Rmain
  • icon-flower
  • dev_p4-iggy-rebased
  • moon2_demo_temp
  • scope_hack
  • raw_captouch_new
  • dev_p4
  • raw_captouch_old
  • q3k/doom-poc
  • dev_p4-iggy
  • events
  • micropython_api
  • uctx-wip
  • rev4_micropython
  • main+schneider
  • v1.0.0
  • v1.0.0+rc1
  • v1.0.0+rc2
  • v1.0.0+rc3
  • v1.0.0+rc4
  • v1.0.0+rc5
  • v1.0.0+rc6
  • v1.1.0
  • v1.1.0+rc1
  • v1.1.1
  • v1.2.0
  • v1.2.0+rc1
  • v1.3.0
  • v1.4.0
94 results

Target

Select target project
No results found
Select Git revision
  • main
  • rahix/big-flow3r
  • fpletz/flake
  • sampler_fix
  • pippin/media_framework
  • release/1.2.0
  • release/1.1.1
  • release/1.1.0
  • sec/auto-nick
  • rahix/flow3rseeds
  • compressor
  • sec/blinky
  • pippin/uhm_flash_access_bust
  • release/1.0.0
  • fm_fix2
  • fm_fix
  • pippin/make_empty_drawlists_skip_render_and_blit
  • pressable_bugfix
  • moon2_gay_drums
  • moon2_applications
  • schneider/application-remove-name
  • anon/webflasher
  • pippin/display-python-errors-on-display
  • bl00mbox
  • bl00mbox_old
  • schneider/recovery
  • schneider/bhi581
  • anon/update-sim
  • ci-1690580595
  • iggy/stemming_merge
  • schneider/factory_test
  • iggy/stemming
  • ch3/bl00mbox_docs
  • audio_input
  • anon/gpndemo
  • wip-docs
  • sdkconfig-spiram-tinyusb
  • history-rewrite
  • wip-tinyusb
  • audio_io
  • 9Rmain
  • icon-flower
  • dev_p4-iggy-rebased
  • moon2_demo_temp
  • scope_hack
  • raw_captouch_new
  • dev_p4
  • raw_captouch_old
  • q3k/doom-poc
  • dev_p4-iggy
  • events
  • micropython_api
  • uctx-wip
  • rev4_micropython
  • main+schneider
  • v1.0.0
  • v1.0.0+rc1
  • v1.0.0+rc2
  • v1.0.0+rc3
  • v1.0.0+rc4
  • v1.0.0+rc5
  • v1.0.0+rc6
  • v1.1.0
  • v1.1.0+rc1
  • v1.1.1
  • v1.2.0
  • v1.2.0+rc1
67 results
Show changes
1000 files
+ 3354
0
Compare changes
  • Side-by-side
  • Inline

Files

.clang-format

0 → 100644
+5 −0
Original line number Diff line number Diff line
---
BasedOnStyle: Google
IndentWidth: 4
IncludeBlocks: Preserve
Cpp11BracedListStyle: false

.clang-tidy

0 → 100644
+3 −0
Original line number Diff line number Diff line
# Don't care about deprecated APIs (noisy) and about memcpy/strcpy (we'll fix
# that later).
Checks: '-clang-analyzer-security.insecureAPI.DeprecatedOrUnsafeBufferHandling,-clang-diagnostic-deprecated-declarations'

.gitignore

0 → 100644
+28 −0
Original line number Diff line number Diff line
# esp-idf
sdkconfig.old
sdkconfig
dependencies.lock
build

.sdkconfig.defaults.generated

# micropython
__pycache__

# editor crud
.vscode
*swp
*~

# Python
.venv
/venv/

# sphinx
docs/_build/

/tools/mypy.sh

# bl00mbox docs
components/bl00mbox/docs/
components/bl00mbox/public/

.gitlab-ci.yml

0 → 100644
+93 −0
Original line number Diff line number Diff line
stages:
  - check
  - build
  - deploy

variables:
  GIT_SUBMODULE_STRATEGY: recursive
  GIT_DEPTH: 0

default:
  # built via:
  #     docker load < $(nix-build nix/docker-image.nix)
  image: registry.gitlab.com/flow3r-badge/flow3r-build:238576xsg79mjr2bkqg106qisvd3b5q9

clang-tidy:
  stage: check
  script:
    - "bash tools/clang-tidy.sh"
    - "python3 tools/codequal-report.py clang-tidy warnings.txt > cqual.json"
  artifacts:
    when: always
    reports:
      codequality: cqual.json

format:
  stage: check
  script:
    - "git clean -fdx"
    - "bash tools/format.sh"
    - "[ -z \"$(git status --porcelain)\" ] || (echo 'Differences found, please run tools/format.sh.' && git diff HEAD && exit 1)"

build:
  stage: build
  script:
    - idf.py -g c23 build size
  artifacts:
    expose_as: 'firmware'
    paths: ['build/flow3r.bin']
    expire_in: 5 hours

build_recovery:
  stage: build
  script:
    - cd recovery
    - idf.py build size
  artifacts:
    expose_as: 'Recovery'
    paths: ['recovery/build/flow3r-recovery.bin', 'recovery/build/partition_table/partition-table.bin', 'recovery/build/bootloader/bootloader.bin']
    expire_in: 5 hours

simulate:
  stage: build
  script:
    - python3 sim/run.py --screenshot
  artifacts:
    expose_as: 'Simulator Screenshot'
    paths: ['flow3r.png']
    expire_in: 5 hours

pages:
  stage: deploy
  rules:
    - if: $CI_COMMIT_BRANCH == "main"
  script:
    - git tag | xargs git tag -d
    - git checkout origin/main
    - git checkout -b dev
    - git branch --all
    - git branch --all | sed -e 's/..//' | grep '^remotes/origin/release/' | while read b; do git checkout -b "v${b#remotes/origin/release/}" "$b"; done
    - git checkout dev
    - git branch
    - mkdir public
    - cd docs
    - make versionedhtml
    - cp -r _build/$(git branch --sort=version:refname | tail -n1 | sed -e 's/..//')/* _build/
    - python redirects.py
    - cp -r _build/* ../public/
    - find ../public/
  artifacts:
    paths: ['public']
    expire_in: 1d

dist:
  stage: deploy
  variables:
    # Force a full clone to make version machinery work.
    GIT_STRATEGY: clone
  rules:
    - if: $CI_COMMIT_TAG
  script:
    - bash tools/dist.sh
  artifacts:
    paths: ['dist']

.gitmodules

0 → 100644
+6 −0
Original line number Diff line number Diff line
[submodule "lib/berkeley-db-1.xx"]
	path = components/micropython/vendor/lib/berkeley-db-1.xx
	url = https://github.com/pfalcon/berkeley-db-1.xx
[submodule "lib/micropython-lib"]
	path = components/micropython/vendor/lib/micropython-lib
	url = https://github.com/micropython/micropython-lib.git

CHANGELOG.md

0 → 100644
+273 −0
Original line number Diff line number Diff line
# Changelog

All notable changes to this project will be documented in this file.

The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).

## [Unreleased]

## [1.4.0] - 2024-12-24
### Summary

- documentation reworked and expanded
- primary context menu: can be opened at any time to view help texts, open the audio mixer or force-exit an application.
- help viewer: applications can provide context-sensitive help texts to make it easier to figure them out and reduce
  the load on appilcation writers to explain everything on a small screen.
- audio mixer: set levels of bl00mbox channels and mute/unmute them. Muted channels don't use CPU.
- secondary context menu: can be opened in an application menu to delete apps, set them as autostart or mark them as
  favorite to sort them to the top of menus
- new preloaded apps: violin, wobbler, mp3 player
- major rework of captouch driver features
- added `st3m.ui.widgets` module for easier app integration of user inputs (for example, captouch gestures)
- bl00mbox can now run channel-specific micropython callbacks whenever the channel is rendered, allowing
  for much more flexible backgrounded music applications

### Added
- system: unregistered apps are marked as "new"
- system: new category "Demos" for things that focus on being technical examples rather than being use case oriented
- gdb: micropython REPL available while debugging
- micropython: added `indent` keyword to `json.dumps`/`json.dump`
- apps: added overrides for OS button
- apps: added `get_help()` method to provide context sensitive help texts to users
- settings: Touch UI (default off) activates preview for captouch menu navigation
- media: support for more (most) mp3 tag types
- gr33nhouse: sort by application type
- captouch: no more silent captouch calibration, driver saves persistent calibration file and guides user through manual
  calibration when none is found.
- captouch: petals can be turned off run with reduced output to increase data rate
- captouch: unfiltered data log is accessible
- captouch: added `PetalLog` helper class for data processing
- bl00mbox: added .delete() method for various objects, added destructors for better garbabe collection behavior
- bl00mbox: added RMS volume collection option and provide volume normalization guidelines in flo3r docs

### Changed
- settings: "Enable WiFi on Boot" option is now "Always-On Wi-Fi" (but is functionally identical), should help reduce confusion about Wi-Fi turning off automatically
- captouch: normalized positional output in new `.pos`/`.raw_pos` attributes, deprecated old `.position` API
- captouch: normalized raw capacitance output in new `.raw_cap` attribute, deprecated old `.pressure` API
- captouch: removed all abstractions that indicate petal pads without replacement,
  i.e. `InputController.petals[x].ccw` or `InputState.petals[x].raw`

### Fixed
- updat3r: Improved version comparison logic, making the "you are up to date :)" logic work
- captouch: petal 5 fully functional
- bl00mbox: a whole lot of bugs and performance issues (but not all :P)

## [1.3.0] - 2023-11-26
### Summary
- Wifi connection UI
- Media framework
- SD card works reliably
- Performance improvements
- Backend improvements
- Wider micropython API
- Improved preloaded applications
- ...and many bugfixes!

### Added
- Added the `Audio Passthrough` app for toggling audio passthrough through
  line-in/mic to speaker or lineout.
- Added the `w1f1` app for managing wifi access to Settings, incorporates
  an in-progress cap-touch multi-tap keyboard (`k3yboard`).
- Added the `Scalar` app in `Music` category for playing scales.
- Added the `Mandelbrot` app, which illustrates how one can do direct
  framebuffer access and control 8bpp palettized modes from python.
- Added configuration of audio adjustments and startup dB level to `settings.json`.
- Added configuration of wifi credentials + hostname via `settings.json`
- Added support for apps to set wifi state automatically (configurable in
  settings: `Let apps change WiFi`)
- Added task profiler which prints over serial (configurable in
  settings: `Debug: ftop`)
- Added an error screen to the `Nick` app when `nick.json` is invalid.
- Added `urequests` and `uos` support in the simulator.
- Added audio/video media framework, and `Wurzelitzer` app as a small jukebox
  frontend - currently supporting mp3 audio, mpeg1 video, GIF and protracker
  .mod files.
- Added exporting of built firmwares as part of CI.
- Added basic implementation of `os.statvfs()` to fetch full/available
  disk space on flash and SD.
- Added `set_position` and `scroll_to` methods to `ScrollController`
- graphics: sprite sheet support for `ctx.image()`
- graphics: `ctx.parse()` for parsing SVG-path-data/ctx-protocol.
- graphics: 1,2,4,8,16,24 and 32 bits-per-pixel graphics modes.
- graphics: direct framebuffer access.
- graphics: palette setting in 1,2,4 and 8bpp graphics modes.
- graphics: flags for 2x 3x and 4x pixel doubling, low-latency and direct-ctx modes.
- graphics: experimental smart redraw mode
- graphics: clipped and composited overlay buffer
- graphics: allow a graphics state depth of up to 10 (`ctx.save()` `ctx.restore()`)
- graphics: virtual framebuffer with scrolling
- battery: Main menu shows a charge percentage estimate based on real battery characterization
- Added basic media playback in the `fil3s` app.
- Added a delete button to `fil3s`/Files app to allow for deleting files,
  folders and apps on-device.
- Added new menu categories, `Media` and `Games`, and made category handling more robust
  to correctly handle introducing new categories in the future.
- Added configuration UI for audio, appearance and graphics settings.
- Added configurable LED patterns for the main menu.
- Added "restore defaults" option in the settings menu.
- Added wah modulation in `Otamatone`.
- Added several API functions for `ViewManager` to make complex view handling in apps
  easier and robust.
- Added firmware update app, `updat3r`.
- Added storage information in `About` app.
- Added audio equalization for built-in speakers.
- Added a function to retrieve scope data for manual drawing/processing.
- Added I2C scanner app.
- Added sensor demo app.
- Added `CONFIG_DEBUG_GDB_ENABLED` flag for easy debugging over USB JTAG.
- Added saving/restoring state to several apps.
- Added variable sequence length support in `gay drums`.

### Changed
- Changed the st3m\_tar logic to only update files on flash after an update
  if they've been changed, greatly improving start times after an update.
- Flashing flow3r through idf.py now automatically restarts it.
- Switched the REPL/fatal/disk restart button to the OS shoulder button (right
  shoulder button, unless swapped in settings).
- Improved performance of the `gr33nhouse` app list by not rendering hidden
  entries and scrolling ones too long to fit on screen.
- Changed the audio adjustment logic, and added support for holding down the
  shoulder to keep increasing/decreasing level.
- Improved download reliability of the `gr33nhouse` app by adding chunked
  downloads, some `gc.collect()` calls, progress bar and an error screen.
- Settings are now automatically loaded and saved when entering and leaving
  the settings page.
- Moved the `Clouds` app to the `Badge` menu and updated it to use IMU data.
- Added a more sane commandline interface to the simulator.
- More stub functions for the simulator.
- Improved performance of system menus by not rendering hidden entries.
- Added visualization of state, instead of an audio scope in UI of `harmonic
  demo` and `melodic demo`.
- The system provided scope is now always stroked.
- Improved BPM tap accuracy in `gay drums`.
- Some shell code rewritten to avoid the expensive calls `ctx.start_group()` and
  `ctx.end_group()`.
- Overlay graphics gets rendered to a separate framebuffer, of which a clipped rectangle
  is composited during scan-out. The python overlay code has been adapted to keep track
  of which parts of overlay need refresh.
- Slightly lower AA quality; for a 3x performance boost in the
  worst-case scanline rasterization code path.
- The entry section in `flow3r.toml` can now be omitted if the Application
  class is called `App`.
- disabled support for compositing group API in ctx, where used global\_alpha on
  its own did was responsible for it seeming to work.
- Split the `settings.py` file into two, creating `settings_menu.py` to hold
  UI-related code and allow `settings` to be used import loops without
  in many cases.
- When running apps through REPL mode (with `mpremote` etc), multi-view apps
  are now properly handled and don't restart whenever OS shoulder is pressed.
- A multitude of built-in apps now scroll names to fit the screen.
- Apps are now sorted and deduplicated by display name, not by folder name.
- Improved handedness in buttons.
- `harmonic demo` turned into a fully-featured `chord organ`
- `menu` key in `flow3r.toml` has been replaced with `category`. The old key can still
  be used to maintain backwards compatibility with older firmwares.
- Backported recent improvements for micropython's garbage collection to make it faster.
- `shoegaze` can now use chords configured in `chord organ`.
- Changed the priority of additional threads spawned by micropython to be equal to its
  main thread's priority.
- Apps that require Wi-Fi connection can directly take the user to Wi-Fi settings.
- Changed the default app installation directory on flash to `/flash/apps`.
- `gr33nhouse` now installs apps on SD card if available.
- Increased the frequency of LED animations.
- Changed the way LED colors are blended when using slew rates lower than 255 to be
  more in line with color perception.
- Rearranged system menu.
- Made system indicator icons bigger.
- Removed CCCamp's Wi-Fi settings from the default config.
- Made InputState and parts of InputController lazily evaluated.
- bl00mbox: allow circular signal dependencies
- bl00mbox: several plugins and patches deprecated and replaced with updated
  versions, see https://gitlab.com/moon2embeddedaudio/bl00mbox/-/blob/main/README.md

### Fixed
- Fixed `tiny sampler` keeping the microphone active after app exit.
- Fixed missing `include/` dir on builds on Darwin.
- Fixed the `time` module in the simulator being broken for apps trying to use it.
- Fixed wrong petal ordering in the simulator.
- Fixed simulator not exiting when closed.
- Fixed `Comic Mono` missing in the simulator.
- Fixed initialization orientation of display and transform initialization for
  ctx contexts, (this enables arbitrary transformations to images and gradients.)
- Fixed broken anti-aliasing for compressed side of curved strokes.
- Fixed cleanup at exit for firmware apps
- Fixed sampler start bug in bl00mbox
- Fixed reset of graphics subsystem upon entering REPL / using mpremote.
- Fixed multitude of issues with transition animations.
- Fixed lost captouch and button presses when they're shorter than a think cycle.
- Fixed `ScrollController`'s handling of high delta values.
- Fixed many crashes in `fil3s` app.
- Fixed a crash in `CapScrollController`.
- Fixed gamma LUT setting for LEDs.
- Fixed bl00mbox channels leaking on micropython's soft reboot.
- Fixed importing bl00mbox's fake stub in the simulator.
- Performance fixes for bl00mbox.
- Fixed troubles with deleting files on some SD cards (like the bundled one).
- Fixed the default I2C1 pins in micropython's I2C interface.
- Fixed large files being truncated when installing apps via `gr33nhouse`.
- Fixed LED color handling in the simulator.
- Fixed flickering .down property of Pressable when going through REPEATED state.


## [1.2.0] - 2023-08-18
### Added
- Added a WiFi status indicator icon.
- Added a battery status indicator icon.
- Added support for loading apps from `/sd/apps` and `/flash/apps`.
- Added an error screen when apps fail to start.
- Added Python/st3m API to access battery charge status.
- Added the ability to always hide icons (*System**Settings**Show Icons*).

### Fixed
- File descriptor leak on app load.  This would lead to the OS crashing when
  too many apps are installed.


## [1.1.1] - 2023-08-17
### Fixed
- Crash on WiFi startup


## [1.1.0] - 2023-08-17

### Added
- Added _Comic Mono_ font.
- Added a setting for automatically connecting to Camp WiFi.
- Added a *System**Get Apps* App for downloading apps directly from <https://flow3r.garden/apps/>.
- Added `ApplicationContext.bundle_path` so apps can find out what directory
  they live in.  This should be used for loading app assets from the correct
  path.
- Added TLS support for MicroPython.
- Added modules for `.tar.gz` extraction.
- Added `aioble` module (Bluetooth Low Energy).
- Added line-in support to bl00mbox.
- Added pronoun support in the Nick app.
- Added color options in the Nick app.
- Added IMU-based rotation in the Nick app.

### Changed
- `ctx.get_font_name()` now raises an exception for unknown fonts.
- Raised max concurrent texture limit to 32.

### Fixed
- Fixed PNG without alpha and JPEG support by enabling `CTX_FORMAT_RGB8`.
- Fixed image cache eviction by introducing a ctx frameclock.
- Fixed incorrect merging of settings dicts in `st3m.settings`.
- Fixed some USB problems.
- Fixed sound filenames not working when they start with `/flash/` or `/sd/`.
- Fixed syntax errors in `flow3r.toml` crashing the menu.


## [1.0.0] - 2023-08-13

Initial Release


[unreleased]: https://git.flow3r.garden/flow3r/flow3r-firmware/-/compare/v1.4.0...main
[1.4.0]: https://git.flow3r.garden/flow3r/flow3r-firmware/-/compare/v1.3.0...v1.4.0
[1.3.0]: https://git.flow3r.garden/flow3r/flow3r-firmware/-/compare/v1.2.0...v1.3.0
[1.2.0]: https://git.flow3r.garden/flow3r/flow3r-firmware/-/compare/v1.1.1...v1.2.0
[1.1.1]: https://git.flow3r.garden/flow3r/flow3r-firmware/-/compare/v1.1.0...v1.1.1
[1.1.0]: https://git.flow3r.garden/flow3r/flow3r-firmware/-/compare/v1.0.0...v1.1.0
[1.0.0]: https://git.flow3r.garden/flow3r/flow3r-firmware/-/tags/v1.0.0

CMakeLists.txt

0 → 100644
+22 −0
Original line number Diff line number Diff line
cmake_minimum_required(VERSION 3.12)

set(IDF_TARGET esp32s3)

include($ENV{IDF_PATH}/tools/cmake/project.cmake)

project(flow3r)

# Make `1.1` literals into single-point precision float instead of double
# precision. Also warn any time something gets promoted to a double. We
# generally don't want doubles, doubles on ESP32 bad.
idf_component_get_property(st3m_lib st3m COMPONENT_LIB)
idf_component_get_property(flow3r_bsp_lib flow3r_bsp COMPONENT_LIB)
idf_component_get_property(bl00mbox_lib bl00mbox COMPONENT_LIB)
if("${CMAKE_CXX_COMPILER_ID}" STREQUAL "Clang")
    target_compile_options(${st3m_lib} PRIVATE -cl-single-precision-constant -Wdouble-promotion)
    target_compile_options(${flow3r_bsp_lib} PRIVATE -cl-single-precision-constant -Wdouble-promotion)
    target_compile_options(${bl00mbox_lib} PRIVATE -Wno-error=unknown-pragmas)
else()
    target_compile_options(${st3m_lib} PRIVATE -fsingle-precision-constant -Wdouble-promotion)
    target_compile_options(${flow3r_bsp_lib} PRIVATE -fsingle-precision-constant -Wdouble-promotion)
endif()

COPYING

0 → 100644
+0 −0

File added.

Preview size limit exceeded, changes collapsed.

COPYING.LESSER

0 → 100644
+165 −0
Original line number Diff line number Diff line
                   GNU LESSER GENERAL PUBLIC LICENSE
                       Version 3, 29 June 2007

 Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
 Everyone is permitted to copy and distribute verbatim copies
 of this license document, but changing it is not allowed.


  This version of the GNU Lesser General Public License incorporates
the terms and conditions of version 3 of the GNU General Public
License, supplemented by the additional permissions listed below.

  0. Additional Definitions.

  As used herein, "this License" refers to version 3 of the GNU Lesser
General Public License, and the "GNU GPL" refers to version 3 of the GNU
General Public License.

  "The Library" refers to a covered work governed by this License,
other than an Application or a Combined Work as defined below.

  An "Application" is any work that makes use of an interface provided
by the Library, but which is not otherwise based on the Library.
Defining a subclass of a class defined by the Library is deemed a mode
of using an interface provided by the Library.

  A "Combined Work" is a work produced by combining or linking an
Application with the Library.  The particular version of the Library
with which the Combined Work was made is also called the "Linked
Version".

  The "Minimal Corresponding Source" for a Combined Work means the
Corresponding Source for the Combined Work, excluding any source code
for portions of the Combined Work that, considered in isolation, are
based on the Application, and not on the Linked Version.

  The "Corresponding Application Code" for a Combined Work means the
object code and/or source code for the Application, including any data
and utility programs needed for reproducing the Combined Work from the
Application, but excluding the System Libraries of the Combined Work.

  1. Exception to Section 3 of the GNU GPL.

  You may convey a covered work under sections 3 and 4 of this License
without being bound by section 3 of the GNU GPL.

  2. Conveying Modified Versions.

  If you modify a copy of the Library, and, in your modifications, a
facility refers to a function or data to be supplied by an Application
that uses the facility (other than as an argument passed when the
facility is invoked), then you may convey a copy of the modified
version:

   a) under this License, provided that you make a good faith effort to
   ensure that, in the event an Application does not supply the
   function or data, the facility still operates, and performs
   whatever part of its purpose remains meaningful, or

   b) under the GNU GPL, with none of the additional permissions of
   this License applicable to that copy.

  3. Object Code Incorporating Material from Library Header Files.

  The object code form of an Application may incorporate material from
a header file that is part of the Library.  You may convey such object
code under terms of your choice, provided that, if the incorporated
material is not limited to numerical parameters, data structure
layouts and accessors, or small macros, inline functions and templates
(ten or fewer lines in length), you do both of the following:

   a) Give prominent notice with each copy of the object code that the
   Library is used in it and that the Library and its use are
   covered by this License.

   b) Accompany the object code with a copy of the GNU GPL and this license
   document.

  4. Combined Works.

  You may convey a Combined Work under terms of your choice that,
taken together, effectively do not restrict modification of the
portions of the Library contained in the Combined Work and reverse
engineering for debugging such modifications, if you also do each of
the following:

   a) Give prominent notice with each copy of the Combined Work that
   the Library is used in it and that the Library and its use are
   covered by this License.

   b) Accompany the Combined Work with a copy of the GNU GPL and this license
   document.

   c) For a Combined Work that displays copyright notices during
   execution, include the copyright notice for the Library among
   these notices, as well as a reference directing the user to the
   copies of the GNU GPL and this license document.

   d) Do one of the following:

       0) Convey the Minimal Corresponding Source under the terms of this
       License, and the Corresponding Application Code in a form
       suitable for, and under terms that permit, the user to
       recombine or relink the Application with a modified version of
       the Linked Version to produce a modified Combined Work, in the
       manner specified by section 6 of the GNU GPL for conveying
       Corresponding Source.

       1) Use a suitable shared library mechanism for linking with the
       Library.  A suitable mechanism is one that (a) uses at run time
       a copy of the Library already present on the user's computer
       system, and (b) will operate properly with a modified version
       of the Library that is interface-compatible with the Linked
       Version.

   e) Provide Installation Information, but only if you would otherwise
   be required to provide such information under section 6 of the
   GNU GPL, and only to the extent that such information is
   necessary to install and execute a modified version of the
   Combined Work produced by recombining or relinking the
   Application with a modified version of the Linked Version. (If
   you use option 4d0, the Installation Information must accompany
   the Minimal Corresponding Source and Corresponding Application
   Code. If you use option 4d1, you must provide the Installation
   Information in the manner specified by section 6 of the GNU GPL
   for conveying Corresponding Source.)

  5. Combined Libraries.

  You may place library facilities that are a work based on the
Library side by side in a single library together with other library
facilities that are not Applications and are not covered by this
License, and convey such a combined library under terms of your
choice, if you do both of the following:

   a) Accompany the combined library with a copy of the same work based
   on the Library, uncombined with any other library facilities,
   conveyed under the terms of this License.

   b) Give prominent notice with the combined library that part of it
   is a work based on the Library, and explaining where to find the
   accompanying uncombined form of the same work.

  6. Revised Versions of the GNU Lesser General Public License.

  The Free Software Foundation may publish revised and/or new versions
of the GNU Lesser General Public License from time to time. Such new
versions will be similar in spirit to the present version, but may
differ in detail to address new problems or concerns.

  Each version is given a distinguishing version number. If the
Library as you received it specifies that a certain numbered version
of the GNU Lesser General Public License "or any later version"
applies to it, you have the option of following the terms and
conditions either of that published version or of any later version
published by the Free Software Foundation. If the Library as you
received it does not specify a version number of the GNU Lesser
General Public License, you may choose any version of the GNU Lesser
General Public License ever published by the Free Software Foundation.

  If the Library as you received it specifies that a proxy can decide
whether future versions of the GNU Lesser General Public License shall
apply, that proxy's public statement of acceptance of any version is
permanent authorization for you to choose that version for the
Library.

README.md

0 → 100644
+12 −0
Original line number Diff line number Diff line
# flow3r badge

See https://docs.flow3r.garden/badge/firmware-development.html for a firmware development guide.

## License
All original source code in this repository is Copyright (C) 2023 Flow3r Badge Contributors. This source code is licensed under the GNU Lesser General Public License Version 3.0 as described in the file COPYING.

This program is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License Version 3.0 as published by the Free Software Foundation.

This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public License Version 3.0 along with this program.  If not, see <https://www.gnu.org/licenses/>.
+8 −0
Original line number Diff line number Diff line
idf_component_register(
    SRCS
        audio_mod.c
    INCLUDE_DIRS
        .
        ../ctx
        ../st3m
)
+140 −0
Original line number Diff line number Diff line
#ifndef __clang__
#pragma GCC optimize("O2")
#endif

#include <fcntl.h>
#include <st3m_audio.h>
#include <st3m_media.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

#include "ctx.h"

#define POCKETMOD_IMPLEMENTATION
#include "pocketmod.h"

typedef struct {
    st3m_media control;
    pocketmod_context pocketmod;
    uint8_t *data;
    size_t size;
    char *path;
    float scroll_pos;
} mod_state;

static void mod_draw(st3m_media *media, Ctx *ctx) {
    mod_state *self = (void *)media;

    ctx_rectangle(ctx, -120, -120, 240, 240);
    ctx_gray(ctx, 0);
    ctx_fill(ctx);
    // ctx_arc(ctx, 0, 0, 10, 10);
    ctx_rgb(ctx, 1.0, 1.0, 1.0);
    ctx_font_size(ctx, 20);
    char buf[100];
    sprintf(buf, "pat:%i/%i line:%i", self->pocketmod.pattern,
            self->pocketmod.num_patterns, self->pocketmod.line);
    ctx_text_align(ctx, CTX_TEXT_ALIGN_CENTER);
    ctx_move_to(ctx, 0, -20);
    ctx_text(ctx, buf);
    ctx_fill(ctx);

    ctx_font_size(ctx, 14);
    int xpos = 0;
    int str_width = ctx_text_width(ctx, self->path);
    if (str_width > 220) {
        xpos = ctx_sinf(self->scroll_pos) * (str_width - 220) / 2;
    }
    ctx_move_to(ctx, xpos, 14);
    ctx_gray(ctx, 0.6);
    ctx_text(ctx, self->path);
}

static void mod_think(st3m_media *media, float ms_elapsed) {
    mod_state *self = (void *)media;
    if (self->control.paused) return;

    if (self->control.seek == 0) {
        pocketmod_init(&self->pocketmod, self->data, self->size, 48000);
        self->control.seek = -1;
    }

    int samples_needed = (ms_elapsed / 1000.0) * 48000;
    if (samples_needed > 1000) samples_needed = 1000;

    float rendered[samples_needed * 2];
    int rend = pocketmod_render(&self->pocketmod, rendered, sizeof(rendered));
    st3m_pcm_queue_float(48000, 2, rend / (sizeof(float) * 2), rendered);

    if (self->control.duration == 0) {
        self->control.duration = self->pocketmod.num_patterns + 1;
    }
    if (self->pocketmod.pattern >= self->control.duration)
        self->control.duration = self->pocketmod.pattern + 1;
    self->control.position = self->pocketmod.pattern;
    if (self->pocketmod.loop_count)
        self->control.duration = self->control.position;

    self->scroll_pos += ms_elapsed / 1000.0;
}

static void mod_destroy(st3m_media *media) {
    mod_state *self = (void *)media;
    if (self->data) free(self->data);
    if (self->path) free(self->path);
    free(self);
}

static int file_get_contents(const char *path, uint8_t **contents,
                             size_t *length) {
    FILE *file;
    long size;
    long remaining;
    uint8_t *buffer;
    file = fopen(path, "rb");
    if (!file) {
        return -1;
    }
    fseek(file, 0, SEEK_END);
    size = remaining = ftell(file);

    if (length) {
        *length = size;
    }
    rewind(file);
    buffer = malloc(size + 2);
    if (!buffer) {
        fclose(file);
        return -1;
    }
    remaining -= fread(buffer, 1, remaining, file);
    if (remaining) {
        fclose(file);
        free(buffer);
        return -1;
    }
    fclose(file);
    *contents = (unsigned char *)buffer;
    buffer[size] = 0;
    return 0;
}

st3m_media *st3m_media_load_mod(const char *path) {
    mod_state *self = (mod_state *)malloc(sizeof(mod_state));
    memset(self, 0, sizeof(mod_state));
    self->control.draw = mod_draw;
    self->control.think = mod_think;
    self->control.destroy = mod_destroy;
    self->control.has_audio = true;
    file_get_contents(path, &self->data, &self->size);
    if (!self->data ||
        !pocketmod_init(&self->pocketmod, self->data, self->size, 48000)) {
        if (self->data) free(self->data);
        free(self);
        return NULL;
    }
    self->path = strdup(path);
    self->scroll_pos = 0;
    return (st3m_media *)self;
}
+8 −0
Original line number Diff line number Diff line
idf_component_register(
    SRCS
        audio_mp3.c
    INCLUDE_DIRS
        .
        ../ctx
        ../st3m
)
+117 −0
Original line number Diff line number Diff line
CC0 1.0 Universal

Statement of Purpose

The laws of most jurisdictions throughout the world automatically confer
exclusive Copyright and Related Rights (defined below) upon the creator and
subsequent owner(s) (each and all, an "owner") of an original work of
authorship and/or a database (each, a "Work").

Certain owners wish to permanently relinquish those rights to a Work for the
purpose of contributing to a commons of creative, cultural and scientific
works ("Commons") that the public can reliably and without fear of later
claims of infringement build upon, modify, incorporate in other works, reuse
and redistribute as freely as possible in any form whatsoever and for any
purposes, including without limitation commercial purposes. These owners may
contribute to the Commons to promote the ideal of a free culture and the
further production of creative, cultural and scientific works, or to gain
reputation or greater distribution for their Work in part through the use and
efforts of others.

For these and/or other purposes and motivations, and without any expectation
of additional consideration or compensation, the person associating CC0 with a
Work (the "Affirmer"), to the extent that he or she is an owner of Copyright
and Related Rights in the Work, voluntarily elects to apply CC0 to the Work
and publicly distribute the Work under its terms, with knowledge of his or her
Copyright and Related Rights in the Work and the meaning and intended legal
effect of CC0 on those rights.

1. Copyright and Related Rights. A Work made available under CC0 may be
protected by copyright and related or neighboring rights ("Copyright and
Related Rights"). Copyright and Related Rights include, but are not limited
to, the following:

  i. the right to reproduce, adapt, distribute, perform, display, communicate,
  and translate a Work;

  ii. moral rights retained by the original author(s) and/or performer(s);

  iii. publicity and privacy rights pertaining to a person's image or likeness
  depicted in a Work;

  iv. rights protecting against unfair competition in regards to a Work,
  subject to the limitations in paragraph 4(a), below;

  v. rights protecting the extraction, dissemination, use and reuse of data in
  a Work;

  vi. database rights (such as those arising under Directive 96/9/EC of the
  European Parliament and of the Council of 11 March 1996 on the legal
  protection of databases, and under any national implementation thereof,
  including any amended or successor version of such directive); and

  vii. other similar, equivalent or corresponding rights throughout the world
  based on applicable law or treaty, and any national implementations thereof.

2. Waiver. To the greatest extent permitted by, but not in contravention of,
applicable law, Affirmer hereby overtly, fully, permanently, irrevocably and
unconditionally waives, abandons, and surrenders all of Affirmer's Copyright
and Related Rights and associated claims and causes of action, whether now
known or unknown (including existing as well as future claims and causes of
action), in the Work (i) in all territories worldwide, (ii) for the maximum
duration provided by applicable law or treaty (including future time
extensions), (iii) in any current or future medium and for any number of
copies, and (iv) for any purpose whatsoever, including without limitation
commercial, advertising or promotional purposes (the "Waiver"). Affirmer makes
the Waiver for the benefit of each member of the public at large and to the
detriment of Affirmer's heirs and successors, fully intending that such Waiver
shall not be subject to revocation, rescission, cancellation, termination, or
any other legal or equitable action to disrupt the quiet enjoyment of the Work
by the public as contemplated by Affirmer's express Statement of Purpose.

3. Public License Fallback. Should any part of the Waiver for any reason be
judged legally invalid or ineffective under applicable law, then the Waiver
shall be preserved to the maximum extent permitted taking into account
Affirmer's express Statement of Purpose. In addition, to the extent the Waiver
is so judged Affirmer hereby grants to each affected person a royalty-free,
non transferable, non sublicensable, non exclusive, irrevocable and
unconditional license to exercise Affirmer's Copyright and Related Rights in
the Work (i) in all territories worldwide, (ii) for the maximum duration
provided by applicable law or treaty (including future time extensions), (iii)
in any current or future medium and for any number of copies, and (iv) for any
purpose whatsoever, including without limitation commercial, advertising or
promotional purposes (the "License"). The License shall be deemed effective as
of the date CC0 was applied by Affirmer to the Work. Should any part of the
License for any reason be judged legally invalid or ineffective under
applicable law, such partial invalidity or ineffectiveness shall not
invalidate the remainder of the License, and in such case Affirmer hereby
affirms that he or she will not (i) exercise any of his or her remaining
Copyright and Related Rights in the Work or (ii) assert any associated claims
and causes of action with respect to the Work, in either case contrary to
Affirmer's express Statement of Purpose.

4. Limitations and Disclaimers.

  a. No trademark or patent rights held by Affirmer are waived, abandoned,
  surrendered, licensed or otherwise affected by this document.

  b. Affirmer offers the Work as-is and makes no representations or warranties
  of any kind concerning the Work, express, implied, statutory or otherwise,
  including without limitation warranties of title, merchantability, fitness
  for a particular purpose, non infringement, or the absence of latent or
  other defects, accuracy, or the present or absence of errors, whether or not
  discoverable, all to the greatest extent permissible under applicable law.

  c. Affirmer disclaims responsibility for clearing rights of other persons
  that may apply to the Work or any use thereof, including without limitation
  any person's Copyright and Related Rights in the Work. Further, Affirmer
  disclaims responsibility for obtaining any necessary consents, permissions
  or other rights required for any use of the Work.

  d. Affirmer understands and acknowledges that Creative Commons is not a
  party to this document and has no duty or obligation with respect to this
  CC0 or use of the Work.

For more information, please see
<http://creativecommons.org/publicdomain/zero/1.0/>
+568 −0
Original line number Diff line number Diff line
#ifndef __clang__
#pragma GCC optimize("O2")
#endif

#include <fcntl.h>
#include <st3m_audio.h>
#include <st3m_media.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

#include "lwip/igmp.h"
#include "lwip/ip4.h"
#include "lwip/netdb.h"
#include "lwip/sockets.h"

#include "ctx.h"

#define MINIMP3_NONSTANDARD_BUT_LOGICAL
#define MINIMP3_NO_SIMD
#define MINIMP3_IMPLEMENTATION
#include "minimp3.h"

typedef struct {
    st3m_media control;
    mp3dec_t mp3d;
    char *path;
    char *artist;
    char *title;
    int year;
    int started;
    int samplerate;
    int channels;
    uint8_t *data;
    size_t size;
    size_t count;

    int pos;
    int offset;
    int buffer_size;

    int file_size;
    FILE *file;

    int socket;

    int in_buffering;
    float scroll_pos;
} mp3_state;

static int has_data(mp3_state *mp3) {
    if (mp3->file) return 1;
    fd_set rfds;
    struct timeval tv = { 0, 0 };
    FD_ZERO(&rfds);
    FD_SET(mp3->socket, &rfds);
    if (select(mp3->socket + 1, &rfds, NULL, NULL, &tv) == 1)
        return FD_ISSET(mp3->socket, &rfds);
    return 0;
}

static void mp3_fetch_data(mp3_state *mp3) {
    if (mp3->pos) {
        memmove(mp3->data, &mp3->data[mp3->pos], mp3->count - mp3->pos);
        mp3->offset += mp3->pos;
        mp3->count -= mp3->pos;
        mp3->pos = 0;
    }

    // if incoming data-buffer falls below 16kb - do a full buffer fill
    if (!mp3->file && (mp3->count < 16 * 1024)) {
        mp3->in_buffering = 1;
    }

    if ((mp3->size - mp3->count > 0) && has_data(mp3)) {
        int desire_bytes = (mp3->size - mp3->count);
        if (desire_bytes > 2048) desire_bytes = 2048;
        if (desire_bytes) {
            int read_bytes;
            if (mp3->file)
                read_bytes =
                    fread(mp3->data + mp3->count, 1, desire_bytes, mp3->file);
            else
                read_bytes =
                    read(mp3->socket, mp3->data + mp3->count, desire_bytes);
            mp3->count += read_bytes;
        }
    }
}

static char *mp3_get_string(st3m_media *media, const char *key) {
    mp3_state *self = (void *)media;
    if (strcmp(key, "artist") == 0) {
        return strdup(self->artist);
    } else if (strcmp(key, "title") == 0) {
        return strdup(self->title);
    }
    return NULL;
}

static void mp3_draw(st3m_media *media, Ctx *ctx) {
    mp3_state *self = (void *)media;

    ctx_rectangle(ctx, -120, -120, 240, 240);
    ctx_gray(ctx, 0);
    ctx_fill(ctx);
    ctx_rgb(ctx, 1.0, 1.0, 1.0);
    ctx_rectangle(ctx, -120, 0, 240, 1);
    ctx_rectangle(ctx, -120 + self->offset * 240.0 / self->file_size, -32, 2,
                  64);
    ctx_fill(ctx);
    ctx_font_size(ctx, 24);
    ctx_text_align(ctx, CTX_TEXT_ALIGN_CENTER);

    int xpos = 0;
    int str_width = ctx_text_width(ctx, self->artist);
    if (str_width > 200) {
        xpos = ctx_sinf(self->scroll_pos) * (str_width - 200) / 2;
    }
    ctx_move_to(ctx, xpos, -40);
    ctx_text(ctx, self->artist);

    str_width = ctx_text_width(ctx, self->title);
    xpos = 0;
    if (str_width > 200) {
        xpos = ctx_sinf(self->scroll_pos) * (str_width - 200) / 2;
    }
    ctx_move_to(ctx, xpos, 64);
    ctx_text(ctx, self->title);

    ctx_font_size(ctx, 14);
    str_width = ctx_text_width(ctx, self->path);
    xpos = 0;
    if (str_width > 220) {
        xpos = ctx_sinf(self->scroll_pos) * (str_width - 220) / 2;
    }
    ctx_move_to(ctx, xpos, 14);
    ctx_gray(ctx, 0.6);
    ctx_text(ctx, self->path);

    if (!self->file) {
        ctx_rectangle(ctx, -100, 65, self->count * 200.0 / self->size, 55);
        if (self->in_buffering)
            ctx_rgba(ctx, 0.8, 0.2, 0.0, 1.0);
        else
            ctx_gray(ctx, 0.2);
        ctx_fill(ctx);
    }
}

static void mp3_think(st3m_media *media, float ms_elapsed) {
    mp3_state *self = (void *)media;

    if (self->file && self->control.seek >= 0) {
        if (self->control.seek > 1.0) {
            self->control.seek = 1.0;
        }
        float seek = self->control.seek * self->control.duration;
        fseek(self->file, seek, SEEK_SET);
        self->offset = seek;
        self->pos = 0;
        self->count = 0;
        self->control.time = 0;
        self->control.position = self->offset;
        self->control.seek = -1;
        mp3dec_init(&self->mp3d);
    }

    mp3_fetch_data(self);

    self->scroll_pos += ms_elapsed / 1000.0;

    if (self->in_buffering) {
        if (self->size - self->count > 0) return;
        self->in_buffering = 0;
    }

    if (self->control.paused) return;

    if (self->file) {
        self->control.position = self->offset;
        if (self->offset + 512 >= self->file_size)
            self->control.position = self->file_size;
    }

    if (!self->started) {
        self->started = 1;
        mp3_think(media, 100);
    }
    int samples_needed = (((st3m_pcm_queue_length() - st3m_pcm_queued()) / 2)) /
                         48000.0 * self->samplerate;

    int samples;
    mp3dec_frame_info_t info = {
        0,
    };
    if (samples_needed > 0 &&
        ((self->offset + 512 < self->file_size) || (!self->file))) {
        do {
            int16_t rendered[MINIMP3_MAX_SAMPLES_PER_FRAME];
            samples =
                mp3dec_decode_frame(&self->mp3d, self->data + self->pos,
                                    self->count - self->pos, rendered, &info);
            self->pos += info.frame_bytes;
            if (samples) {
                self->samplerate = info.hz;
                self->channels = info.channels;
                self->control.time += samples / (float)self->samplerate;
                st3m_pcm_queue_s16(self->samplerate, self->channels, samples,
                                   rendered);
            } else if (info.frame_bytes) {
                mp3_fetch_data(self);
            } else {
                break;
            }
            samples_needed -= (samples);
        } while (samples_needed > 0);
    }
}

static void mp3_destroy(st3m_media *media) {
    mp3_state *self = (void *)media;
    if (self->data) free(self->data);
    if (self->file) fclose(self->file);
    if (self->socket) {
        shutdown(self->socket, SHUT_RDWR);
        close(self->socket);
    }
    if (self->path) free(self->path);
    if (self->title) free(self->title);
    if (self->artist) free(self->artist);
    free(self);
}

typedef struct {
    char tag[3];
    char title[30];
    char artist[30];
    char album[30];
    char year[4];
    char comment[30];
    char genre[1];
    char pad[128];
} id3tag_t;

st3m_media *st3m_media_load_mp3(const char *path) {
    mp3_state *self = (mp3_state *)malloc(sizeof(mp3_state));
    if (!self) return NULL;
    memset(self, 0, sizeof(mp3_state));
    self->control.draw = mp3_draw;
    self->control.think = mp3_think;
    self->control.destroy = mp3_destroy;
    self->control.get_string = mp3_get_string;
    self->control.has_audio = true;
    self->samplerate = 44100;
    self->buffer_size = 32 * 1024;
    self->scroll_pos = 0;

    if (!strncmp(path, "http://", 7)) {
        int port = 80;
        char *hostname = strdup(path + 7);
        char *rest = NULL;
        self->buffer_size = 96 * 1024;
        rest = strchr(hostname, '/') + 1;
        strchr(hostname, '/')[0] = 0;
        if (strchr(hostname, ':')) {
            port = atoi(strchr(hostname, ':') + 1);
            strchr(hostname, ':')[0] = 0;
        }

        struct hostent *host;
        struct sockaddr_in addr;
        self->socket = socket(PF_INET, SOCK_STREAM, 0);
        if (self->socket < 0) {
            free(hostname);
            mp3_destroy((st3m_media *)self);
            return NULL;
        }
        int flag = 1;
        setsockopt(self->socket, IPPROTO_TCP, TCP_NODELAY, &flag, sizeof(int));
        memset(&addr, 0, sizeof(addr));
        addr.sin_family = AF_INET;
        addr.sin_port = htons(port);
        host = gethostbyname(hostname);
        if (!host) {
            mp3_destroy((st3m_media *)self);
            free(hostname);
            return NULL;
        }
        addr.sin_addr.s_addr = ((long unsigned int **)host->h_addr_list)[0][0];

        if (connect(self->socket, (struct sockaddr *)&addr, sizeof(addr)) ==
            0) {
            char s[1024];
            sprintf(s, "GET /%s HTTP/1.1\r\n", rest);
            write(self->socket, s, strlen(s));
            sprintf(s, "Range: bytes=0-\r\n");
            write(self->socket, s, strlen(s));
            if (hostname) {
                sprintf(s, "Host: %s\r\n", hostname);
                write(self->socket, s, strlen(s));
            }
            sprintf(s, "User-Agent: flow3r\r\n");
            write(self->socket, s, strlen(s));
            sprintf(s, "\r\n");
            write(self->socket, s, strlen(s));
            fsync(self->socket);

            self->data = malloc(self->buffer_size);
            self->size = self->buffer_size;

            mp3dec_init(&self->mp3d);
            self->control.duration = -1;
            free(hostname);

            if (!self->data) {
                mp3_destroy((st3m_media *)self);
                return NULL;
            }

            self->in_buffering = 1;
            self->path = strdup(path);
            return (st3m_media *)self;
        }
        free(hostname);

        mp3_destroy((st3m_media *)self);
        return NULL;
    }
    st3m_media_tags_t *tags = st3m_media_get_tags(path);
    if (tags) {
        if (tags->title) self->title = strdup(tags->title);
        if (tags->artist) self->artist = strdup(tags->artist);
        self->year = tags->year;
        st3m_media_free_tags(tags);
    }

    self->file = fopen(path, "r");
    if (!self->file) {
        mp3_destroy((st3m_media *)self);
        return NULL;
    }
    fseek(self->file, 0, SEEK_END);
    self->file_size = ftell(self->file);

    self->data = malloc(self->buffer_size);
    if (!self->data) {
        mp3_destroy((st3m_media *)self);
        return NULL;
    }
    self->size = self->buffer_size;
    mp3dec_init(&self->mp3d);
    self->control.duration = self->file_size;

    self->path = strdup(path);
    if (!self->path) {
        mp3_destroy((st3m_media *)self);
        return NULL;
    }

    rewind(self->file);

    return (st3m_media *)self;
}

static uint32_t id3v2_decode_size(char *start, bool syncsafe) {
    uint32_t ret = 0;
    if (syncsafe) {
        for (int j = 0; j < 4; j++) {
            ret += (start[3 - j] & 0b1111111) << (7 * j);
        }
    } else {
        for (int j = 0; j < 4; j++) {
            ret += start[3 - j] << (8 * j);
        }
    }
    return ret;
}

static char *strndup_textframe(char *content, int len) {
    char *ret;
    if (content[0] == 1) {  // corrupt bytes should be assumed to be 0
        // utf-16:
        int string_start = 1;
        bool byte_flip = false;
        if (content[1] == ((char)0xFF) && content[2] == ((char)0xFE)) {
            string_start += 2;
        } else if (content[1] == ((char)0xFE) && content[2] == ((char)0xFF)) {
            string_start += 2;
            byte_flip = true;
        }
        int ascii_len =
            (len - string_start) /
            2;  // one extra byte is in there already, preventing round-downs
        ret = malloc(ascii_len + 1);
        if (!ret) return NULL;
        ret[ascii_len] = 0;
        for (int i = 0; i < ascii_len; i++) {
            if (content[string_start + 2 * i + 1 - byte_flip]) {
                ret[i] = '?';
            } else {
                ret[i] = content[string_start + 2 * i + byte_flip];
            }
        }
    } else {
        // iso-8859-1
        ret = strndup(&content[1], len - 1);
    }
    int ret_len = strlen(ret);
    // filter out high bit special chars
    for (int i = 0; i < ret_len; i++) {
        if (ret[i] & 0x80) ret[i] = '?';
    }
    return ret;
}

enum supported_tags { NONE, TITLE, ARTIST, ALBUM, TRACK_NUMBER, YEAR };

st3m_media_tags_t *audio_mp3_get_tags(const char *path) {
    // returns a new media_tags_t object with tag information
    // retrieved from file at path (or NULL). freeing is up to the user.
    FILE *file = fopen(path, "r");
    if (!file) return NULL;
    fseek(file, 0, SEEK_END);
    int file_size = ftell(file);

    st3m_media_tags_t *tags = calloc(1, sizeof(st3m_media_tags_t));
    if (!tags) return NULL;

    // ID3v1/ID3v1.1
    fseek(file, file_size - 128, SEEK_SET);
    id3tag_t id3;
    fread(&id3, 128, 1, file);
    if (id3.tag[0] == 'T' && id3.tag[1] == 'A' && id3.tag[2] == 'G') {
        tags->title = strndup(id3.title, 30);
        while (tags->title[strlen(tags->title) - 1] == ' ')
            tags->title[strlen(tags->title) - 1] = 0;

        tags->artist = strndup(id3.artist, 30);
        while (tags->artist[strlen(tags->artist) - 1] == ' ')
            tags->artist[strlen(tags->artist) - 1] = 0;

        tags->album = strndup(id3.album, 30);
        while (tags->album[strlen(tags->album) - 1] == ' ')
            tags->album[strlen(tags->album) - 1] = 0;

        tags->year = atoi(id3.year);

        if (!id3.comment[28]) {
            tags->track_number = id3.comment[29];
        }
        fclose(file);
        return tags;
    }

    // ID3v2
    fseek(file, 0, SEEK_SET);
    char buf[10];
    fread(buf, 10, 1, file);
    if (buf[0] == 'I' && buf[1] == 'D' && buf[2] == '3') {
        uint32_t frame_pos = 10;
        uint8_t version = buf[3];
        if (version < 2 || version > 4) {
            fclose(file);
            free(tags);
            return NULL;
        }
        uint32_t tag_size = 10 + id3v2_decode_size(&buf[6], version >= 3);
        if (buf[4] & 0b100000) {  // extended header
            fread(buf, 10, 1, file);
            frame_pos += id3v2_decode_size(&buf[0], version >= 3);
        }
        while (frame_pos < tag_size) {
            uint32_t frame_size = 0;
            fseek(file, frame_pos, SEEK_SET);
            if (version > 2) {
                fread(buf, 10, 1, file);
                frame_size = id3v2_decode_size(&buf[4], version >= 4);
                frame_pos += 10;
            } else {
                fread(buf, 6, 1, file);
                frame_size = id3v2_decode_size(&buf[3], false);
                frame_size >>= 8;
                frame_pos += 6;
            }
#if 0
            printf("\nframe pos: %lu, frame size: %lu, tag size: %lu\n", frame_pos, frame_size, tag_size);
            char tag[5];
            memcpy(tag, buf, 4);
            tag[4] = 0;
            printf("tag: %s\n", tag);
#endif

            if (frame_pos + frame_size > tag_size) break;

            enum supported_tags frame_tag = NONE;
            if (version > 2) {
                if (strncmp(buf, "TIT2", 4) == 0) {
                    frame_tag = TITLE;
                } else if (strncmp(buf, "TPE1", 4) == 0) {
                    frame_tag = ARTIST;
                } else if (strncmp(buf, "TRCK", 4) == 0) {
                    frame_tag = TRACK_NUMBER;
                } else if (strncmp(buf, "TYER", 4) == 0) {
                    frame_tag = YEAR;
                } else if (strncmp(buf, "TALB", 4) == 0) {
                    frame_tag = ALBUM;
                }
            } else {
                if (strncmp(buf, "TT2", 3) == 0) {
                    frame_tag = TITLE;
                } else if (strncmp(buf, "TP1", 3) == 0) {
                    frame_tag = ARTIST;
                } else if (strncmp(buf, "TRK", 3) == 0) {
                    frame_tag = TRACK_NUMBER;
                } else if (strncmp(buf, "TYE", 3) == 0) {
                    frame_tag = YEAR;
                } else if (strncmp(buf, "TAL", 3) == 0) {
                    frame_tag = ALBUM;
                }
            }
            if (frame_tag == NONE) continue;

            char *fbuf = malloc(
                frame_size);  // putting it on heap bc task stack may overflow
            if (!fbuf)
                continue;  // earlier, don't wanna worried about limits here
            if (fread(fbuf, 1, frame_size, file) != frame_size) {
                free(fbuf);
                break;
            }

            switch (frame_tag) {
                case TITLE:
                    tags->title = strndup_textframe(fbuf, frame_size);
                    break;
                case ARTIST:
                    tags->artist = strndup_textframe(fbuf, frame_size);
                    break;
                case TRACK_NUMBER:;
                    char *slashpos = strchr(fbuf, '/');
                    if (slashpos) *slashpos = 0;
                    tags->track_number = atoi(fbuf);
                    break;
                case YEAR:
                    tags->year = atoi(fbuf);
                    break;
                case ALBUM:
                    tags->album = strndup_textframe(fbuf, frame_size);
                    break;
                default:
                    break;  // should never be reached, just to make compiler
                            // happy
            }
            free(fbuf);
            if (tags->title && tags->artist && tags->track_number &&
                tags->year && tags->album)
                break;
            frame_pos += frame_size;
        }
        fclose(file);
        return tags;
    }

    free(tags);
    fclose(file);
    return NULL;
}
+44 −0
Original line number Diff line number Diff line
#SPDX-License-Identifier: CC0-1.0

idf_component_register(
    SRCS
        bl00mbox.c
        bl00mbox_audio.c
        bl00mbox_user.c
        bl00mbox_os.c
        bl00mbox_plugin_registry.c
        bl00mbox_radspa_requirements.c
        bl00mbox_containers.c
        radspa/standard_plugin_lib/osc.c
        radspa/standard_plugin_lib/osc_fm.c
        radspa/standard_plugin_lib/env_adsr.c
        radspa/standard_plugin_lib/ampliverter.c
        radspa/standard_plugin_lib/sampler.c
        radspa/standard_plugin_lib/delay.c
        radspa/standard_plugin_lib/flanger.c
        radspa/standard_plugin_lib/multipitch.c
        radspa/standard_plugin_lib/trigger_merge.c
        radspa/standard_plugin_lib/sequencer.c
        radspa/standard_plugin_lib/noise.c
        radspa/standard_plugin_lib/noise_burst.c
        radspa/standard_plugin_lib/distortion.c
        radspa/standard_plugin_lib/lowpass.c
        radspa/standard_plugin_lib/filter.c
        radspa/standard_plugin_lib/mixer.c
        radspa/standard_plugin_lib/range_shifter.c
        radspa/standard_plugin_lib/poly_squeeze.c
        radspa/standard_plugin_lib/slew_rate_limiter.c
        radspa/standard_plugin_lib/buffer.c
        plugins/bl00mbox_specific/bl00mbox_line_in.c
        plugins/bl00mbox_specific/bl00mbox_channel_plugin.c
        radspa/radspa_helpers.c
        extern/xoroshiro64star.c
    INCLUDE_DIRS
        include
        plugins
        plugins/bl00mbox_specific
        radspa
        radspa/standard_plugin_lib
        extern
        config
)
+121 −0
Original line number Diff line number Diff line
Creative Commons Legal Code

CC0 1.0 Universal

    CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE
    LEGAL SERVICES. DISTRIBUTION OF THIS DOCUMENT DOES NOT CREATE AN
    ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS
    INFORMATION ON AN "AS-IS" BASIS. CREATIVE COMMONS MAKES NO WARRANTIES
    REGARDING THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS
    PROVIDED HEREUNDER, AND DISCLAIMS LIABILITY FOR DAMAGES RESULTING FROM
    THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED
    HEREUNDER.

Statement of Purpose

The laws of most jurisdictions throughout the world automatically confer
exclusive Copyright and Related Rights (defined below) upon the creator
and subsequent owner(s) (each and all, an "owner") of an original work of
authorship and/or a database (each, a "Work").

Certain owners wish to permanently relinquish those rights to a Work for
the purpose of contributing to a commons of creative, cultural and
scientific works ("Commons") that the public can reliably and without fear
of later claims of infringement build upon, modify, incorporate in other
works, reuse and redistribute as freely as possible in any form whatsoever
and for any purposes, including without limitation commercial purposes.
These owners may contribute to the Commons to promote the ideal of a free
culture and the further production of creative, cultural and scientific
works, or to gain reputation or greater distribution for their Work in
part through the use and efforts of others.

For these and/or other purposes and motivations, and without any
expectation of additional consideration or compensation, the person
associating CC0 with a Work (the "Affirmer"), to the extent that he or she
is an owner of Copyright and Related Rights in the Work, voluntarily
elects to apply CC0 to the Work and publicly distribute the Work under its
terms, with knowledge of his or her Copyright and Related Rights in the
Work and the meaning and intended legal effect of CC0 on those rights.

1. Copyright and Related Rights. A Work made available under CC0 may be
protected by copyright and related or neighboring rights ("Copyright and
Related Rights"). Copyright and Related Rights include, but are not
limited to, the following:

  i. the right to reproduce, adapt, distribute, perform, display,
     communicate, and translate a Work;
 ii. moral rights retained by the original author(s) and/or performer(s);
iii. publicity and privacy rights pertaining to a person's image or
     likeness depicted in a Work;
 iv. rights protecting against unfair competition in regards to a Work,
     subject to the limitations in paragraph 4(a), below;
  v. rights protecting the extraction, dissemination, use and reuse of data
     in a Work;
 vi. database rights (such as those arising under Directive 96/9/EC of the
     European Parliament and of the Council of 11 March 1996 on the legal
     protection of databases, and under any national implementation
     thereof, including any amended or successor version of such
     directive); and
vii. other similar, equivalent or corresponding rights throughout the
     world based on applicable law or treaty, and any national
     implementations thereof.

2. Waiver. To the greatest extent permitted by, but not in contravention
of, applicable law, Affirmer hereby overtly, fully, permanently,
irrevocably and unconditionally waives, abandons, and surrenders all of
Affirmer's Copyright and Related Rights and associated claims and causes
of action, whether now known or unknown (including existing as well as
future claims and causes of action), in the Work (i) in all territories
worldwide, (ii) for the maximum duration provided by applicable law or
treaty (including future time extensions), (iii) in any current or future
medium and for any number of copies, and (iv) for any purpose whatsoever,
including without limitation commercial, advertising or promotional
purposes (the "Waiver"). Affirmer makes the Waiver for the benefit of each
member of the public at large and to the detriment of Affirmer's heirs and
successors, fully intending that such Waiver shall not be subject to
revocation, rescission, cancellation, termination, or any other legal or
equitable action to disrupt the quiet enjoyment of the Work by the public
as contemplated by Affirmer's express Statement of Purpose.

3. Public License Fallback. Should any part of the Waiver for any reason
be judged legally invalid or ineffective under applicable law, then the
Waiver shall be preserved to the maximum extent permitted taking into
account Affirmer's express Statement of Purpose. In addition, to the
extent the Waiver is so judged Affirmer hereby grants to each affected
person a royalty-free, non transferable, non sublicensable, non exclusive,
irrevocable and unconditional license to exercise Affirmer's Copyright and
Related Rights in the Work (i) in all territories worldwide, (ii) for the
maximum duration provided by applicable law or treaty (including future
time extensions), (iii) in any current or future medium and for any number
of copies, and (iv) for any purpose whatsoever, including without
limitation commercial, advertising or promotional purposes (the
"License"). The License shall be deemed effective as of the date CC0 was
applied by Affirmer to the Work. Should any part of the License for any
reason be judged legally invalid or ineffective under applicable law, such
partial invalidity or ineffectiveness shall not invalidate the remainder
of the License, and in such case Affirmer hereby affirms that he or she
will not (i) exercise any of his or her remaining Copyright and Related
Rights in the Work or (ii) assert any associated claims and causes of
action with respect to the Work, in either case contrary to Affirmer's
express Statement of Purpose.

4. Limitations and Disclaimers.

 a. No trademark or patent rights held by Affirmer are waived, abandoned,
    surrendered, licensed or otherwise affected by this document.
 b. Affirmer offers the Work as-is and makes no representations or
    warranties of any kind concerning the Work, express, implied,
    statutory or otherwise, including without limitation warranties of
    title, merchantability, fitness for a particular purpose, non
    infringement, or the absence of latent or other defects, accuracy, or
    the present or absence of errors, whether or not discoverable, all to
    the greatest extent permissible under applicable law.
 c. Affirmer disclaims responsibility for clearing rights of other persons
    that may apply to the Work or any use thereof, including without
    limitation any person's Copyright and Related Rights in the Work.
    Further, Affirmer disclaims responsibility for obtaining any necessary
    consents, permissions or other rights required for any use of the
    Work.
 d. Affirmer understands and acknowledges that Creative Commons is not a
    party to this document and has no duty or obligation with respect to
    this CC0 or use of the Work.
+3 −0
Original line number Diff line number Diff line
# documentation

https://moon2embeddedaudio.gitlab.io/bl00mbox/main/
+9 −0
Original line number Diff line number Diff line
//SPDX-License-Identifier: CC0-1.0
#include "bl00mbox.h"
#include "bl00mbox_plugin_registry.h"
#include "bl00mbox_audio.h"

void bl00mbox_init(){
    bl00mbox_plugin_registry_init();
    bl00mbox_audio_init();
}
+356 −0
Original line number Diff line number Diff line
//SPDX-License-Identifier: CC0-1.0
#include "bl00mbox_audio.h"
#include "bl00mbox_user.h"
#include "bl00mbox_os.h"
#include "bl00mbox_channel_plugin.h"
#include <assert.h>

static uint16_t full_buffer_len;

static uint32_t render_pass_id;

int16_t * bl00mbox_line_in_interlaced = NULL;

static bl00mbox_lock_t user_lock = NULL;
// grab user_lock for r/w
static bl00mbox_set_t * all_chans = NULL;
// grab user_lock for r/w
static bl00mbox_set_t * background_mute_override_chans = NULL;
// grab user_lock for r/w
static bl00mbox_channel_t * foreground_chan = NULL;

// grab both user_lock and active_chans_lock for writing.
// for user-side reading grab user_lock.
// render task reads with active_chans_lock.
static bl00mbox_array_t * active_chans = NULL;
static bl00mbox_lock_t active_chans_lock = NULL;

static void update_active_chans(){
    // must be called after changing foreground_chan or background_mute_override_chans
    // while _still_ holding user_lock but not active_chans_lock
    size_t num_chans = background_mute_override_chans->len;
    if(foreground_chan) num_chans++;
    bl00mbox_array_t * new_active_chans = malloc(sizeof(bl00mbox_array_t) + num_chans * sizeof(void *));
    if(new_active_chans){
        size_t index = 0;
        if(foreground_chan){
            new_active_chans->elems[index] = foreground_chan;
            index++;
        }
        bl00mbox_set_iter_t iter;
        bl00mbox_set_iter_start(&iter, background_mute_override_chans);
        bl00mbox_channel_t * chan;
        while((chan = bl00mbox_set_iter_next(&iter))){
            if(chan == foreground_chan) continue;
            new_active_chans->elems[index] = chan; 
            index++;
        }
        new_active_chans->len = index;
    } else {
        bl00mbox_log_error("out of memory");
    }

#ifdef BL00MBOX_DEBUG
    if(new_active_chans) bl00mbox_log_error("active chans: %d", (int) new_active_chans->len);
#endif
    bl00mbox_array_t * previous_active_chans;
    bl00mbox_take_lock(&active_chans_lock);
    previous_active_chans = active_chans;
    active_chans = new_active_chans;
    bl00mbox_give_lock(&active_chans_lock);
    free(previous_active_chans);
}

bl00mbox_array_t * bl00mbox_collect_channels(bool active){
    bl00mbox_array_t * ret = NULL;
    bl00mbox_take_lock(&user_lock);
    if(active){
        if(active_chans){
            size_t ret_size = sizeof(bl00mbox_array_t);
            ret_size += active_chans->len * sizeof(void *);
            ret = malloc(ret_size);
            if(ret) memcpy(ret, active_chans, ret_size);
        } else {
            ret = malloc(sizeof(bl00mbox_array_t));
            if(ret) ret->len = 0;
        }
    } else {
        ret = bl00mbox_set_to_array(all_chans);
    }
    bl00mbox_give_lock(&user_lock);
    if(!ret) bl00mbox_log_error("out of memory");
    return ret;
}

void bl00mbox_channel_set_background_mute_override(bl00mbox_channel_t * chan, bool enable){
    bl00mbox_take_lock(&user_lock);
    chan->background_mute_override = enable;
    bool update;
    if(enable){
        update = bl00mbox_set_add(background_mute_override_chans, chan);
    } else {
        update = bl00mbox_set_remove(background_mute_override_chans, chan);
    }
    if(update) update_active_chans();
    bl00mbox_give_lock(&user_lock);
}

bool bl00mbox_channel_get_foreground(bl00mbox_channel_t * chan){
    return foreground_chan == chan;
}

void bl00mbox_channel_set_foreground(bl00mbox_channel_t * chan, bool enable){
    if(bl00mbox_channel_get_foreground(chan) == enable) return;
    bl00mbox_take_lock(&user_lock);
    foreground_chan = enable ? chan : NULL;
    update_active_chans();
    bl00mbox_give_lock(&user_lock);
}

void bl00mbox_channel_event(bl00mbox_channel_t * chan){
#ifdef BL00MBOX_AUTO_FOREGROUNDING
    bl00mbox_channel_set_foreground(chan, true);
#endif
}

bl00mbox_channel_t * bl00mbox_channel_create(){
    bl00mbox_channel_t * chan = calloc(1, sizeof(bl00mbox_channel_t));
    if(!chan) goto failed;
    chan->volume = BL00MBOX_DEFAULT_CHANNEL_VOLUME;
    chan->sys_gain = 4096;

    // must be destroyed manually as it's not in the plugin list
    chan->channel_plugin = bl00mbox_plugin_create_unlisted(chan, &bl00mbox_channel_plugin_desc, 0);
    if(!chan->channel_plugin) goto failed;

    if(!bl00mbox_create_lock(&chan->render_lock)) goto failed;

    bl00mbox_take_lock(&user_lock);
    if(!bl00mbox_set_add_skip_unique_check(all_chans, chan)) goto failed;
    foreground_chan = chan;
    update_active_chans();
    bl00mbox_give_lock(&user_lock);
    return chan;

failed:
    if(chan){
        if(chan->channel_plugin){
            // supress errors
            chan->channel_plugin->parent_self_ref = &chan->channel_plugin;
            bl00mbox_plugin_destroy(chan->channel_plugin);
        }
        if(chan->render_lock) bl00mbox_delete_lock(&chan->render_lock);
        free(chan);
    }
    bl00mbox_log_error("channel allocation failed");
    return NULL;
}

void bl00mbox_channel_clear(bl00mbox_channel_t * chan){
    // note: this does NOT destroy the channel_plugin as it is unlisted
    bl00mbox_set_iter_t iter;
    bl00mbox_set_iter_start(&iter, &chan->plugins);
    bl00mbox_plugin_t * plugin;
    while((plugin = bl00mbox_set_iter_next(&iter))){
        bl00mbox_plugin_destroy(plugin);
    }
    chan->plugin_id = 0;
}

void bl00mbox_channel_destroy(bl00mbox_channel_t * chan){
    bl00mbox_channel_clear(chan);

    // remove from all lists
    bl00mbox_take_lock(&user_lock);
    bool is_active = false;
    if(foreground_chan == chan){
        foreground_chan = NULL;
        is_active = true;
    }
    if(bl00mbox_set_remove(background_mute_override_chans, chan)){
        is_active = true;
    }
    if(is_active) update_active_chans();
    bl00mbox_set_remove(all_chans, chan);
    bl00mbox_give_lock(&user_lock);

    // remove from parent
    if(* (chan->parent_self_ref) != chan){
        bl00mbox_log_error("channel: parent_self_ref improper: channel %p, ref %p",
                            chan, * (chan->parent_self_ref));
    }
    * (chan->parent_self_ref) = NULL;

    // remove from weak parent
    if(chan->weak_parent_self_ref){
        if(* (chan->weak_parent_self_ref) != chan){
            bl00mbox_log_error("channel: weak_parent_self_ref improper: channel %p, ref %p",
                                chan, * (chan->weak_parent_self_ref));
        }
        * (chan->weak_parent_self_ref) = NULL;
    }

#ifdef BL00MBOX_DEBUG
    if(chan->connections.len) bl00mbox_log_error("connections nonempty");
    if(chan->roots.len) bl00mbox_log_error("roots nonempty");
    if(chan->always_render.len) bl00mbox_log_error("always render nonempty");
    if(chan->plugins.len) bl00mbox_log_error("plugins nonempty");
    bl00mbox_wait();
#endif

    // be really sure that nobody else holds the lock. the renderer
    // doesn't at this point, but if there's multiple tasks running
    // clients there may be collisions.
    // since the client api is generally not thread safe at this point
    // it's okay, we can add the feature easily by just wrapping _all_
    // client api in a lock at some point in the future.
    bl00mbox_delete_lock(&chan->render_lock);

    if(chan->channel_plugin) bl00mbox_plugin_destroy(chan->channel_plugin);
    free(chan->render_plugins);
    free(chan->render_buffers);
    free(chan->name);
    free(chan);
}

void bl00mbox_audio_plugin_render(bl00mbox_plugin_t * plugin){
    if(plugin->render_pass_id == render_pass_id) return;
#ifdef BL00MBOX_LOOPS_ENABLE
    if(plugin->is_being_rendered) return;
#endif
    plugin->is_being_rendered = true;
    plugin->rugin->render(plugin->rugin, full_buffer_len, render_pass_id);
    plugin->render_pass_id = render_pass_id;
    plugin->is_being_rendered = false;
}

static bool _bl00mbox_audio_channel_render(bl00mbox_channel_t * chan, int16_t * out, bool adding){
    chan->render_pass_id = render_pass_id;

    int32_t vol = radspa_mult_shift(chan->volume, chan->sys_gain);
    if(!vol) return false; // don't render if muted

    // render these even if nothing is plugged into mixer
    if(chan->render_plugins){
        for(size_t i = 0; i < chan->render_plugins->len; i++){
            bl00mbox_audio_plugin_render(chan->render_plugins->elems[i]);
        }
    }

    bl00mbox_channel_plugin_update_values(chan->channel_plugin->rugin, render_pass_id);

    if(!(chan->render_buffers && chan->render_buffers->len)) return false;


    int32_t acc[full_buffer_len];

    // first one non-adding
    int16_t * buffer = chan->render_buffers->elems[0];
    if(buffer[1] == -32768){
        for(size_t i = 0; i < full_buffer_len; i++){
            acc[i] = buffer[0];
        }
    } else {
        for(size_t i = 0; i < full_buffer_len; i++){
            acc[i] = buffer[i];
        }
    }

    // rest adding
    for(size_t i = 1; i < chan->render_buffers->len; i++){
        buffer = chan->render_buffers->elems[i];
        if(buffer[1] == -32768){
            if(buffer[0]){
                for(size_t i = 0; i < full_buffer_len; i++){
                    acc[i] += buffer[0];
                }
            }
        } else {
            for(size_t i = 0; i < full_buffer_len; i++){
                acc[i] += buffer[i];
            }
        }
    }

    for(uint16_t i = 0; i < full_buffer_len; i++){
        // flip around for rounding towards zero/mulsh boost
        int invert = chan->dc < 0 ? -1 : 1;
        chan->dc = chan->dc * invert;
        chan->dc = ((uint64_t) chan->dc * (((1<<12) - 1)<<20)) >> 32;
        chan->dc = chan->dc * invert;

        chan->dc += acc[i];

        acc[i] -= (chan->dc >> 12);
    }
    if(adding){
        for(uint16_t i = 0; i < full_buffer_len; i++){
            out[i] = radspa_add_sat(radspa_gain(acc[i], vol), out[i]);
        }
    } else {
        for(uint16_t i = 0; i < full_buffer_len; i++){
            out[i] = radspa_gain(acc[i], vol);
        }
    }
    if(chan->compute_rms){
        for(uint16_t i = 0; i < full_buffer_len; i++){
            int32_t sq = acc[i];
            sq = (sq * sq) - chan->mean_square;
            // always round down with negative sq so that decay always works.
            // bitshift instead of div does that for us nicely.
            // cannot underflow as ((-a) >> 11) can never be less than -a.
            chan->mean_square += sq >> 11;
        }
    }
    return true;
}

static bool bl00mbox_audio_channel_render(bl00mbox_channel_t * chan, int16_t * out, bool adding){
    if(render_pass_id == chan->render_pass_id) return false;
    bl00mbox_take_lock(&chan->render_lock);
    bool ret = _bl00mbox_audio_channel_render(chan, out, adding);
    bl00mbox_give_lock(&chan->render_lock);
    // null it out if nothing was rendered
    chan->mean_square *= ret;
    return ret;
}

void bl00mbox_audio_render(int16_t * rx, int16_t * tx, uint16_t len){
    full_buffer_len = len/2;
    bl00mbox_line_in_interlaced = rx;
    int16_t acc[full_buffer_len];
    bool acc_init = false;

    bl00mbox_take_lock(&active_chans_lock);
    render_pass_id++;
    if(active_chans){
        for(size_t i = 0; i < active_chans->len; i++){
            acc_init = bl00mbox_audio_channel_render(active_chans->elems[i], acc, acc_init) || acc_init;
        }
    }
    bl00mbox_give_lock(&active_chans_lock);

    if(acc_init){
        for(uint16_t i = 0; i < full_buffer_len; i++){
            tx[2*i] = acc[i];
            tx[2*i+1] = acc[i];
        }
    } else {
        memset(tx, 0, len * sizeof(int16_t));
    }
}

void bl00mbox_audio_init(){
    assert(bl00mbox_create_lock(&active_chans_lock));

    // micropython objects are generally not thread safe, so for most of the user API we need
    // not care about locking after they've been created. however, bl00mbox Channel objects may
    // be created by different threads (i.e., thread API), so these sets must be fully thread safe.
    assert(bl00mbox_create_lock(&user_lock));

    all_chans = calloc(1, sizeof(bl00mbox_set_t));
    assert(all_chans);

    background_mute_override_chans = calloc(1, sizeof(bl00mbox_set_t));
    assert(background_mute_override_chans);
}
Original line number Diff line number Diff line
#include "bl00mbox_containers.h"

static bool equals(void * some, void * other, bl00mbox_set_key_t key){
    if(!key) return some == other;
    return key(some, other);
}

static bool set_add_inner(bl00mbox_set_t * set, void * content){
    bl00mbox_ll_t * ll = malloc(sizeof(bl00mbox_ll_t));
    if(!ll) return false;
    ll->content = content;
    ll->next = set->start;
    set->start = ll;
    set->len++;
    return true;
}

bool bl00mbox_set_contains(bl00mbox_set_t * set, void * content){
    if(!content) return false; // NULL pointers can't be in set
    if(!set->start) return false;
    bl00mbox_ll_t * seek = set->start;
    while(seek){
        if(equals(seek->content, content, set->key)) break;
        seek = seek->next;
    }
    return seek;
}

bool bl00mbox_set_add_skip_unique_check(bl00mbox_set_t * set, void * content){
    if(!content) return false; // don't allow for NULL pointers in set
#ifdef BL00MBOX_DEBUG
    if(bl00mbox_set_contains(set, content)){
        bl00mbox_log_error("set corrupted");
        return false;
    }
#endif
    return set_add_inner(set, content);
}

bool bl00mbox_set_add(bl00mbox_set_t * set, void * content){
    if(bl00mbox_set_contains(set, content)) return false;
    return set_add_inner(set, content);
}

bool bl00mbox_set_remove(bl00mbox_set_t * set, void * content){
    if(!content) return false;
    bl00mbox_ll_t * seek = set->start;
    bl00mbox_ll_t * prev = NULL;
    while(seek){
        if(equals(seek->content, content, set->key)) break;
        prev = seek;
        seek = seek->next;
    }
    if(seek){
        bl00mbox_ll_t ** target = prev ? &(prev->next) : &(set->start);
        (* target) = seek->next;
        set->len--;
    }
    free(seek);
    return true;
}

void bl00mbox_set_iter_start(bl00mbox_set_iter_t * iter, bl00mbox_set_t * set){
    iter->next = set->start;
}

void * bl00mbox_set_iter_next(bl00mbox_set_iter_t * iter){
    if(!iter->next) return NULL;
    void * ret = iter->next->content;
    iter->next = iter->next->next;
    return ret;
}

bl00mbox_array_t * bl00mbox_set_to_array(bl00mbox_set_t * set){
    bl00mbox_array_t * ret = malloc(sizeof(bl00mbox_array_t) + set->len * sizeof(void *));
    if(!ret) return NULL;
    ret->len = set->len;
    bl00mbox_set_iter_t iter;
    bl00mbox_set_iter_start(&iter, set);
    void * content;
    size_t index = 0;
    while((content = bl00mbox_set_iter_next(&iter))){
        ret->elems[index++] = content;
    }
    return ret;
}
+43 −0
Original line number Diff line number Diff line
#include "bl00mbox_os.h"

#ifdef BL00MBOX_FREERTOS
bool bl00mbox_create_lock(bl00mbox_lock_t * lock){
    assert(*lock == NULL);
    * lock = xSemaphoreCreateMutex();
    return(*lock != NULL);
}
void bl00mbox_delete_lock(bl00mbox_lock_t * lock){ vSemaphoreDelete(* lock); }
void bl00mbox_take_lock(bl00mbox_lock_t * lock){ xSemaphoreTake(* lock, portMAX_DELAY); }
void bl00mbox_give_lock(bl00mbox_lock_t * lock){ xSemaphoreGive(* lock); }
#ifdef BL00MBOX_DEBUG
void bl00mbox_wait() { vTaskDelay(10); }
#endif
#endif

#if defined(BL00MBOX_ESPIDF)
// macros in header
#elif defined(BL00MBOX_PRINTF)
#include <stdarg.h>
#include <string.h>
static void _bl00mbox_log(char * pre, char * txt, va_list args){
    int len = strlen(pre) + strlen(txt) + 2;
    char msg[len];
    snprintf(msg, len, "%s%s\n", pre, txt);
    vprintf(msg, args);
}
void bl00mbox_log_error(char * txt, ...){
    va_list args;
    va_start(args, txt);
    _bl00mbox_log("bl00mbox error: ", txt, args);
    va_end(args);
};
void bl00mbox_log_info(char * txt, ...){
    va_list args;
    va_start(args, txt);
    _bl00mbox_log("bl00mbox info: ", txt, args);
    va_end(args);
};
#else
void bl00mbox_log_error(char * txt, ...){};
void bl00mbox_log_info(char * txt, ...){};
#endif
Original line number Diff line number Diff line
//SPDX-License-Identifier: CC0-1.0
#include "bl00mbox_plugin_registry.h"

static bl00mbox_plugin_registry_t * bl00mbox_plugin_registry = NULL;
static uint16_t bl00mbox_plugin_registry_len = 0;
static bool bl00mbox_plugin_registry_is_initialized = false;

static void plugin_add(radspa_descriptor_t * descriptor){
    if(descriptor->id == BL00MBOX_CHANNEL_PLUGIN_ID){
        bl00mbox_log_error("plugin list id collision");
    }
    if(bl00mbox_plugin_registry_len == 65535){
        bl00mbox_log_error("too many plugins registered");
        return;
    }

    // create plugin registry entry
    bl00mbox_plugin_registry_t * p = malloc(sizeof(bl00mbox_plugin_registry_t));
    if(!p){
        bl00mbox_log_error("no memory for plugin list");
        return;
    }
    p->descriptor = descriptor;
    p->next = NULL;

    // go to end of list
    bl00mbox_plugin_registry_t * plast = bl00mbox_plugin_registry;
    if(plast == NULL){
        bl00mbox_plugin_registry = p;
    } else {
        while(plast->next != NULL){
            if(plast->descriptor->id == p->descriptor->id){
                bl00mbox_log_error("plugin list id collision");
                return;
            }
            plast = plast->next;
        }
        plast->next = p;
    }
    bl00mbox_plugin_registry_len++;
}

uint16_t bl00mbox_plugin_registry_get_plugin_num(void){
    return bl00mbox_plugin_registry_len;
}

radspa_descriptor_t * bl00mbox_plugin_registry_get_descriptor_from_id(uint32_t id){
    /// searches plugin registry for first descriptor with given id number
    /// and returns pointer to it. returns NULL if no match is found.
    bl00mbox_plugin_registry_t * p = bl00mbox_plugin_registry;
    while(p != NULL){
        if(p->descriptor->id == id) break;
        p = p->next;
    }
    if(p != NULL) return p->descriptor;
    return NULL;
}

radspa_descriptor_t * bl00mbox_plugin_registry_get_descriptor_from_index(uint32_t index){
    /// returns pointer to descriptor of registry entry at given index.
    /// returns NULL if out of range.
    if(index >= bl00mbox_plugin_registry_len) return NULL;
    bl00mbox_plugin_registry_t * p = bl00mbox_plugin_registry;
    for(uint16_t i = 0; i < index; i++){
        p = p->next;
        if(p == NULL){
            bl00mbox_log_error("bl00mbox: plugin list length error");
            abort();
        }
    }
    return p->descriptor;
}

radspa_descriptor_t * bl00mbox_plugin_registry_get_id_from_index(uint32_t index){
    /// returns pointer to descriptor of registry entry at given index.
    /// returns NULL if out of range.
    if(index >= bl00mbox_plugin_registry_len) return NULL;
    bl00mbox_plugin_registry_t * p = bl00mbox_plugin_registry;
    for(uint16_t i = 0; i < index; i++){
        p = p->next;
        if(p == NULL){
            bl00mbox_log_error("bl00mbox: plugin list length error");
            abort();
        }
    }
    return p->descriptor;
}

/* REGISTER PLUGINS HERE!
 * - include .c file to SRCS in bl00mbox/CMakeLists.txt
 * - include .h file directory to INCLUDE_DIRS in bl00mbox/CMakeLists.txt
 * - include .h file below
 * - use plugin_add in bl00mbox_plugin_registry_init as
 *   exemplified below
 *
 * NOTE: the plugin registry linked list is intended to be filled once at
 * boot time. dynamically adding plugins at runtime may or may not work,
 * removing plugins from the registry at runtime is not intended.
 */

#include "osc_fm.h"
#include "osc.h"
#include "env_adsr.h"
#include "ampliverter.h"
#include "delay.h"
#include "lowpass.h"
#include "filter.h"
#include "sequencer.h"
#include "sampler.h"
#include "flanger.h"
#include "noise.h"
#include "noise_burst.h"
#include "distortion.h"
#include "mixer.h"
#include "multipitch.h"
#include "trigger_merge.h"
#include "slew_rate_limiter.h"
#include "range_shifter.h"
#include "poly_squeeze.h"
#include "bl00mbox_line_in.h"
#include "buffer.h"

void bl00mbox_plugin_registry_init(void){
    if(bl00mbox_plugin_registry_is_initialized) return;
    // do not add bl00mbox_channel_plugin, it is not to be spawned by users
    plugin_add(&osc_desc);
    plugin_add(&filter_desc);
    plugin_add(&sequencer_desc);
    plugin_add(&sampler_desc);
    plugin_add(&multipitch_desc);
    plugin_add(&trigger_merge_desc);
    plugin_add(&bl00mbox_line_in_desc);
    plugin_add(&buffer_desc);
    plugin_add(&distortion_desc);
    plugin_add(&mixer_desc);
    plugin_add(&flanger_desc);
    plugin_add(&noise_desc);
    plugin_add(&noise_burst_desc);
    plugin_add(&env_adsr_desc);
    plugin_add(&delay_desc);
    plugin_add(&range_shifter_desc);
    plugin_add(&poly_squeeze_desc);
    plugin_add(&slew_rate_limiter_desc);
    plugin_add(&ampliverter_desc);
    plugin_add(&osc_fm_desc);
    plugin_add(&lowpass_desc);
}
Original line number Diff line number Diff line
//SPDX-License-Identifier: CC0-1.0
#include "bl00mbox_radspa_requirements.h"

bool radspa_host_request_buffer_render(int16_t * buf){
    bl00mbox_plugin_t * plugin = ((bl00mbox_connection_t *) buf)->source.plugin;
    bl00mbox_audio_plugin_render(plugin);
    return 1;
}

// py: bigtable = [int(22/200*(2**(14-5+8+x*4096/2400/64))) for x in range(64)]
// for 48kHz main sample rate
static const uint16_t bigtable[64] = {
        14417, 14686, 14960, 15240, 15524, 15813, 16108, 16409, 
        16715, 17027, 17345, 17668, 17998, 18334, 18676, 19024, 
        19379, 19741, 20109, 20484, 20866, 21255, 21652, 22056, 
        22467, 22887, 23313, 23748, 24191, 24643, 25103, 25571, 
        26048, 26534, 27029, 27533, 28047, 28570, 29103, 29646, 
        30199, 30763, 31336, 31921, 32517, 33123, 33741, 34371, 
        35012, 35665, 36330, 37008, 37699, 38402, 39118, 39848, 
        40592, 41349, 42120, 42906, 43706, 44522, 45352, 46199
};

// py: smoltable = [int(22/240*(2**(15-5+9+x*4096/2400/64/64))) for x in range(64)]
// for 48kHz main sample rate
static const uint16_t smoltable[64] = {
        48059, 48073, 48087, 48101, 48115, 48129, 48143, 48156, 
        48170, 48184, 48198, 48212, 48226, 48240, 48254, 48268, 
        48282, 48296, 48310, 48324, 48338, 48352, 48366, 48380, 
        48394, 48407, 48421, 48435, 48449, 48463, 48477, 48491, 
        48505, 48519, 48533, 48548, 48562, 48576, 48590, 48604, 
        48618, 48632, 48646, 48660, 48674, 48688, 48702, 48716, 
        48730, 48744, 48758, 48772, 48786, 48801, 48815, 48829, 
        48843, 48857, 48871, 48885, 48899, 48913, 48928, 48942,
};

uint32_t radspa_sct_to_rel_freq(int16_t sct, int16_t undersample_pow){
    /// returns approx. proportional to 2**((sct/2400) + undersample_pow) so that
    /// a uint32_t accumulator overflows at 440Hz with sct = INT16_MAX - 6*2400
    /// when sampled at (48>>undersample_pow)kHz

    // compiler explorer says this is 33 instructions with O2. might be alright?
    uint32_t a = sct;
    a = sct + 28*2400 - 32767 - 330;
    // at O2 u get free division for each modulo. still slow, 10 instructions or so.
    int16_t octa = a / 2400;
    a = a % 2400;
    uint8_t bigindex = a / 64;
    uint8_t smolindex = a % 64;
    
    uint32_t ret = 2; //weird but trust us
    ret *= bigtable[bigindex];
    ret *= smoltable[smolindex];

    int16_t shift = 27 - octa - undersample_pow;
    if(shift > 0){
        ret = ret >> shift;
    }
    return ret;
}

int16_t radspa_random(){ return xoroshiro64star()>>16; }
+497 −0
Original line number Diff line number Diff line
//SPDX-License-Identifier: CC0-1.0
#include "bl00mbox_user.h"

extern void bl00mbox_disconnect_rx_callback(void * rx, uint16_t signal_index);
extern void bl00mbox_connect_rx_callback(void * rx, void * tx, uint16_t signal_index);
extern void bl00mbox_disconnect_mx_callback(void * chan, void * tx);
extern void bl00mbox_connect_mx_callback(void * chan, void * tx);

// get signal struct from a signal index
radspa_signal_t * bl00mbox_signal_get_by_index(radspa_t * plugin, uint16_t signal_index){
    return &(plugin->signals[signal_index]);
}

static inline bl00mbox_connection_t * conn_from_signal(bl00mbox_signal_t * signal){
    return (bl00mbox_connection_t *) signal->rignal->buffer;
}

static bool signal_is_input(bl00mbox_signal_t * signal){
    return signal->rignal->hints & RADSPA_SIGNAL_HINT_INPUT ? true : false;
}

static bool signal_is_output(bl00mbox_signal_t * signal){
    return signal->rignal->hints & RADSPA_SIGNAL_HINT_OUTPUT ? true : false;
}

static bool signal_equals(bl00mbox_signal_t * some, bl00mbox_signal_t * other){
    return (some->plugin == other->plugin) && (some->index == other->index);
}

static bool signals_are_connected(bl00mbox_signal_t * some, bl00mbox_signal_t * other){
    if(!some->rignal->buffer) return false;
    return some->rignal->buffer == other->rignal->buffer;
}

bool bl00mbox_signal_is_output(bl00mbox_signal_t * signal){
    return signal_is_output(signal);
}

bool bl00mbox_signal_is_input(bl00mbox_signal_t * signal){
    return signal_is_input(signal);
}

bl00mbox_connection_t * bl00mbox_connection_from_signal(bl00mbox_signal_t * signal){
    return conn_from_signal(signal);
}

uint16_t bl00mbox_channel_plugins_num(bl00mbox_channel_t * chan){
    return chan->plugins.len;
}

bl00mbox_array_t * bl00mbox_channel_collect_plugins(bl00mbox_channel_t * chan){
    unsigned int len = chan->plugins.len;
    bl00mbox_array_t * ret;
    ret = malloc(sizeof(bl00mbox_array_t) + len * sizeof(void *));
    if(!ret) return NULL;
    ret->len = len;

    bl00mbox_set_iter_t iter;
    bl00mbox_set_iter_start(&iter, &chan->plugins);
    bl00mbox_plugin_t * plugin;
    size_t i = 0;
    while((plugin = bl00mbox_set_iter_next(&iter))) ret->elems[i++] = plugin;
    return ret;
}

uint16_t bl00mbox_channel_conns_num(bl00mbox_channel_t * chan){
    return chan->connections.len;
}

uint16_t bl00mbox_channel_mixer_num(bl00mbox_channel_t * chan){
    return chan->roots.len;
}

bl00mbox_array_t * bl00mbox_channel_collect_connections_mx(bl00mbox_channel_t * chan){
    bl00mbox_array_t * ret;
    ret = malloc(sizeof(bl00mbox_array_t) + chan->roots.len * sizeof(void *));
    if(!ret) return NULL;

    ret->len = chan->roots.len;

    bl00mbox_set_iter_t iter;
    bl00mbox_set_iter_start(&iter, &chan->roots);
    bl00mbox_connection_t * conn;
    size_t i = 0;
    while((conn = bl00mbox_set_iter_next(&iter))){
        ret->elems[i++] = &conn->source;
    }
    return ret;
}

bl00mbox_array_t * bl00mbox_signal_collect_connections(bl00mbox_signal_t * signal){
    // caller has to free memory
    // return NULL -> OOM error
    bl00mbox_array_t * ret = NULL;
    bl00mbox_connection_t * conn = conn_from_signal(signal);
    if(!conn){
        ret = malloc(sizeof(bl00mbox_array_t));
        if(!ret) return NULL;
        ret->len = 0;
    } else if(signal->rignal->hints & RADSPA_SIGNAL_HINT_INPUT){
        ret = malloc(sizeof(bl00mbox_array_t) + sizeof(void *));
        if(!ret) return NULL;
        ret->len = 1;
        ret->elems[0] = &conn->source;
    } else {
        // TODO: add sentinel for channel mixer connection
        ret = malloc(sizeof(bl00mbox_array_t) + conn->subscribers.len * sizeof(void *));
        if(!ret) return NULL;
        ret->len = conn->subscribers.len;

        bl00mbox_set_iter_t iter;
        bl00mbox_set_iter_start(&iter, &conn->subscribers);
        bl00mbox_signal_t * sub;
        size_t i = 0;
        while((sub = bl00mbox_set_iter_next(&iter))){
            ret->elems[i++] = sub;
        }
    }
    return ret;
}

static void update_roots(bl00mbox_channel_t * chan){
    // create list of plugins to be rendered, i.e. all roots and always_actives
    bl00mbox_set_t * roots = &chan->roots; // content: bl00mbox_connection_t
    bl00mbox_set_t * always_render = &chan->always_render; // content: bl00mbox_plugin_t
    radspa_signal_t * output_rignal = &chan->channel_plugin->rugin->signals[1];
    
    // render_buffers are simple, just copy the content of the set and add the output plugin manually
    int num_render_buffers = roots->len + (output_rignal->buffer ? 1 : 0);
    bl00mbox_array_t * render_buffers = malloc(sizeof(bl00mbox_array_t) + sizeof(void *) * num_render_buffers);
    // for render_plugins there may be duplicates. we still allocate full memory for now
    int num_render_plugins = roots->len + always_render->len + (output_rignal->buffer ? 1 : 0);
    bl00mbox_array_t * render_plugins = malloc(sizeof(bl00mbox_array_t) + sizeof(void *) * num_render_plugins);
    if(!(render_buffers && render_plugins)) goto defer;

    size_t index = 0;

    bl00mbox_set_iter_t iter;
    // filling up mixer roots
    bl00mbox_set_iter_start(&iter, roots);
    bl00mbox_connection_t * conn;
    while((conn = bl00mbox_set_iter_next(&iter))){
        render_buffers->elems[index] = conn->buffer;
        render_plugins->elems[index] = conn->source.plugin;
        index++;
    }
    render_buffers->len = index;

    // if someone is connected to the channel_plugin output:
    // add to render_buffers/render_plugin
    if(output_rignal->buffer){
        render_buffers->elems[index] = output_rignal->buffer;
        render_buffers->len++;

        conn = output_rignal->buffer;
        bl00mbox_plugin_t * plugin = conn->source.plugin;
        bool is_duplicate = false;
        for(size_t rindex = 0; rindex < index; rindex++){
            if(render_plugins->elems[rindex] == plugin){
                is_duplicate = true;
                break;
            }
        }
        if(!is_duplicate){
            render_plugins->elems[index++] = conn->source.plugin;
        }
    }

    // adding always_render to the plugin list. those should be after the regular roots
    // because we might mess with natural render order otherwise
    size_t duplicate_index = index;
    bl00mbox_set_iter_start(&iter, always_render);
    bl00mbox_plugin_t * plugin;
    while((plugin = bl00mbox_set_iter_next(&iter))){
        // check for duplicates
        bool is_duplicate = false;
        for(size_t rindex = 0; rindex < duplicate_index; rindex++){
            if(render_plugins->elems[rindex] == plugin){
                is_duplicate = true;
                break;
            }
        }
        if(!is_duplicate) render_plugins->elems[index++] = plugin;
    }
    render_plugins->len = index;

    // if we overshot let's trim excess memory.
    if(index != num_render_plugins){
        bl00mbox_array_t * tmp = realloc(render_plugins, sizeof(bl00mbox_array_t) + sizeof(void *) * index);
        if(tmp) render_plugins = tmp;
    }

defer:
    if(!(render_plugins && render_buffers)){
        free(render_plugins);
        free(render_buffers);
        render_plugins = NULL;
        render_buffers = NULL;
        bl00mbox_log_error("out of memory, render list cleared")
    }
#ifdef BL00MBOX_DEBUG
    else {
        bl00mbox_log_info("new render data, %d plugins, %d buffers",
        (int) render_plugins->len, (int) render_buffers->len);
    }
#endif
    bl00mbox_array_t * render_plugins_prev = chan->render_plugins;
    bl00mbox_array_t * render_buffers_prev = chan->render_buffers;
    bl00mbox_take_lock(&chan->render_lock);
    chan->render_plugins = render_plugins;
    chan->render_buffers = render_buffers;
    bl00mbox_give_lock(&chan->render_lock);
    free(render_plugins_prev);
    free(render_buffers_prev);
}

bl00mbox_plugin_t * bl00mbox_plugin_create_unlisted(bl00mbox_channel_t * chan, radspa_descriptor_t * desc, uint32_t init_var){
    // doesn't instantiate, don't free
    bl00mbox_plugin_t * plugin = calloc(1, sizeof(bl00mbox_plugin_t));
    if(plugin == NULL) return NULL;
    radspa_t * rugin = desc->create_plugin_instance(init_var);
    if(rugin == NULL){ free(plugin); return NULL; }

    plugin->init_var = init_var;
    plugin->rugin = rugin;
    plugin->channel = chan;
    plugin->id = chan->plugin_id++;
    return plugin;
}

bl00mbox_plugin_t * bl00mbox_plugin_create(bl00mbox_channel_t * chan, uint32_t id, uint32_t init_var){
    // doesn't instantiate, don't free
    radspa_descriptor_t * desc = bl00mbox_plugin_registry_get_descriptor_from_id(id);
    if(desc == NULL) return NULL;

    bl00mbox_plugin_t * plugin = bl00mbox_plugin_create_unlisted(chan, desc, init_var);

    if(!bl00mbox_set_add_skip_unique_check(&chan->plugins, plugin)){
        plugin->rugin->descriptor->destroy_plugin_instance(plugin->rugin);
        free(plugin);
        return NULL;
    }

    bl00mbox_channel_event(chan);
    return plugin;
}

void bl00mbox_plugin_destroy(bl00mbox_plugin_t * plugin){
    bl00mbox_channel_t * chan = plugin->channel;

    // remove from parent
    if(* (plugin->parent_self_ref) != plugin){
        bl00mbox_log_error("plugin: parent_self_ref improper: plugin %s, %p, ref %p",
            plugin->rugin->descriptor->name, plugin, * (plugin->parent_self_ref));
    }
    * (plugin->parent_self_ref) = NULL;

    // disconnect all signals
    int num_signals = plugin->rugin->len_signals;
    for(int i = 0; i < num_signals; i++){
        bl00mbox_signal_t sig = {
            .index = i,
            .plugin = plugin,
            .rignal = &(plugin->rugin->signals[i])
        };
        bl00mbox_signal_disconnect(&sig);
    }

    // pop from sets
    bl00mbox_plugin_set_always_render(plugin, false);
    bl00mbox_set_remove(&chan->plugins, plugin);

    if(plugin == chan->channel_plugin) chan->channel_plugin = NULL;

    plugin->rugin->descriptor->destroy_plugin_instance(plugin->rugin);
    free(plugin);
}


static bl00mbox_connection_t * create_connection(bl00mbox_signal_t * source){
    if(!signal_is_output(source)) return NULL;
    bl00mbox_connection_t * ret = calloc(1, sizeof(bl00mbox_connection_t));
    if(ret == NULL) return NULL;
    ret->subscribers.key = signal_equals;
    memcpy(&ret->source, source, sizeof(bl00mbox_signal_t));

    if(!bl00mbox_set_add_skip_unique_check(&source->plugin->channel->connections, ret)){
        free(ret);
        return NULL;
    }

    bl00mbox_channel_t * chan = source->plugin->channel;
    bl00mbox_take_lock(&chan->render_lock);
    source->rignal->buffer = &ret->buffer;
    bl00mbox_give_lock(&chan->render_lock);
    return ret;
}

static bl00mbox_connection_t * weak_create_connection(bl00mbox_signal_t * source){
    bl00mbox_connection_t * conn = conn_from_signal(source);
    if(conn) return conn;
    conn = create_connection(source);
    return conn;
}

static bool weak_delete_connection(bl00mbox_connection_t * conn){
    // are there still active connections?
    if(conn->subscribers.len || conn->connected_to_mixer) return false;

    bl00mbox_channel_t * chan = conn->source.plugin->channel;

    // disconnect buffer from plugin
    bl00mbox_take_lock(&chan->render_lock);
    conn->source.rignal->buffer = NULL;
    bl00mbox_give_lock(&chan->render_lock);

    // remove from connections list
    if(!bl00mbox_set_remove(&chan->connections, conn)) bl00mbox_log_error("connection list corruption");

#ifdef BL00MBOX_DEBUG
    if(conn->subscribers.len) bl00mbox_log_error("subscribers nonempty");
#endif

    free(conn);
    return true;
}

bl00mbox_error_t bl00mbox_signal_connect_mx(bl00mbox_signal_t * signal){
    if(!signal_is_output(signal)) return BL00MBOX_ERROR_INVALID_CONNECTION;
    bl00mbox_channel_t * chan = signal->plugin->channel;

    bl00mbox_connection_t * conn = weak_create_connection(signal);
    if(!conn) goto failed;

    // check if already connected
    if(conn->connected_to_mixer) return BL00MBOX_ERROR_OK;
    conn->connected_to_mixer = true;
    if(!bl00mbox_set_add(&chan->roots, conn)) goto failed;

    update_roots(chan);
    bl00mbox_connect_mx_callback(chan->parent, signal->plugin->parent);
    bl00mbox_channel_event(chan);
    return BL00MBOX_ERROR_OK;

failed:
    if(conn){
        conn->connected_to_mixer = false;
        weak_delete_connection(conn);
    }
    bl00mbox_log_error("couldn't connect to mixer");
    return BL00MBOX_ERROR_OOM;
}

static void bl00mbox_signal_disconnect_mx(bl00mbox_signal_t * signal){
    if(!signal_is_output(signal)) return;
    bl00mbox_connection_t * conn = conn_from_signal(signal);
    if(conn == NULL) return; //not connected

    conn->connected_to_mixer = false;
    bl00mbox_channel_t * chan = signal->plugin->channel;
    bl00mbox_set_remove(&chan->roots, conn);
    update_roots(chan);

    bl00mbox_disconnect_mx_callback(chan->parent, signal->plugin->parent);
    weak_delete_connection(conn);
}

static void bl00mbox_signal_disconnect_rx(bl00mbox_signal_t * signal){
    if(!signal_is_input(signal)) return;

    // try to get connection and return if not connected
    bl00mbox_connection_t * conn = conn_from_signal(signal);
    if(!conn) return;

    bl00mbox_channel_t * chan = signal->plugin->channel;
    bl00mbox_take_lock(&chan->render_lock);
    signal->rignal->buffer = NULL;
    bl00mbox_give_lock(&chan->render_lock);

    if(signal->plugin->rugin->descriptor->id == BL00MBOX_CHANNEL_PLUGIN_ID) update_roots(chan);


    bl00mbox_set_remove(&conn->subscribers, signal);
    weak_delete_connection(conn);

    bl00mbox_disconnect_rx_callback(signal->plugin->parent, signal->index);
}

void bl00mbox_signal_disconnect_tx(bl00mbox_signal_t * signal){
    if(!signal_is_output(signal)) return;
    bl00mbox_connection_t * conn = conn_from_signal(signal);
    if(!conn) return;

    // disconnect from mixer
    if(conn->connected_to_mixer) bl00mbox_signal_disconnect_mx(signal);

    // disconnect all subscribers
    bl00mbox_set_iter_t iter;
    bl00mbox_set_iter_start(&iter, &conn->subscribers);
    bl00mbox_signal_t * sub;
    while((sub = bl00mbox_set_iter_next(&iter))){
        bl00mbox_signal_disconnect_rx(sub);
    }
}

void bl00mbox_signal_disconnect(bl00mbox_signal_t * signal){
    if(!conn_from_signal(signal)) return;
    if(signal_is_input(signal)){
        bl00mbox_signal_disconnect_rx(signal);
    }
    if(signal_is_output(signal)){
        bl00mbox_signal_disconnect_tx(signal);
        bl00mbox_signal_disconnect_mx(signal);
    }
    if(conn_from_signal(signal)) bl00mbox_log_error("connection persists after disconnect");
}

bl00mbox_error_t bl00mbox_signal_connect(bl00mbox_signal_t * some, bl00mbox_signal_t * other){
    // are signals on the same channel?
    if(some->plugin->channel != other->plugin->channel) return BL00MBOX_ERROR_INVALID_CONNECTION;
    bl00mbox_channel_t * chan = some->plugin->channel;

    // which one is input, which one is output?
    bl00mbox_signal_t * signal_rx;
    bl00mbox_signal_t * signal_tx;
    if(signal_is_input(some) && signal_is_output(other)){
        signal_rx = some;
        signal_tx = other;
    } else if(signal_is_input(other) && signal_is_output(some)){
        signal_rx = other;
        signal_tx = some;
    } else {
        return BL00MBOX_ERROR_INVALID_CONNECTION;
    }

    bl00mbox_connection_t * conn;
    if(!(conn = conn_from_signal(signal_tx))){
        if(!(conn = create_connection(signal_tx))) return BL00MBOX_ERROR_OOM;
    } else {
        if(signals_are_connected(signal_rx, signal_tx)) return BL00MBOX_ERROR_OK; // already connected
    }

    bl00mbox_signal_disconnect_rx(signal_rx);

    bl00mbox_signal_t * sub;

    sub = malloc(sizeof(bl00mbox_signal_t));
    if(!sub){
        weak_delete_connection(conn);
        return BL00MBOX_ERROR_OOM;
    }

    memcpy(sub, signal_rx, sizeof(bl00mbox_signal_t));

    bl00mbox_set_add(&conn->subscribers, sub);

    // we must block here else we could access the buffer of a constant signal
    // and think it's nonconst, which is bad
    bl00mbox_take_lock(&chan->render_lock);
    signal_rx->rignal->buffer = signal_tx->rignal->buffer;
    bl00mbox_give_lock(&chan->render_lock);

    if(signal_rx->plugin->rugin->descriptor->id == BL00MBOX_CHANNEL_PLUGIN_ID) update_roots(chan);

    bl00mbox_connect_rx_callback(signal_rx->plugin->parent, signal_tx->plugin->parent, signal_rx->index);

    bl00mbox_channel_event(chan);
    return BL00MBOX_ERROR_OK;
}

void bl00mbox_plugin_set_always_render(bl00mbox_plugin_t * plugin, bool value){
    bl00mbox_channel_t * chan = plugin->channel;
    if(plugin->always_render == value) return;
    plugin->always_render = value;

    if(value){
        bl00mbox_set_add(&chan->always_render, plugin);
    } else {
        bl00mbox_set_remove(&chan->always_render, plugin);
    }
    update_roots(chan);

    bl00mbox_channel_event(chan);
}

bl00mbox_error_t bl00mbox_signal_set_value(bl00mbox_signal_t * signal, int value){
    //while(signal->plugin->is_being_rendered) {};
    if(!signal_is_input(signal)) return BL00MBOX_ERROR_INVALID_CONNECTION;
    if(conn_from_signal(signal)) bl00mbox_signal_disconnect(signal);
    signal->rignal->value = value < -32767 ? -32767 : (value > 32767 ? 32767 : value);
    return BL00MBOX_ERROR_OK;
}

int16_t bl00mbox_signal_get_value(bl00mbox_signal_t * signal){
    //while(signal->plugin->is_being_rendered) {};
    return signal->rignal->buffer ? signal->rignal->buffer[0] : signal->rignal->value;
}
Original line number Diff line number Diff line
#pragma once
#define BL00MBOX_FLOW3R

//#define BL00MBOX_DEBUG

#ifdef BL00MBOX_FLOW3R
//#include "flow3r_bsp.h"
//#define BL00MBOX_MAX_BUFFER_LEN FLOW3R_BSP_AUDIO_DMA_BUFFER_SIZE
#define BL00MBOX_MAX_BUFFER_LEN 64
#define BL00MBOX_DEFAULT_CHANNEL_VOLUME 8192
#define BL00MBOX_AUTO_FOREGROUNDING
#define BL00MBOX_LOOPS_ENABLE
#define BL00MBOX_FREERTOS
#define BL00MBOX_ESPIDF
// note: this option relies on implementation details of the garbage
// collector, specifically the fact that it is stop-the-world and
// collects all unreachable objects it can find before it gives control
// back to micropython. changing it from stop-the-world to anything
// else is to our knowledge not possible without rewriting all mutators,
// so we consider this aspect future proof. also we see no reason to
// not collect all of them since sweeping is very fast, unless it is
// outsourced to a separate sweeping task, in which case this option
// may result in use-after-free, but we don't really see that happening
// anytime soon.
// if you want to use this option in such an environment however,
// setting a ChannelCore's callback to None before dropping all
// references to it solves the issue.
#define BL00MBOX_CALLBACKS_FUNSAFE
#endif
Original line number Diff line number Diff line
/*  Written in 2016 by David Blackman and Sebastiano Vigna (vigna@acm.org)

To the extent possible under law, the author has dedicated all copyright
and related and neighboring rights to this software to the public domain
worldwide. This software is distributed without any warranty.

See <http://creativecommons.org/publicdomain/zero/1.0/>. */

#include <stdint.h>

/* This is xoroshiro64* 1.0, our best and fastest 32-bit small-state
   generator for 32-bit floating-point numbers. We suggest to use its
   upper bits for floating-point generation, as it is slightly faster than
   xoroshiro64**. It passes all tests we are aware of except for linearity
   tests, as the lowest six bits have low linear complexity, so if low
   linear complexity is not considered an issue (as it is usually the
   case) it can be used to generate 32-bit outputs, too.

   We suggest to use a sign test to extract a random Boolean value, and
   right shifts to extract subsets of bits.

   The state must be seeded so that it is not everywhere zero. */


static inline uint32_t rotl(const uint32_t x, int k) {
	return (x << k) | (x >> (32 - k));
}

// mod1: state seed
static uint32_t s[2] = {420, 69};

//uint32_t next(void) {
uint32_t xoroshiro64star(void) {
    // mod2: changed name to avoid namespace collisions.
	const uint32_t s0 = s[0];
	uint32_t s1 = s[1];
	const uint32_t result = s0 * 0x9E3779BB;

	s1 ^= s0;
	s[0] = rotl(s0, 26) ^ s1 ^ (s1 << 9); // a, b
	s[1] = rotl(s1, 13); // c

	return result;
}
+12 −0
Original line number Diff line number Diff line
//SPDX-License-Identifier: CC0-1.0
#pragma once
#include <stdbool.h>
#include <stdint.h>

#define SAMPLE_RATE 48000

uint16_t bl00mbox_sources_count();
uint16_t bl00mbox_source_add(void* render_data, void* render_function);
void bl00mbox_source_remove(uint16_t index);
bool bl00mbox_audio_render(int16_t * rx, int16_t * tx, uint16_t len);
void bl00mbox_init(void);
Original line number Diff line number Diff line
//SPDX-License-Identifier: CC0-1.0
#pragma once
#include "bl00mbox_config.h"
#include "bl00mbox_os.h"
#include "bl00mbox_containers.h"

#include <stdio.h>
#include <math.h>
#include <string.h>
#include "radspa.h"
#include "radspa_helpers.h"

struct _bl00mbox_plugin_t;
struct _bl00mbox_connection_source_t;
struct _bl00mbox_channel_root_t;
struct _bl00mbox_channel_t;

extern int16_t * bl00mbox_line_in_interlaced;

// pointer is unique identifier, no memcpy of this!
typedef struct _bl00mbox_plugin_t{
    radspa_t * rugin; // radspa plugin
    char * name;
    uint32_t id; // unique number in channel to for UI purposes

    uint32_t render_pass_id; // may be used by host to determine whether recomputation is necessary
    uint32_t init_var; // init var that was used for plugin creation
    volatile bool is_being_rendered; // true if rendering the plugin is in progress, else false.
    bool always_render;
    struct _bl00mbox_channel_t * channel; // channel that owns the plugin

    void * parent;
    struct _bl00mbox_plugin_t ** parent_self_ref;
} bl00mbox_plugin_t;

// pointer is NOT unique identifier, memcpy allowed
typedef struct {
    bl00mbox_plugin_t * plugin;
    radspa_signal_t * rignal;
    int index;
} bl00mbox_signal_t;

typedef struct _bl00mbox_connection_t{ //child of bl00mbox_ll_t
    int16_t buffer[BL00MBOX_MAX_BUFFER_LEN]; // MUST stay on top of struct bc type casting! TODO: offsetof()
    bl00mbox_signal_t source;
    bl00mbox_set_t subscribers; // content: bl00mbox_signal_t;
    bool connected_to_mixer; // legacy thing, don't wanna sentinel subsribers
} bl00mbox_connection_t;

// pointer is unique identifier, no memcpy of this!
typedef struct _bl00mbox_channel_t{
    char * name;

    int32_t volume;
    bool background_mute_override;

    // secondary gain that the channel user is supposed to leave untouched so that the OS
    // can change gain too, for example for a system mixer. we still want to apply both in the
    // same pass, so we keep it here.
    int32_t sys_gain;

    // whether to keep track of the rms volume of the channel. adds a bit of cpu load, best
    // keep it off if not used.
    bool compute_rms;
    // we are storing the un-rooted value. this means that if you want the value in decibels
    // you have to only do the log operation and can skip the root as you can express roots
    // as divisions in the log domain which is much cheaper.
    uint32_t mean_square;
    // average output used for DC blocking.
    int32_t dc;

    uint32_t render_pass_id; // may be used by host to determine whether recomputation is necessary

    uint32_t plugin_id; // used to give each plugin in channel a unique identifier

    // we render all of these and add them up. it's a legacy thing from when we had a output mixer
    // but that kinda mixes poorly (heh) with our general API.
    bl00mbox_set_t roots; // content: bl00mbox_connection_t
    bl00mbox_set_t connections; // content: bl00mbox_connection_t
    bl00mbox_set_t always_render; // content: bl00mbox_plugin_t
    bl00mbox_set_t plugins; // content: bl00mbox_plugin_t

    bl00mbox_plugin_t * channel_plugin;

    bl00mbox_lock_t render_lock;
    // take .render_lock before changing these
    bl00mbox_array_t * render_plugins;
    bl00mbox_array_t * render_buffers;

    void * parent;
    struct _bl00mbox_channel_t ** parent_self_ref;
    struct _bl00mbox_channel_t ** weak_parent_self_ref;
} bl00mbox_channel_t;

void bl00mbox_audio_init();

bl00mbox_channel_t * bl00mbox_channel_create();
void bl00mbox_audio_plugin_render(bl00mbox_plugin_t * plugin);
bool bl00mbox_channel_get_foreground(bl00mbox_channel_t * chan);
void bl00mbox_channel_set_foreground(bl00mbox_channel_t * chan, bool enable);
void bl00mbox_channel_set_background_mute_override(bl00mbox_channel_t * chan, bool enable);
void bl00mbox_channel_clear(bl00mbox_channel_t * chan);
void bl00mbox_channel_destroy(bl00mbox_channel_t * chan);
void bl00mbox_channel_event(bl00mbox_channel_t * channel);
bl00mbox_array_t * bl00mbox_collect_channels(bool active);
Original line number Diff line number Diff line
#pragma once
#include "bl00mbox_os.h"

typedef struct _bl00mbox_ll_t {
    struct _bl00mbox_ll_t * next;
    void * content;
} bl00mbox_ll_t;

typedef struct {
    size_t len;
    void * elems[];
} bl00mbox_array_t;

typedef bool (* bl00mbox_set_key_t)(void *, void *);

// initialize all zeroed out except for content type
typedef struct {
    bl00mbox_ll_t * start;
    bl00mbox_set_key_t key;
    size_t len;
} bl00mbox_set_t;

typedef struct {
    bl00mbox_ll_t * next;
}bl00mbox_set_iter_t;

bool bl00mbox_set_contains(bl00mbox_set_t * set, void * content);
bool bl00mbox_set_add_skip_unique_check(bl00mbox_set_t * set, void * content);
bool bl00mbox_set_add(bl00mbox_set_t * set, void * content);
bool bl00mbox_set_remove(bl00mbox_set_t * set, void * content);

// removing from set during iteration is safe, adding is NOT
void bl00mbox_set_iter_start(bl00mbox_set_iter_t * iter, bl00mbox_set_t * set);
void * bl00mbox_set_iter_next(bl00mbox_set_iter_t * iter);

bl00mbox_array_t * bl00mbox_set_to_array(bl00mbox_set_t * set);
Original line number Diff line number Diff line
#pragma once
#include "bl00mbox_config.h"
#include <stdbool.h>

typedef enum {
    BL00MBOX_ERROR_OK = false,
    BL00MBOX_ERROR_OOM,
    BL00MBOX_ERROR_INVALID_CONNECTION,
    BL00MBOX_ERROR_INVALID_IDENTIFIER,
} bl00mbox_error_t;

#ifdef BL00MBOX_FREERTOS
#include "freertos/FreeRTOS.h"
#include "freertos/semphr.h"
typedef SemaphoreHandle_t bl00mbox_lock_t;
#endif

bool bl00mbox_create_lock(bl00mbox_lock_t * lock);
void bl00mbox_delete_lock(bl00mbox_lock_t * lock);
void bl00mbox_take_lock(bl00mbox_lock_t * lock);
void bl00mbox_give_lock(bl00mbox_lock_t * lock);

#ifdef BL00MBOX_DEBUG
void bl00mbox_wait();
#endif

#ifdef BL00MBOX_ESPIDF
#include "esp_log.h"
#define bl00mbox_log_error(txt, ...) ESP_LOGE("bl00mbox", txt, ##__VA_ARGS__);
#ifdef BL00MBOX_DEBUG
#define bl00mbox_log_info(txt, ...) ESP_LOGE("bl00mbox", txt, ##__VA_ARGS__);
#else
#define bl00mbox_log_info(txt, ...) ESP_LOGI("bl00mbox", txt, ##__VA_ARGS__);
#endif
#else
void bl00mbox_log_error(char * txt, ...);
void bl00mbox_log_info(char * txt, ...);
#endif
Original line number Diff line number Diff line
//SPDX-License-Identifier: CC0-1.0
#pragma once
#include "stdio.h"
#include "radspa.h"
#include "bl00mbox_os.h"
#include "bl00mbox_channel_plugin.h"

typedef struct _bl00mbox_plugin_registry_t{
    radspa_descriptor_t * descriptor;
    struct _bl00mbox_plugin_registry_t * next;
} bl00mbox_plugin_registry_t;

radspa_descriptor_t * bl00mbox_plugin_registry_get_descriptor_from_id(uint32_t id);
radspa_descriptor_t * bl00mbox_plugin_registry_get_descriptor_from_index(uint32_t index);
void bl00mbox_plugin_registry_init(void);
uint16_t bl00mbox_plugin_registry_get_plugin_num(void);
Original line number Diff line number Diff line
//SPDX-License-Identifier: CC0-1.0
#pragma once

#include <stdio.h>
#include <math.h>
#include <string.h>

#include "bl00mbox_plugin_registry.h"
#include "bl00mbox_audio.h"
#include "bl00mbox_os.h"
#include "bl00mbox_containers.h"

#include <stdint.h>
#include "bl00mbox_audio.h"
#include "radspa_helpers.h"

// lazy 2nd error channel: pointer return types resulting in NULL means OOM

uint16_t bl00mbox_channel_plugins_num(bl00mbox_channel_t * chan);
uint16_t bl00mbox_channel_conns_num(bl00mbox_channel_t * chan);
uint16_t bl00mbox_channel_mixer_num(bl00mbox_channel_t * chan);
bl00mbox_array_t * bl00mbox_channel_collect_plugins(bl00mbox_channel_t * chan);
bl00mbox_array_t * bl00mbox_channel_collect_connections_mx(bl00mbox_channel_t * chan);

bl00mbox_plugin_t * bl00mbox_plugin_create_unlisted(bl00mbox_channel_t * chan, radspa_descriptor_t * desc, uint32_t init_var);
bl00mbox_plugin_t * bl00mbox_plugin_create(bl00mbox_channel_t * chan, uint32_t id, uint32_t init_var);
void bl00mbox_plugin_destroy(bl00mbox_plugin_t * plugin);
void bl00mbox_plugin_set_always_render(bl00mbox_plugin_t * plugin, bool value);

bl00mbox_error_t bl00mbox_signal_set_value(bl00mbox_signal_t * signal, int value);
int16_t bl00mbox_signal_get_value(bl00mbox_signal_t * signal);
bl00mbox_error_t bl00mbox_signal_connect(bl00mbox_signal_t * some, bl00mbox_signal_t * other);
bl00mbox_error_t bl00mbox_signal_connect_mx(bl00mbox_signal_t * some);
void bl00mbox_signal_disconnect(bl00mbox_signal_t * signal);
bl00mbox_array_t * bl00mbox_signal_collect_connections(bl00mbox_signal_t * signal);

bl00mbox_connection_t * bl00mbox_connection_from_signal(bl00mbox_signal_t * signal);

bool bl00mbox_signal_is_input(bl00mbox_signal_t * signal);
bool bl00mbox_signal_is_output(bl00mbox_signal_t * signal);
Original line number Diff line number Diff line
# SPDX-License-Identifier: CC0-1.0

from bl00mbox._user import *
import bl00mbox._patches as patches
import bl00mbox._helpers as helpers
from bl00mbox._plugins import plugins
Original line number Diff line number Diff line
# SPDX-License-Identifier: CC0-1.0
import time


def terminal_scope(
    signal,
    signal_min=-32767,
    signal_max=32767,
    delay_ms=20,
    width=80,
    fun=None,
    fun_ms=None,
):
    """give it a signal and show it on terminal"""
    if signal_max <= signal_min:
        return
    ms_counter = 0
    fun_counter = 0
    if fun != None:
        fun()
    while True:
        if fun != None:
            if fun_ms != None:
                if fun_ms <= fun_counter:
                    fun()
                    fun_counter = fun_counter % fun_ms
        raw_val = signal.value
        ret = f"{ms_counter:06d}"
        if raw_val == -32768:
            ret += " [" + "?" * width + "] INVALID"
        else:
            val = int((width * (raw_val - signal_min)) / (signal_max - signal_min))
            if val > width:
                val = width
            if val < 0:
                val = 0
            ret += " [" + "X" * val + "." * (width - val) + "]"
            percent = int(100 * val / width)
            ret += f" {percent:02d}%"
        print(ret)
        time.sleep_ms(delay_ms)
        ms_counter += delay_ms
        fun_counter += delay_ms


# terminal_scope(a.env.signals.output, 0, fun = a.start, fun_ms = 1000)


def sct_to_note_name(sct):
    sct = sct - 18367 + 100
    octave = ((sct + 9 * 200) // 2400) + 4
    tones = ["A", "Bb", "B", "C", "Db", "D", "Eb", "E", "F", "Gb", "G", "Ab"]
    tone = tones[(sct // 200) % 12]
    return tone + str(octave)


def note_name_to_sct(name):
    tones = ["A", "Bb", "B", "C", "Db", "D", "Eb", "E", "F", "Gb", "G", "Ab"]
    semitones = tones.index(name[0])
    if semitones > 2:
        semitones -= 12
    if name[1] == "b":
        octave = int(name[2:])
        semitones -= 1
    elif name[1] == "#":
        octave = int(name[2:])
        semitones += 1
    else:
        octave = int(name[1:])
    return 18367 + (octave - 4) * 2400 + (200 * semitones)


def sct_to_freq(sct):
    return 440 * 2 ** ((sct - 18367) / 2400)
Original line number Diff line number Diff line
#include "bl00mbox_channel_plugin.h"
#include "bl00mbox_config.h"

radspa_descriptor_t bl00mbox_channel_plugin_desc = {
    .name = "channel",
    .id = BL00MBOX_CHANNEL_PLUGIN_ID,
    .description = "bl00mbox channel signals",
    .create_plugin_instance = bl00mbox_channel_plugin_create,
    .destroy_plugin_instance = radspa_standard_plugin_destroy
};

// TODO: at this point we CANNOT just forward the same buffer pointer to every client because the buffer
// pointer serves as a channel-specific source plugin identifier, so we need to memcpy the line in.
// this could be faster at some point by adding a special case but we don't wanna think about it now.

typedef struct {
    int16_t buffer[BL00MBOX_MAX_BUFFER_LEN];
    uint32_t buffer_render_pass_id;
    int16_t value;
    int16_t value_render_pass_id;
} line_in_singleton_t;

static line_in_singleton_t line_in;

static inline void update_line_in_buffer(uint16_t num_samples, uint32_t render_pass_id){
    if(line_in.buffer_render_pass_id == render_pass_id) return;
    for(uint16_t i = 0; i < num_samples; i++){
        int32_t val = bl00mbox_line_in_interlaced[2*i];
        val += bl00mbox_line_in_interlaced[2*i+1];
        val = radspa_clip(val>>1);
        line_in.buffer[i] = val;
    }
    line_in.value = line_in.buffer[0];
    line_in.value_render_pass_id = render_pass_id;
    line_in.buffer_render_pass_id = render_pass_id;
}

static inline void update_line_in_value(uint32_t render_pass_id){
    if(line_in.value_render_pass_id == render_pass_id) return;
    int32_t val = bl00mbox_line_in_interlaced[0];
    val += bl00mbox_line_in_interlaced[1];
    val = radspa_clip(val>>1);
    line_in.value = val;
    line_in.value_render_pass_id = render_pass_id;
}

void bl00mbox_channel_plugin_run(radspa_t * channel_plugin, uint16_t num_samples, uint32_t render_pass_id){
    if(!bl00mbox_line_in_interlaced) return;

    // handle line in signal, only render full if requested
    radspa_signal_t * input_sig = radspa_signal_get_by_index(channel_plugin, 0);
    if(input_sig->buffer){
        update_line_in_buffer(num_samples, render_pass_id);
        memcpy(input_sig->buffer, line_in.buffer, sizeof(int16_t) * num_samples);
    }
    // do NOT render output here, if somebody has requested channel this would be too early
    // we're accessing the source buffer directly if present to avoid needing memcpy
}

void bl00mbox_channel_plugin_update_values(radspa_t * channel_plugin, uint32_t render_pass_id){
    update_line_in_value(render_pass_id);
    radspa_signal_t * input_sig = radspa_signal_get_by_index(channel_plugin, 0);
    input_sig->value = line_in.value;
}

radspa_t * bl00mbox_channel_plugin_create(uint32_t init_var){
    radspa_t * channel_plugin = radspa_standard_plugin_create(&bl00mbox_channel_plugin_desc, 2, 0, 0);
    if(!channel_plugin) return NULL;
    channel_plugin->render = bl00mbox_channel_plugin_run;
    radspa_signal_set(channel_plugin, 0, "line_in", RADSPA_SIGNAL_HINT_OUTPUT, 0);
    radspa_signal_set(channel_plugin, 1, "line_out", RADSPA_SIGNAL_HINT_INPUT, 0);
    return channel_plugin;
}
Original line number Diff line number Diff line
#pragma once
#include "radspa.h"
#include "radspa_helpers.h"
// SPECIAL REQUIREMENTS
#include "bl00mbox_audio.h"

#define BL00MBOX_CHANNEL_PLUGIN_ID 4002

extern radspa_descriptor_t bl00mbox_channel_plugin_desc;
radspa_t * bl00mbox_channel_plugin_create(uint32_t init_var);
void bl00mbox_channel_plugin_run(radspa_t * channel_plugin, uint16_t num_samples, uint32_t render_pass_id);

void bl00mbox_channel_plugin_update_values(radspa_t * channel_plugin, uint32_t render_pass_id);
Original line number Diff line number Diff line
#pragma once
#include "radspa.h"
#include "radspa_helpers.h"
// SPECIAL REQUIREMENTS
#include "bl00mbox_audio.h"

extern radspa_descriptor_t bl00mbox_line_in_desc;
radspa_t * bl00mbox_line_in_create(uint32_t init_var);
void bl00mbox_line_in_run(radspa_t * line_in, uint16_t num_samples, uint32_t render_pass_id);
Original line number Diff line number Diff line
#pragma once
#include <radspa.h>
#include <radspa_helpers.h>

extern radspa_descriptor_t ampliverter_desc;
radspa_t * ampliverter_create(uint32_t init_var);
void ampliverter_run(radspa_t * osc, uint16_t num_samples, uint32_t render_pass_id);
Original line number Diff line number Diff line
#pragma once
#include <radspa.h>
#include <radspa_helpers.h>

extern radspa_descriptor_t buffer_desc;
radspa_t * buffer_create(uint32_t init_var);
void buffer_run(radspa_t * buffer, uint16_t num_samples, uint32_t render_pass_id);
Original line number Diff line number Diff line
#pragma once
#include <radspa.h>
#include <radspa_helpers.h>

typedef struct {
    int32_t read_head_position;
    int32_t write_head_position;
    int32_t max_delay;
    int32_t time_prev;
} delay_data_t;

extern radspa_descriptor_t delay_desc;
radspa_t * delay_create(uint32_t init_var);
void delay_run(radspa_t * osc, uint16_t num_samples, uint32_t render_pass_id);