# CLAUDE.md

This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.

## Project Overview

**react-native-webrtc** is a React Native module that provides WebRTC functionality for real-time communication applications on mobile and desktop platforms. It bridges the native WebRTC libraries on Android and iOS to JavaScript/TypeScript, enabling developers to build peer-to-peer audio/video communication applications and data channel functionality.

- **Version**: 124.0.7
- **Supported Platforms**: Android (armeabi-v7a, arm64-v8a, x86, x86_64), iOS (arm64, x86_64), tvOS (arm64)
- **WebRTC Revision**: M124 (Jitsi-maintained fork)

## Common Development Commands

### Building and Linting
```bash
# Lint TypeScript code and run type checking
npm run lint

# Lint and auto-fix issues
npm run lintfix

# Format code using Prettier
npm run format
# Or directly: tools/format.sh

# Build the TypeScript module (generates lib/ directory)
npm run prepare
# This runs: husky install && bob build
# Output: lib/commonjs/, lib/module/, lib/typescript/
```

### Package Build
The package uses `react-native-builder-bob` to generate multiple build targets:
- CommonJS (`lib/commonjs/`)
- ES Modules (`lib/module/`)
- TypeScript definitions (`lib/typescript/`)

### Testing with Example Apps
```bash
# Navigate to example directory
cd examples/GumTestApp

# iOS
npm install
cd ios && pod install && cd ..
npx react-native run-ios

# Android
npm install
npx react-native run-android
```

### Native Development

**Android:**
- Open `android/` in Android Studio
- Uses Gradle build system
- WebRTC dependency: `org.jitsi:webrtc:124.+`
- Minimum SDK: 24

**iOS:**
- Open `ios/RCTWebRTC.xcworkspace` in Xcode
- Uses CocoaPods: `pod install` in ios/ directory
- WebRTC dependency: `JitsiWebRTC ~> 124.0.0`
- Minimum iOS: 12.0

### Important Notes
- The native WebRTC library is maintained by Jitsi at https://github.com/jitsi/webrtc
- This module does NOT include the WebRTC source; it depends on pre-built binaries from Jitsi
- To customize WebRTC builds, refer to the Jitsi WebRTC repository

## Directory Structure

