agentleFS
software-mansionsoftware-mansion/react-native-audio-api/.claude/skills/turbo-modules/SKILL.md

turbo-modules

Skill864 starsChanged 7 days agoMITView on GitHub

TurboModule spec, JSI binding injection, and platform native module entry points. Use when adding a new native method to NativeAudioAPIModule.ts, wiring a new top-level HostObject through AudioAPIModuleInstaller, debugging "native module not found" or "undefined is not a function" for a global, or understanding the install() bootstrap flow on iOS and Android. Trigger phrases: "native module not found", "install()", "NativeAudioAPIModule", "injectJSIBindings", "AudioAPIModuleInstaller", "JSI global", "TurboModule spec", "module bootstrap", "undefined is not a function".

The file

We split this skill into the rules it gives an agent

5 rules. About 0 are common, 0 are distinctive, and 5 are very specific to this project.

  • ≈0

    Common · estimate

    Many files like this have a rule of this kind.

  • ≈0

    Distinctive · estimate

    This author's own choices. Worth a look.

  • 5

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Very specific:

    Rule: if it needs AVAudioSession, AudioManager, MediaSession, or OS permissions → TurboModule.

    line 17
  2. Very specific:

    After install() returns, TypeScript code can call globalThis.createAudioContext(sampleRate) and get back a HostObject — no serialization, …

    line 71
  3. Very specific:

    Adding a new top-level global: add a static jsi::Function getCreateXxxFunction(...) private method and a setProperty("createXxx", ...) call …

    line 117
  4. Very specific:

    Update src/AudioAPIModule/globals.d.ts in the same change.

    line 122
  5. Very specific:

    Create AudioEventHandlerRegistry (owns JS callbacks, needs runtime + callInvoker)

    line 143

≈ “Common” is an estimate: at least 1 in 5 of the 408,460 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
SKILL.md

Skill: TurboModules & JSI Installation

When to Use TurboModule vs HostObjects

Rule: if it needs AVAudioSession, AudioManager, MediaSession, or OS permissions → TurboModule. If it's audio processing → HostObject installed by AudioAPIModuleInstaller.

Use TurboModule methodUse HostObject property/method
Platform system APIs (audio session, permissions, notifications, device routing)All audio graph operations (create/connect/disconnect nodes, AudioParam, scheduling)
One-time initialization (install)Real-time playback control
Features that need native UI thread or system callbacksFeatures that only need the JSI runtime
Android-only or iOS-only behaviorCross-platform C++ engine behavior

Most audio nodes do not need a TurboModule method — they are exposed entirely through JSI HostObjects injected by injectJSIBindings.


Reference


The Big Picture

Most audio functionality is exposed not through TurboModule method calls but through JSI HostObjects placed directly on the JS global object. The TurboModule's job is narrow:

  1. Be available early via the standard RN module system
  2. Provide install() — one synchronous call that injects HostObject factories onto globalThis
  3. Expose platform-specific system APIs (audio session, permissions, notifications, devices) that cannot be done through pure JSI
flowchart TD
  A["JS: NativeAudioAPIModule.install()"]

  subgraph ios["iOS — AudioAPIModule.mm"]
    B["init AudioSessionManager · AudioEngine\nget jsi::Runtime* · CallInvoker"]
  end

  subgraph android["Android — AudioAPIModule.kt + .cpp"]
    C["MediaSessionManager.initialize()\nJNI: injectJSIBindings()"]
  end

  D["AudioAPIModuleInstaller::injectJSIBindings\n(runtime, callInvoker, eventRegistry, uiRuntime?)"]

  subgraph globals["globalThis — set by injectJSIBindings"]
    G["createAudioContext\ncreateOfflineAudioContext\ncreateAudioRecorder\ncreateAudioBuffer\ncreateAudioDecoder\ncreateAudioFileUtils\nAudioEventEmitter HostObject"]
  end

  A --> ios
  A --> android
  ios --> D
  android --> D
  D --> globals

After install() returns, TypeScript code can call globalThis.createAudioContext(sampleRate) and get back a HostObject — no serialization, no bridge round-trip.


TurboModule Spec (src/specs/NativeAudioAPIModule.ts)

