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
  • 89-apps-should-be-able-to-specify-if-they-want-wifi-to-be-disabled-when-entering-them
  • 9Rmain
  • allow-reloading-sunmenu
  • always-have-a-wifi-instance
  • anon/gpndemo
  • anon/update-sim
  • anon/webflasher
  • app_text_viewer
  • audio_input
  • audio_io
  • blm_dev_chan
  • ch3/bl00mbox_docs
  • ci-1690580595
  • dev_p4
  • dev_p4-iggy
  • dev_p4-iggy-rebased
  • dx/dldldld
  • dx/fb-save-restore
  • dx/hint-hint
  • dx/jacksense-headset-mic-only
  • events
  • fil3s-limit-filesize
  • fil3s-media
  • fpletz/flake
  • gr33nhouse-improvements
  • history-rewrite
  • icon-flower
  • iggy/stemming
  • iggy/stemming_merge
  • led_fix_fix
  • main
  • main+schneider
  • media_has_video_has_audio
  • micropython_api
  • mixer2
  • moon2_demo_temp
  • moon2_migrate_apps
  • more-accurate-battery
  • pippin/ctx_sprite_sheet_support
  • pippin/display-python-errors-on-display
  • pippin/make_empty_drawlists_skip_render_and_blit
  • pippin/more-accurate-battery
  • pippin/tcp_redirect_hack
  • pippin/tune_ctx_config_update_from_upstream
  • pippin/uhm_flash_access_bust
  • pressable_bugfix
  • py_only_update_fps_overlay_when_changing
  • q3k/doom-poc
  • q3k/render-to-texture
  • rahix/flow3rseeds
  • raw_captouch_new
  • raw_captouch_old
  • release/1.0.0
  • release/1.1.0
  • release/1.1.1
  • release/1.2.0
  • release/1.3.0
  • release/1.4.0
  • restore_blit
  • return_of_melodic_demo
  • rev4_micropython
  • schneider/application-remove-name
  • schneider/bhi581
  • schneider/factory_test
  • schneider/recovery
  • scope_hack
  • sdkconfig-spiram-tinyusb
  • sec/auto-nick
  • sec/blinky
  • sector_size_512
  • shoegaze-fps
  • smaller_gradient_lut
  • store_delta_ms_and_ins_as_class_members
  • task_cleanup
  • uctx-wip
  • w1f1-in-sim
  • widgets_draw
  • wifi-json-error-handling
  • wip-docs
  • wip-tinyusb
  • 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
  • 9Rmain
  • anon/gpndemo
  • anon/update-sim
  • anon/webflasher
  • audio_input
  • audio_io
  • bl00mbox
  • bl00mbox_old
  • captouch-threshold
  • ch3/bl00mbox_docs
  • ci-1690580595
  • compressor
  • dev_p4
  • dev_p4-iggy
  • dev_p4-iggy-rebased
  • dos
  • dos-main-patch-50543
  • events
  • fm_fix
  • fm_fix2
  • fpletz/flake
  • history-rewrite
  • icon-flower
  • iggy/stemming
  • iggy/stemming_merge
  • json-error
  • main
  • main+schneider
  • media-buf
  • micropython_api
  • moon2_applications
  • moon2_demo_temp
  • moon2_gay_drums
  • passthrough
  • phhw
  • pippin/display-python-errors-on-display
  • pippin/make_empty_drawlists_skip_render_and_blit
  • pippin/media_framework
  • pippin/uhm_flash_access_bust
  • pressable_bugfix
  • q3k/doom-poc
  • rahix/big-flow3r
  • rahix/flow3rseeds
  • raw_captouch_new
  • raw_captouch_old
  • release/1.0.0
  • release/1.1.0
  • release/1.1.1
  • rev4_micropython
  • schneider/application-remove-name
  • schneider/bhi581
  • schneider/factory_test
  • schneider/recovery
  • scope
  • scope_hack
  • sdkconfig-spiram-tinyusb
  • sec/auto-nick
  • sec/blinky
  • simtest
  • slewtest
  • t
  • test
  • test2
  • uctx-wip
  • view-think
  • vm-pending
  • vsync
  • wave
  • wip-docs
  • wip-tinyusb
  • 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
83 results
Show changes
424 files
+ 49170
11831
Compare changes
  • Side-by-side
  • Inline

Files

+8 −0
Original line number Diff line number Diff line
@@ -12,9 +12,17 @@ __pycache__
# editor crud
.vscode
*swp
*~

# Python
.venv
/venv/