```
react-native-webrtc/
├── src/                          # TypeScript/JavaScript bridge layer (~3,143 lines)
│   ├── index.ts                  # Main entry point, exports all public API
│   ├── EventEmitter.ts           # Native event bridging system
│   ├── RTCPeerConnection.ts      # Peer connection wrapper (primary API)
│   ├── RTCDataChannel.ts         # Data channel communication
│   ├── MediaStream.ts            # Media stream container
│   ├── MediaStreamTrack.ts       # Audio/video track abstraction
│   ├── getUserMedia.ts           # Camera/microphone acquisition
│   ├── getDisplayMedia.ts        # Screen capture
│   ├── Permissions.ts            # Permission handling (cross-platform)
│   ├── RTCView.ts                # Video rendering component wrapper
│   ├── RTCPIPView.tsx            # Picture-in-Picture iOS support
│   ├── RTCRtpSender.ts           # RTP sender control
│   ├── RTCRtpReceiver.ts         # RTP receiver control
│   ├── RTCRtpTransceiver.ts      # Transceiver management
│   ├── RTCIceCandidate.ts        # ICE candidate wrapper
│   ├── RTCSessionDescription.ts  # Session description wrapper
│   └── [other support files]
│
├── android/                      # Android native implementation
│   ├── build.gradle              # Android module build configuration
│   └── src/main/java/com/oney/WebRTCModule/
│       ├── WebRTCModule.java              # Main native module (ReactContextBaseJavaModule)
│       ├── WebRTCModulePackage.java       # React package registration
│       ├── GetUserMediaImpl.java           # getUserMedia implementation
│       ├── PeerConnectionObserver.java    # PeerConnection event observer
│       ├── DataChannelWrapper.java        # DataChannel wrapper
│       ├── RTCVideoViewManager.java       # Video view manager
│       ├── WebRTCView.java                # Native video rendering view
│       ├── CameraCaptureController.java   # Camera control
│       ├── DisplayUtils.java              # Display utilities
│       └── [video capture, effects, utilities]
│
├── ios/                          # iOS native implementation
│   ├── RCTWebRTC/                # Main iOS module
│   │   ├── WebRTCModule.h/m              # Main module header/implementation
│   │   ├── WebRTCModule+RTCPeerConnection.m
│   │   ├── WebRTCModule+RTCMediaStream.m
│   │   ├── WebRTCModule+RTCDataChannel.m
│   │   ├── WebRTCModule+Permissions.m
│   │   ├── WebRTCModule+RTCAudioSession.m
│   │   ├── WebRTCModule+Transceivers.m
│   │   ├── WebRTCModule+VideoTrackAdapter.m
│   │   ├── RTCVideoViewManager.h/m       # Video view manager
│   │   ├── PIPController.h/m             # Picture-in-Picture
│   │   ├── ScreenCaptureController.h/m   # Screen capture
│   │   ├── WebRTCModuleOptions.h/m       # Module options
│   │   ├── RCTConvert+WebRTC.h/m         # Type conversion utilities
│   │   └── [other support files]
│   ├── RCTWebRTC.xcodeproj/
│   └── RCTWebRTC.xcworkspace/
│
├── lib/                          # Build output (generated)
│   ├── commonjs/                 # CommonJS build
│   ├── module/                   # ES module build
│   └── typescript/               # TypeScript definitions
│
├── Documentation/                # User guides
│   ├── BasicUsage.md
│   ├── CallGuide.md
│   ├── AndroidInstallation.md
│   ├── iOSInstallation.md
│   └── [other guides]
│
├── examples/                     # Test applications
│   ├── GumTestApp/               # iOS/Android example
│   └── GumTestApp_macOS/         # macOS example
│
├── package.json                  # NPM configuration
├── react-native-webrtc.podspec   # CocoaPods specification
├── react-native.config.js        # React Native linking config
└── tsconfig.json                 # TypeScript configuration
```

## Architecture Overview

### High-Level Data Flow

```
JavaScript/TypeScript Layer
          ↓
    React Native Bridge
          ↓
    NativeModule (WebRTCModule)
          ↓
Native WebRTC Library (org.jitsi.webrtc)
          ↓
    OS-level APIs (MediaCodec, AVFoundation, etc.)
```

## Key Architectural Components

### 1. JavaScript/TypeScript Bridge Layer (`src/`)

The TypeScript layer provides a W3C-compliant WebRTC API surface that JavaScript developers use. All native functionality is exposed through the `NativeModules.WebRTCModule` API.

**Key files and their roles:**

#### Main Entry Point
- **`index.ts`**: 
  - Imports `WebRTCModule` from React Native's `NativeModules`
  - Throws error if native module not found
  - Calls `setupNativeEvents()` to initialize event listeners
  - Exports all public classes and functions (RTCPeerConnection, MediaStream, etc.)
  - Provides `registerGlobals()` to set up W3C-standard `navigator.mediaDevices` and global WebRTC objects

#### Event System
- **`EventEmitter.ts`**:
  - Manages bidirectional communication of WebRTC events from native to JS
  - Creates a `NativeEventEmitter` subscribed to the native `WebRTCModule`
  - Defines 13 core native event types: `peerConnectionSignalingStateChanged`, `peerConnectionStateChanged`, `peerConnectionIceConnectionChanged`, `dataChannelStateChanged`, `dataChannelReceiveMessage`, `mediaStreamTrackMuteChanged`, etc.
  - Implements a JS-only `EventEmitter` that re-emits native events for application code
  - Tracks subscriptions per listener to allow cleanup

#### Core WebRTC Classes