Defines the TypeScript interface for the native module. Codegen (React Native's codegen) generates the native binding glue from this file.

interface Spec extends TurboModule {
  install(): boolean;                           // synchronous — MUST run first
  getDevicePreferredSampleRate(): number;       // synchronous
  setAudioSessionActivity(enabled: boolean): Promise<boolean>;
  setSystemOptions(...): void;
  observeAudioInterruptions(focusType, enabled): void;
  requestRecordingPermissions(): Promise<PermissionStatus>;
  // ... audio devices, notifications ...
}

const NativeAudioAPIModule = TurboModuleRegistry.get<Spec>('AudioAPIModule')!;

install() is synchronous (RCT_EXPORT_BLOCKING_SYNCHRONOUS_METHOD on iOS, override fun install(): Boolean on Android). It must complete before the app tries to use any audio API. It is called once during module bootstrap in src/AudioAPIModule/index.ts.

Web mock (src/specs/NativeAudioAPIModule.web.ts): on the web platform, the whole spec is mocked with no-ops and resolved promises (e.g. permissions always return 'Granted'). This file replaces the native spec at bundle time for web builds.


AudioAPIModuleInstaller (common/cpp/audioapi/AudioAPIModuleInstaller.h)

The single C++ class that owns JSI injection. It is #include-d by both iOS (.mm) and Android (.cpp) native modules, keeping the injection logic platform-agnostic.

class AudioAPIModuleInstaller {
 public:
  static void injectJSIBindings(
      jsi::Runtime *jsiRuntime,
      const std::shared_ptr<react::CallInvoker> &jsCallInvoker,
      const std::shared_ptr<IAudioEventHandlerRegistry> &audioEventHandlerRegistry);
};

Each get*Function() private method creates a jsi::Function via jsi::Function::createFromHostFunction(). The lambda captures the dependencies it needs (jsCallInvoker, audioEventHandlerRegistry) by value (shared_ptr). The header is header-only; there is no .cpp.

RN_AUDIO_API_ENABLE_WORKLETS is gone. createAudioContext takes sample rate, an optional latency-hint string, and an optional Android output-profile string. It does not take a worklet runtime.

Adding a new top-level global: add a static jsi::Function getCreateXxxFunction(...) private method and a setProperty("createXxx", ...) call in injectJSIBindings. This is only needed for objects that JS creates directly (not objects created as properties of another HostObject).

Construction-time options (e.g. new AudioRecorder({ androidInputPreset, iosVoiceProcessing })) travel as positional args of these factory functions — there is no options object and no TurboModule method involved. Three rules:

  • Parse defensively — if (count > N && args[N].isBool()) — and keep the no-arg behavior as the default, so an older JS bundle against a newer binary still works.
  • Update src/AudioAPIModule/globals.d.ts in the same change; it is the only type contract for these globals.
  • Platform-specific options are passed to both platforms and consumed by the #ifdef ANDROID branch in the HostObject constructor; the other platform ignores its counterpart. Name them with the platform prefix (androidInputPreset, iosVoiceProcessing) so the asymmetry is visible from JS.

iOS Native Module (AudioAPIModule.mm)

Uses ObjC++ with RCT_EXPORT_MODULE and RCT_EXPORT_BLOCKING_SYNCHRONOUS_METHOD.

Key steps in install:

  1. Allocate platform managers (AudioSessionManager, AudioEngine, SystemNotificationManager, NotificationRegistry)
  2. Get jsi::Runtime * from the bridge: reinterpret_cast<facebook::jsi::Runtime *>(self.bridge.runtime)
  3. Get CallInvoker — different paths for old Bridge vs New Architecture:
    #if defined(RCT_NEW_ARCH_ENABLED)
      auto jsCallInvoker = _callInvoker.callInvoker;
    #else
      auto jsCallInvoker = self.bridge.jsCallInvoker;
    #endif
  4. Create AudioEventHandlerRegistry (owns JS callbacks, needs runtime + callInvoker)
  5. Call AudioAPIModuleInstaller::injectJSIBindings(...)

Lazy AVAudioEngine invariant: allocating the AudioEngine ObjC object at install does NOT create the underlying AVAudioEngine. It is created on demand by createAudioEngineIfNeeded (first node attach, engine start, rebuild), so apps that only use session management and notifications never allocate it. Every reader of self.audioEngine inside AudioEngine.mm must either nil-guard or call createAudioEngineIfNeeded first, and system-driven restart paths (restartAudioEngine) must not resurrect an engine when there is no tracked graph.

Teardown order on reload: invalidate cleans up AudioEngine (nils sharedInstance) and AudioSessionManager (nils audioSession) before the JS runtime destroys its HostObjects. So -[AudioEngine cleanup] stops the active recorder through ActiveRecorderHandle (before taking _engineLock) and the later ~AudioRecorderHostObject stop finds the slot empty. Native recorder/player paths keep asserting on the engine singleton: anything that must run at teardown belongs in cleanup, not in a destructor. Not in destroyAudioEnginePreservingSessionDeactivationState: it runs with _engineLock held and is also the route-change rebuild path.

New Architecture support (getTurboModule):

#ifdef RCT_NEW_ARCH_ENABLED
- (std::shared_ptr<facebook::react::TurboModule>)getTurboModule:
    (const facebook::react::ObjCTurboModule::InitParams &)params
{
  return std::make_shared<facebook::react::NativeAudioAPIModuleSpecJSI>(params);
}
#endif

This connects the ObjC implementation to the codegen-generated C++ TurboModule spec.

methodQueue: the module runs on a dedicated serial queue (com.swmansion.audioapi.MainModuleQueue), not the main thread.

invokeHandlerWithEventName:eventBody:: called from Objective-C system callbacks (audio session interruption, volume change, etc.) to fire events back into JS. It converts NSDictionary to std::unordered_map<std::string, EventValue> and calls audioEventHandlerRegistry_->invokeHandlerWithEventBody(...).


Android Native Module (AudioAPIModule.kt + AudioAPIModule.cpp)

Android uses fbjni HybridObject — a pattern where a Kotlin class holds a C++ peer via HybridData. The Kotlin class handles the Java/Kotlin TurboModule protocol; the C++ peer owns the JSI runtime pointer and call invoker.

Initialization flow

AudioAPIModule.kt (init block)
  ├── System.loadLibrary("react-native-audio-api")        // load .so
  ├── get CallInvokerHolderImpl from reactContext
  ├── get WorkletsModule if worklets enabled
  └── mHybridData = initHybrid(workletsModule, jsContext, callInvokerHolder)
            │
            ▼
      AudioAPIModule.cpp::initHybrid (JNI)
        ├── unwrap jsCallInvoker from holder
        ├── reinterpret_cast<jsi::Runtime *>(jsContext)
        ├── [if worklets] get WorkletsModuleProxy
        └── makeCxxInstance(...)   → creates C++ AudioAPIModule peer
                └── stores: jsiRuntime_, jsCallInvoker_, audioEventHandlerRegistry_
AudioAPIModule.kt::install()
  ├── MediaSessionManager.initialize(...)
  ├── NativeFileInfo.initialize(...)
  └── injectJSIBindings()   // external fun → JNI call
            │
            ▼
      AudioAPIModule.cpp::injectJSIBindings()
        └── AudioAPIModuleInstaller::injectJSIBindings(...)

external fun: Kotlin keyword for JNI-implemented methods. These are registered in AudioAPIModule.cpp::registerNatives():

void AudioAPIModule::registerNatives() {
  registerHybrid({
    makeNativeMethod("initHybrid",          AudioAPIModule::initHybrid),
    makeNativeMethod("injectJSIBindings",   AudioAPIModule::injectJSIBindings),
    makeNativeMethod("invokeHandlerWithEventNameAndEventBody", ...),
  });
}

registerNatives() is called from android/src/main/cpp/audioapi/android/OnLoad.cpp at .so load time.

invokeHandlerWithEventNameAndEventBody: called from Kotlin (MediaSessionManager callbacks) to fire events into JS. Takes a Java Map<String, Object> and converts it to a typed AudioEventPayload in buildPayloadFromJniMap (android/src/main/cpp/audioapi/android/JniEventPayloadParser.cpp), which switches on the event. An event without a case there falls to EmptyPayload{}: the event still reaches JS, but with an empty body. When Kotlin starts sending a new event, add its case, building the same payload type the iOS side dispatches (e.g. ROUTE_CHANGE → StringPayload{.name = "reason", ...}).


Two-Architecture Paths Summary

Old BridgeNew Architecture (TurboModules/Fabric)
iOS CallInvoker sourceself.bridge.jsCallInvoker_callInvoker.callInvoker
iOS runtime sourceself.bridge.runtime (cast)same
iOS codegenRCT_EXPORT_MODULE only+ getTurboModule: implemented
Android CallInvokerreactContext.jsCallInvokerHoldersame
Android codegenNativeAudioAPIModuleSpec base classsame (generated)

The JSI injection itself (AudioAPIModuleInstaller) is identical for both architectures — it only needs the jsi::Runtime * and CallInvoker, which are obtained differently but behave the same.


Pure C++ TurboModule library (react-native-audio-worklets)

Extension packages that expose a C++-only TurboModule (no JNI implementation) use a hybrid Android setup:

PieceRole
react-native.config.js cxxModule* fieldsRegisters NativeAudioWorkletsModule in app autolinking (autolinking_cxxModuleProvider)
android/build.gradle + com.facebook.reactRuns Codegen → react_codegen_rnaudioworklets (JSI spec headers)
AudioWorkletsPackage.ktStub BaseReactPackage so Gradle autolinking includes the library project
Root CMakeLists.txtStatic react-native-audio-worklets target; linked into libappmodules.so via autolinking
common/cpp/NativeAudioWorkletsModule.hForwarding header — autolinking includes <NativeAudioWorkletsModule.h>

iOS uses NativeAudioWorkletsModuleProvider.mm + codegenConfig.ios.modulesProvider instead.

RN guide: https://reactnative.dev/docs/the-new-architecture/pure-cxx-modules


Maintenance: see maintenance.md.

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.