# sphinx
docs/_build/

/tools/mypy.sh

# bl00mbox docs
components/bl00mbox/docs/
components/bl00mbox/public/
+34 −29
Original line number Diff line number Diff line
@@ -5,11 +5,12 @@ stages:

variables:
  GIT_SUBMODULE_STRATEGY: recursive
  GIT_DEPTH: 0

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

clang-tidy:
  stage: check
@@ -21,21 +22,6 @@ clang-tidy:
    reports:
      codequality: cqual.json

mypy:
  stage: check
  variables:
    MYPYPATH: python_payload/mypystubs
  script:
    - "set +e +o pipefail"
    - "bash tools/mypy.sh; result=$?"
    - "python3 tools/codequal-report.py mypy warnings.txt > cqual.json"
    - "set -e -o pipefail"
    - "[ $result == 0 ]"
  artifacts:
    when: always
    reports:
      codequality: cqual.json

format:
  stage: check
  script:
@@ -46,29 +32,50 @@ format:
build:
  stage: build
  script:
    - idf.py -g c23 build
    - 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: 'C23 ELF'
    paths: ['build/flow3r.elf']
    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
    - python3 sim/run.py --screenshot
  artifacts:
    expose_as: 'Smulator Screenshot'
    expose_as: 'Simulator Screenshot'
    paths: ['flow3r.png']
    expire_in: 5 hours

pages:
  stage: deploy
  only:
    - main
  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 html
    - mv _build/html ../public
    - 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
@@ -78,10 +85,8 @@ dist:
  variables:
    # Force a full clone to make version machinery work.
    GIT_STRATEGY: clone
  only:
    - /^v\/[0-9]+\.[0-9]+\.[0-9]+.*$/
    - /^release\/[0-9]+\.[0-9]+\.[0-9]+$/
    - tags
  rules:
    - if: $CI_COMMIT_TAG
  script:
    - bash tools/dist.sh
  artifacts:
+222 −3
Original line number Diff line number Diff line
@@ -6,8 +6,224 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).

## [Unreleased]

## [1.1.1] - 2023-08-17
## [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

@@ -31,7 +247,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).

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

### Fixed
- Fixed PNG without alpha and JPEG support by enabling `CTX_FORMAT_RGB8`.
@@ -47,7 +263,10 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
Initial Release


[unreleased]: https://git.flow3r.garden/flow3r/flow3r-firmware/-/compare/v1.1.0...main
[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
+2 −0
Original line number Diff line number Diff line
@@ -11,9 +11,11 @@ project(flow3r)
# 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)

COPYING

0 → 100644
+674 −0

File added.

Preview size limit exceeded, changes collapsed.

+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;
}
Original line number Diff line number Diff line
Checks: '-clang-analyzer-security.insecureAPI.DeprecatedOrUnsafeBufferHandling,-clang-diagnostic-deprecated-declarations,-clang-diagnostic-incompatible-pointer-types,-clang-analyzer-core.NullDereference'
Checks: '-*,clang-analyzer-osx.SecKeychainAPI'
Original line number Diff line number Diff line
@@ -5,31 +5,40 @@ idf_component_register(
        bl00mbox.c
        bl00mbox_audio.c
        bl00mbox_user.c
        bl00mbox_os.c
        bl00mbox_plugin_registry.c
        bl00mbox_radspa_requirements.c
        plugins/osc_fm.c
        plugins/env_adsr.c
        plugins/ampliverter.c
        plugins/sampler.c
        plugins/delay.c
        plugins/flanger.c
        plugins/multipitch.c
        plugins/sequencer.c
        plugins/noise.c
        plugins/noise_burst.c
        plugins/distortion.c
        plugins/lowpass.c
        plugins/mixer.c
        plugins/slew_rate_limiter.c
        plugins/bl00mbox/bl00mbox_line_in.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
        plugins/bl00mbox_specific
        radspa
        radspa/standard_plugin_lib
        extern
    REQUIRES
        st3m
        config
)
+3 −0
Original line number Diff line number Diff line
# documentation

https://moon2embeddedaudio.gitlab.io/bl00mbox/main/
Original line number Diff line number Diff line
@@ -2,10 +2,8 @@
#include "bl00mbox.h"
#include "bl00mbox_plugin_registry.h"
#include "bl00mbox_audio.h"
#include "st3m_audio.h"

void bl00mbox_init(){
    bl00mbox_plugin_registry_init();
    st3m_audio_set_player_function(bl00mbox_audio_render);
    bl00mbox_channels_init();
    bl00mbox_audio_init();
}
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"