**RTCPeerConnection** (`RTCPeerConnection.ts`):
- Main class for managing peer-to-peer connections
- Each instance has a numeric ID (`_pcId`) tracked by the native module
- Key methods:
  - `createOffer()` / `createAnswer()` - generate session descriptions via native bridge
  - `setLocalDescription()` / `setRemoteDescription()` - manage connection state
  - `addTrack()` / `removeTrack()` - manage media tracks
  - `addIceCandidate()` - process ICE candidates
  - `createDataChannel()` - create data channels
  - `getStats()` - retrieve connection statistics
- Uses EventTarget pattern for event handling
- Maintains internal state: `signalingState`, `iceConnectionState`, `connectionState`, `iceGatheringState`
- Tracks transceivers, remote streams, and pending track events

**MediaStream** (`MediaStream.ts`):
- Container for audio/video tracks
- Each stream has a unique `_id` and `_reactTag`
- Methods:
  - `addTrack()` / `removeTrack()` - manage contained tracks
  - `getTracks()` / `getAudioTracks()` / `getVideoTracks()` - query tracks
  - `release()` - cleanup stream
- Maintains internal `_tracks` array

**MediaStreamTrack** (`MediaStreamTrack.ts`):
- Represents individual audio or video tracks
- Properties: `id`, `kind` (audio/video), `enabled`, `readyState`, `settings`
- Distinguishes between local and remote tracks via `remote` flag
- Methods:
  - `setConstraints()` - apply media constraints
  - `stop()` - stop track capture
  - `getSettings()` / `getCapabilities()` - query capabilities
- Emits events: `ended`, `mute`, `unmute`

**RTCDataChannel** (`RTCDataChannel.ts`):
- For non-media data transmission
- States: connecting, open, closing, closed
- Methods: `send()`, `close()`
- Supports both text and binary (ArrayBuffer) message types
- Tracks: `label`, `id`, `ordered`, `maxPacketLifeTime`, `maxRetransmits`, `protocol`

**Media Device Access**:
- `getUserMedia.ts`: Requests camera/microphone access with constraints
  - Checks permissions first
  - Normalizes constraints
  - Returns `Promise<MediaStream>`
- `getDisplayMedia.ts`: Requests screen capture
- `Permissions.ts`: Cross-platform permission management
  - Android: Uses `PermissionsAndroid` API
  - iOS: Delegates to native `WebRTCModule` methods

**Video Rendering**:
- `RTCView.ts`: Exports `requireNativeComponent('RTCVideoView')`
  - Props: `streamURL`, `mirror`, `objectFit`, `zOrder`, `onDimensionsChange`
  - iOS-specific: `iosPIP` for Picture-in-Picture support
- `RTCPIPView.tsx`: Picture-in-Picture controller (iOS only)
  - Methods: `startIOSPIP()`, `stopIOSPIP()`

**RTP Control**:
- `RTCRtpSender.ts`: RTP sender control and statistics
- `RTCRtpReceiver.ts`: RTP receiver control
- `RTCRtpTransceiver.ts`: Bidirectional transceiver management
- `RTCRtpEncodingParameters.ts`: Encoding configuration for simulcast/SVC

### 2. Android Native Implementation (`android/`)

#### WebRTCModule (Main Bridge)
**`WebRTCModule.java`** (extends `ReactContextBaseJavaModule`):
- Central module implementing all native methods
- Initialization:
  - Creates `PeerConnectionFactory` using Jitsi's WebRTC library
  - Initializes video encoder/decoder factories with H.264 hardware acceleration
  - Sets up audio device module
  - Configures EGL context for hardware acceleration
- Maintains:
  - `mPeerConnectionObservers`: SparseArray mapping peer connection IDs to observer objects
  - `localStreams`: HashMap of local media streams
  - `getUserMediaImpl`: Separate handler for getUserMedia

**Key Exported Methods** (called from JS via NativeModules):
- `peerConnectionInit(config, id)` - Create new peer connection
- `peerConnectionCreateOffer(id, options)` - Generate offer SDP
- `peerConnectionCreateAnswer(id, options)` - Generate answer SDP
- `peerConnectionSetLocalDescription(id, sdp)` - Set local SDP
- `peerConnectionSetRemoteDescription(id, sdp)` - Set remote SDP
- `peerConnectionAddIceCandidate(id, candidate)` - Add ICE candidate
- `mediaStreamCreate(streamId)` - Create media stream
- `mediaStreamAddTrack(streamTag, pcId, trackId)` - Add track to stream
- `getUserMedia(constraints, success, failure)` - Acquire camera/mic
- `getDisplayMedia(success, failure)` - Screen capture
- `dataChannelSend(pcId, dataChannelId, data)` - Send data channel message

**Event Emission**:
```java
void sendEvent(String eventName, @Nullable ReadableMap params) {
    getReactApplicationContext()
        .getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
        .emit(eventName, params);
}
```
Emits native events that are received by the JS `NativeEventEmitter`

#### GetUserMediaImpl
**`GetUserMediaImpl.java`**:
- Handles camera/microphone and screen capture acquisition
- Features:
  - Uses `CameraEnumerator` to discover available cameras
  - Applies media constraints (resolution, frame rate, facing mode)
  - Manages permissions via `ActivityEventListener`
  - Handles screen capture permission via `MediaProjectionManager`
  - Creates `AudioTrack` and `VideoTrack` objects
  - Returns track info via callbacks to JS layer

#### PeerConnectionObserver
**`PeerConnectionObserver.java`**:
- Implements `PeerConnection.Observer` interface
- Listens to native WebRTC events and translates them to React Native events
- Manages:
  - Data channels (`DataChannelWrapper` instances)
  - Remote streams and tracks
  - Video track adapters for rendering
- Callbacks translate native events → `sendEvent()` calls

#### WebRTCView (Video Rendering)
**`WebRTCView.java`**:
- Custom Android View for video rendering
- Uses `SurfaceViewRenderer` from WebRTC library
- Properties: `mirror`, `objectFit`, `zOrder`, `streamURL`
- Automatically connects to media stream when `streamURL` is set

**`RTCVideoViewManager.java`** (extends `SimpleViewManager<WebRTCView>`):
- React ViewManager that creates and manages WebRTCView instances
- Handles prop updates (mirror, objectFit, streamURL, zOrder)

#### Helper Classes
- **`DataChannelWrapper.java`**: Wraps RTCDataChannel with state tracking
- **`CameraCaptureController.java`** / **`AbstractVideoCaptureController.java`**: Camera capture management
- **`ReactBridgeUtil.java`**: Conversion utilities between React Bridge types and WebRTC types
- **`VideoTrackAdapter.java`**: Adapts video frames for rendering

### 3. iOS Native Implementation (`ios/RCTWebRTC/`)

#### WebRTCModule (Main Bridge)
**`WebRTCModule.h/m`** (implements `RCTBridgeModule`, `RCTEventEmitter`):
- Central iOS module managing all WebRTC functionality
- Key properties:
  - `RTCPeerConnectionFactory *peerConnectionFactory`: Factory for creating connections
  - `NSMutableDictionary<NSNumber *, RTCPeerConnection *> *peerConnections`: Active peer connections
  - `NSMutableDictionary<NSString *, RTCMediaStream *> *localStreams`: Local media streams
  - `NSMutableDictionary<NSString *, RTCMediaStreamTrack *> *localTracks`: Local tracks
  - `dispatch_queue_t workerQueue`: Background execution queue

**Initialization** (`init`):
- Sets up video encoder/decoder factories
- Initializes `RTCPeerConnectionFactory`
- Creates dispatch queue for background work
- Applies field trials for WebRTC optimization