bl00mbox_plugin_registry_t * bl00mbox_plugin_registry = NULL;
uint16_t bl00mbox_plugin_registry_len = 0;
bool bl00mbox_plugin_registry_is_initialized = false;
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){
        printf("too many plugins registered");
        abort();
        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 == NULL){ printf("bl00mbox: no memory for plugin list"); abort(); }
    if(!p){
        bl00mbox_log_error("no memory for plugin list");
        return;
    }
    p->descriptor = descriptor;
    p->next = NULL;

@@ -22,7 +28,13 @@ static void plugin_add(radspa_descriptor_t * descriptor){
    if(plast == NULL){
        bl00mbox_plugin_registry = p;
    } else {
        while(plast->next != NULL){ plast = plast->next; }
        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++;
@@ -52,7 +64,7 @@ radspa_descriptor_t * bl00mbox_plugin_registry_get_descriptor_from_index(uint32_
    for(uint16_t i = 0; i < index; i++){
        p = p->next;
        if(p == NULL){
            printf("bl00mbox: plugin list length error");
            bl00mbox_log_error("bl00mbox: plugin list length error");
            abort();
        }
    }
@@ -67,7 +79,7 @@ radspa_descriptor_t * bl00mbox_plugin_registry_get_id_from_index(uint32_t index)
    for(uint16_t i = 0; i < index; i++){
        p = p->next;
        if(p == NULL){
            printf("bl00mbox: plugin list length error");
            bl00mbox_log_error("bl00mbox: plugin list length error");
            abort();
        }
    }
@@ -81,17 +93,18 @@ radspa_descriptor_t * bl00mbox_plugin_registry_get_id_from_index(uint32_t index)
 * - 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 (but will call abort() if no memory is available),
 * 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"
@@ -100,24 +113,35 @@ radspa_descriptor_t * bl00mbox_plugin_registry_get_id_from_index(uint32_t index)
#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;
    plugin_add(&osc_fm_desc);
    plugin_add(&ampliverter_desc);
    plugin_add(&env_adsr_desc);   
    plugin_add(&delay_desc);   
    plugin_add(&lowpass_desc);   
    // 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(&distortion_desc);
    plugin_add(&mixer_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(&multipitch_desc);
    plugin_add(&bl00mbox_line_in_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, uint16_t num_samples){
    bl00mbox_bud_t * bud = ((bl00mbox_connection_t *) buf)->source_bud;
    bl00mbox_audio_bud_render(bud, num_samples);
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;
}

@@ -58,41 +58,4 @@ uint32_t radspa_sct_to_rel_freq(int16_t sct, int16_t undersample_pow){
    return ret;
}

int16_t radspa_clip(int32_t a){
    if(a > 32767){
         return 32767;
    } else if(a < -32767){
         return -32767;
    }
    return a;
}

int16_t radspa_add_sat(int32_t a, int32_t b){ return radspa_clip(a+b); }
int32_t radspa_mult_shift(int32_t a, int32_t b){ return radspa_clip((a*b)>>15); }
int32_t radspa_gain(int32_t a, int32_t b){ return radspa_clip((a*b)>>12); }

int16_t radspa_trigger_start(int16_t velocity, int16_t * hist){
    int16_t ret = ((* hist) > 0) ? -velocity : velocity;
    (* hist) = ret;
    return ret;
}

int16_t radspa_trigger_stop(int16_t * hist){
    (* hist) = 0;
    return 0;
}

int16_t radspa_trigger_get(int16_t trigger_signal, int16_t * hist){
    int16_t ret = 0;
    if((!trigger_signal) && (* hist)){ //stop
        ret = -1;
    } else if(trigger_signal > 0 ){
        if((* hist) <= 0) ret = trigger_signal;
    } else if(trigger_signal < 0 ){
        if((* hist) >= 0) ret = -trigger_signal;
    }
    (* hist) = trigger_signal;
    return ret;
}

int16_t radspa_random(){ return xoroshiro64star()>>16; }
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
@@ -8,9 +8,5 @@
uint16_t bl00mbox_sources_count();
uint16_t bl00mbox_source_add(void* render_data, void* render_function);
void bl00mbox_source_remove(uint16_t index);
void bl00mbox_audio_render(int16_t * rx, int16_t * tx, uint16_t len);

// TEMP
void bl00mbox_player_function(int16_t * rx, int16_t * tx, uint16_t len);

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
#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 <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);
+2483 −2498

File changed.

Preview size limit exceeded, changes collapsed.