**Modular Architecture** (using Objective-C categories):
- `WebRTCModule+RTCPeerConnection.m`: Peer connection methods
- `WebRTCModule+RTCMediaStream.m`: Media stream methods
- `WebRTCModule+RTCDataChannel.m`: Data channel methods
- `WebRTCModule+RTCAudioSession.m`: Audio configuration
- `WebRTCModule+Permissions.m`: Permission handling
- `WebRTCModule+Transceivers.m`: RTP transceiver management
- `WebRTCModule+VideoTrackAdapter.m`: Video frame adaptation

**Event Emission**:
- Extends `RCTEventEmitter`
- Supports array of events: `supportedEvents`
- Emits events via `[self sendEventWithName:body:]`

#### Key Supporting Classes

**`RTCVideoViewManager.h/m`**:
- ViewManager for RTCView component
- Creates and manages `RTCVideoView` native instances
- Handles prop updates

**`ScreenCaptureController.h/m`**:
- Manages screen recording via `RPScreenRecorder`
- Handles permission flow
- Creates screen capture media stream

**`PIPController.h/m`**:
- Picture-in-Picture controller for iOS 15+
- Manages `AVPictureInPictureController`
- Handles PIP lifecycle (start, stop, pause, resume)

**`WebRTCModuleOptions.h/m`**:
- Singleton for configurable module options
- Custom encoder/decoder factories
- Custom audio device
- Field trials configuration
- Logging severity

**`RCTConvert+WebRTC.h/m`**:
- Type conversion utilities
- Converts between React Bridge types and WebRTC native types

**Helper Classes**:
- `DataChannelWrapper.h`: Wraps RTCDataChannel
- `CapturerEventsDelegate.h`: Camera capture event delegate
- `VideoCaptureController.h`: Camera control
- `I420Converter.h`: Video frame format conversion
- `SerializeUtils.h/m`: Serialization utilities for cross-layer communication

## Native Dependency Management

### Android
**`android/build.gradle`**:
```gradle
dependencies {
    implementation "com.facebook.react:react-android:+"
    api 'org.jitsi:webrtc:124.+'           // WebRTC library
    implementation "androidx.core:core:1.7.0"
}
```
- Uses Jitsi-maintained WebRTC build
- Requires Java 8 for WebRTC compatibility
- Hardware acceleration via EGL

### iOS
**`react-native-webrtc.podspec`**:
```ruby
s.dependency 'React-Core'
s.dependency 'JitsiWebRTC', '~> 124.0.0'  # Jitsi WebRTC pod
s.framework = 'AudioToolbox', 'AVFoundation', 'CoreAudio', 
             'CoreGraphics', 'CoreVideo', 'GLKit', 'VideoToolbox'
```
- Minimum iOS 12.0, macOS 10.13, tvOS 16.0
- Links required audio/video frameworks
- Uses Jitsi's pre-built WebRTC pod

## Build System

### JavaScript/TypeScript Build
**`package.json`**:
```json
{
  "react-native": "src/index.ts",
  "main": "lib/commonjs/index.js",
  "module": "lib/module/index.js",
  "types": "lib/typescript/index.d.ts"
}
```
- Uses `react-native-builder-bob` for multi-target output
- Generates: CommonJS, ES Modules, TypeScript definitions
- Targets: `["commonjs", "module", "typescript"]`

### Native Module Registration
**`react-native.config.js`**:
```javascript
module.exports = {
    reactNativePath: '...',
    project: {
        ios: {},
        android: {}
    }
};
```
- Auto-linking configuration for React Native

**Android (`WebRTCModulePackage.java`)**:
```java
public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) {
    return Arrays.asList(new WebRTCModule(reactContext));
}
public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) {
    return Arrays.asList(new RTCVideoViewManager());
}
```

**iOS** (via CocoaPods):
- Automatically linked through `.podspec`
- React sees `WebRTCModule` via RN_EXPORT macros

## Bridge Communication Patterns

### 1. One-Way Native Calls (JS → Native)
JavaScript calls native methods synchronously or asynchronously:

```typescript
// JS
const config = { iceServers: [...] };
const success = WebRTCModule.peerConnectionInit(config, pcId);

// Android/iOS
@ReactMethod
public void peerConnectionInit(ReadableMap config, int id, Promise promise) {
    // Process config, create native resources
    promise.resolve(success);
}
```

### 2. Event Emission (Native → JS)
Native code emits events that JS layer receives:

```java
// Android
WritableMap params = Arguments.createMap();
params.putInt("id", pcId);
params.putString("state", "connected");
sendEvent("peerConnectionStateChanged", params);

// JS - EventEmitter intercepts
nativeEmitter.addListener("peerConnectionStateChanged", (params) => {
    eventEmitter.emit("peerConnectionStateChanged", params);
});
```

### 3. Asynchronous Operations (Callbacks)
For complex operations like getUserMedia:

```java
// Android
WebRTCModule.getUserMedia(constraints, success, failure);

// Implementation
private void getUserMedia(ReadableMap constraints, Callback success, Callback failure) {
    // ... acquire camera/mic ...
    success.invoke(streamId, tracksArray); // or failure.invoke(error)
}

// JS
WebRTCModule.getUserMedia(constraints, (streamId, tracks) => {
    resolve(new MediaStream({streamId, streamReactTag: streamId, tracks}));
}, (error) => {
    reject(error);
});
```

## Key Design Patterns

### 1. Wrapper Pattern
Each native WebRTC object has a JS wrapper that maintains state and bridges calls:
- Native `RTCPeerConnection` → JS `RTCPeerConnection` class
- Native `MediaStream` → JS `MediaStream` class
- Each wrapper tracks a unique ID for native reference

### 2. Event-Driven Architecture
- Native observer/delegate patterns capture WebRTC events
- Events are serialized and sent to JS
- JS EventEmitter re-broadcasts to application listeners

### 3. Dual Initialization
Each major class initializes in both JS and native:

```typescript
constructor(config) {
    this._pcId = nextId++;
    WebRTCModule.peerConnectionInit(config, this._pcId); // Native init
    this._registerEvents(); // JS event setup
}
```

### 4. Lazy Stream Resolution
Remote media streams are created on-demand when track events arrive:
```typescript
// onRemoteTrack event
const remoteStream = this._remoteStreams.get(streamId) 
    || new MediaStream({ streamId, streamReactTag, tracks });
```

### 5. Object Pooling
- PeerConnection and DataChannel objects are pooled by ID
- Android: `SparseArray<PeerConnectionObserver>`
- iOS: `NSMutableDictionary<NSNumber *, RTCPeerConnection *>`

## Data Flow Examples

### Example 1: Peer Connection Creation
```
JS: new RTCPeerConnection(config)
  ↓
JS: WebRTCModule.peerConnectionInit(config, pcId)
  ↓
Native: Create RTCPeerConnection object, store in observers map
  ↓
Native: Return success flag
  ↓
JS: Register event listeners for this peer connection
```

### Example 2: Media Track Reception
```
Native: WebRTC detects remote track
  ↓
Native: PeerConnectionObserver.onAddTrack() fires
  ↓
Native: Create MediaStreamTrack wrapper, send event with track info
  ↓
Native: sendEvent("peerConnectionOnTrack", {pcId, streamId, trackInfo})
  ↓
JS: EventEmitter receives event
  ↓
JS: RTCPeerConnection instance finds event via pcId
  ↓
JS: Emits RTCTrackEvent with new MediaStream and MediaStreamTrack
  ↓
App: Receives 'track' event on RTCPeerConnection
```

### Example 3: Video Rendering
```
JS: <RTCView streamURL={stream.id} />
  ↓
React Native: Maps to native RTCVideoView component
  ↓
Native: Looks up stream by ID in stream registry
  ↓
Native: Connects video track to SurfaceViewRenderer (Android)
         or RTCMTLVideoView (iOS)
  ↓
Native: Renders video frames in real-time
```

## Platform-Specific Considerations

### Android
- Uses hardware video codec when available (H.264)
- Fallback to software encoding/decoding
- Requires API 24+ (min SDK)
- Audio routing controlled via RTCModule
- Screen capture requires API 21+ for MediaProjection

### iOS
- Uses VideoToolbox for hardware acceleration
- Metal rendering for RTCView
- Picture-in-Picture support iOS 15+
- Audio categories: PlayAndRecord, Speakerphone
- Background audio requires entitlements

### Permissions
- **Android**: Handled via `PermissionsAndroid` API (queued due to one-at-a-time limit)
- **iOS**: Handled via native `AVCaptureDevice` requests (show native permission dialogs)

## Extension Points

### Customization
1. **Video Codec**: Pass custom encoder/decoder factories to `WebRTCModuleOptions`
2. **Audio Device**: Provide custom audio device implementation
3. **Field Trials**: Configure WebRTC experimental features
4. **Video Capture**: Extend `CameraCaptureController` (Android) or `VideoCaptureController` (iOS)
5. **Event Handling**: Listen to emitted events via EventTarget API

### Common Tasks

**Enable Custom Video Processing**:
- Android: Provide `VideoFrameProcessor` implementation
- iOS: Override video frame callbacks in capture controller

**Add Statistics Tracking**:
```typescript
const stats = await peerConnection.getStats();
for (const report of stats) {
    if (report.type === 'inbound-rtp') {
        // Process video/audio stats
    }
}
```

**Control Audio Session** (iOS):
```typescript
RTCAudioSession.configureAudioSession();
```

## Testing & Debugging

### Debug Logging
TypeScript layer uses debug module:
```typescript
Logger.enable(`${Logger.ROOT_PREFIX}:*`);
```
Prefix: `react-native-webrtc:*`

### Native Logging
- Android: Logcat output with `WebRTCModule` tag
- iOS: Console output, or via Xcode debugger

### Example App
`GumTestApp` in examples directory demonstrates:
- getUserMedia (camera/mic access)
- Basic video rendering
- Permission handling

## File Organization Philosophy

1. **Clear Separation**: JS/TS layer is completely separate from native implementations
2. **Modular Native Code**: iOS uses categories to split functionality by concern
3. **Single Responsibility**: Each class has one primary purpose
4. **Bridge Indirection**: No direct native API exposure; all bridging through WebRTCModule
5. **W3C Compliance**: JS API closely follows W3C WebRTC specification

## Dependencies

### Core
- `react-native` >= 0.60.0 (peer dependency)
- `base64-js` 1.5.1 (data encoding)
- `event-target-shim` 6.0.2 (W3C event model)
- `debug` 4.3.4 (logging utility)

### Build-Time
- `typescript` 4.6.2
- `react-native-builder-bob` 0.18.2 (multi-target build)
- `eslint` + TypeScript eslint
- `prettier` (code formatting)
- `husky` 7.0.2 (git hooks)

### Runtime Native
- Android: `org.jitsi:webrtc:124.+`
- iOS: `JitsiWebRTC ~> 124.0.0`

## Conclusion

React Native WebRTC follows a clean layered architecture:

1. **Presentation**: TypeScript/JavaScript W3C-compliant API
2. **Bridge Layer**: React Native NativeModules, EventEmitter, and conversion utilities
3. **Native Implementation**: Android (Java) and iOS (Objective-C) modules using platform WebRTC SDKs
4. **Platform SDKs**: Android WebRTC, iOS AVFoundation/WebRTC

The modular design allows for platform-specific optimizations while maintaining a unified API surface for developers. Event-driven architecture ensures responsive real-time communication, while the wrapper pattern provides clean abstraction boundaries.
