# hiyve-rtc-client

WebRTC client library for building real-time video conferencing applications with Hiyve SDK.

## Features

- WebRTC audio/video communication
- Automatic device management and selection
- Real-time connection events and state management
- Support for screen sharing
- File system caching for media
- Video sentiment analysis (lazy-loaded)
- Browser and ES module support

## Installation

### NPM

```bash
npm install @hiyve/rtc-client
```

### Package.json

```json
{
  "dependencies": {
    "@hiyve/rtc-client": "latest"
  }
}
```

## Quick Start

### ES Modules

```javascript
import { Client, ClientEvents, DeviceCheck } from '@hiyve/rtc-client';

// Check device permissions
const deviceCheck = new DeviceCheck();
const permissions = await deviceCheck.checkPermissions();

// Create client instance
const client = new Client({
  signalingUrl: 'https://your-signaling-server.com'
});

// Listen for events
client.addEventListener(ClientEvents.CONNECTED, () => {
  console.log('Connected to signaling server');
});

client.addEventListener(ClientEvents.ROOM_JOINED, (data) => {
  console.log('Joined room:', data.roomId);
});

client.addEventListener(ClientEvents.PEER_JOINED, (data) => {
  console.log('Peer joined:', data.peerId);
});

// Connect and join room
await client.connect();
await client.joinRoom('my-room', 'user-123', 'John Doe');
```

## API Reference

### Main Exports

| Export | Description |
|--------|-------------|
| `Client` | Main WebRTC client class |
| `ClientEvents` | Event types emitted by the client |
| `ClientManager` | Manages multiple client instances |
| `DeviceCheck` | Device permission checking utility |
| `MediaDeviceManager` | Audio/video device enumeration and selection |
| `MediaDeviceTester` | Test audio/video devices |

### Aliased Exports

| Alias | Original |
|-------|----------|
| `HiyveClient` | `Client` |
| `HiyveClientEvents` | `ClientEvents` |

### Storage Helpers

| Export | Signature | Description |
|--------|-----------|-------------|
| `addToLocalStorage` | `(key: string, value: any) => void` | Stores a JSON-serialized value in localStorage |
| `getFromLocalStorage` | `(key: string) => any` | Retrieves and parses a JSON value from localStorage, returns `null` if not found |

### String Utilities

| Export | Signature | Description |
|--------|-----------|-------------|
| `cleanRoomName` | `(roomName: string) => string` | Sanitizes a room name to lowercase alphanumeric characters, hyphens, and underscores |
| `cleanUserId` | `(userId: string) => string` | Sanitizes a user ID to lowercase alphanumeric characters, hyphens, underscores, and `@` |

### File System Cache

| Export | Description |
|--------|-------------|
| `getFileSystemCache` | Returns a file system cache instance scoped to a user and room. Requires `{ userId, roomName }` options. |
| `clearFileSystemCache` | Clears the file system cache for a given user and room. Accepts `(userId, roomName, isRoomOwner?)`. |
| `EnhancedFileSystemCache` | File system caching class for media with advanced storage management |

### Sentiment Analysis

Lazy-loaded analyzers for real-time video sentiment detection. Each loader returns a Promise that resolves to the analyzer class. Use the single-video analyzer for one participant or the multi-video manager for tracking multiple participants simultaneously.

| Loader | Engine | Best For |
|--------|--------|----------|
| `loadVideoSentimentAnalyzer` | Default | Single video sentiment analysis |
| `loadMultiVideoSentimentManager` | Default | Multi-participant sentiment tracking |
| `loadMediaPipeVideoSentimentAnalyzer` | MediaPipe | Single video, 3-5x faster than default |
| `loadMediaPipeMultiVideoSentimentManager` | MediaPipe | Multi-participant, handles 20-30+ participants |
| `loadHumanVideoSentimentAnalyzer` | Human.js | Single video, WASM-optimized, 5-10x faster |
| `loadHumanMultiVideoSentimentManager` | Human.js | Multi-participant, handles 30+ participants |

### Client Events

```javascript
// Connection
ClientEvents.READY                      // Client initialized and ready
ClientEvents.CONNECTED                  // Connected to signaling server
ClientEvents.DISCONNECTED               // Disconnected from server
ClientEvents.ERROR                      // Error occurred

// Room lifecycle
ClientEvents.ROOM_JOINED                // Successfully joined a room
ClientEvents.ROOM_CLOSED                // Room closed by owner
ClientEvents.USER_JOINED_ROOM           // Remote user joined the room
ClientEvents.USER_DISCONNECTED          // Remote user left the room

// Media tracks
ClientEvents.MEDIA_TRACK_ADDED          // Remote media track available
ClientEvents.MEDIA_TRACK_REMOVED        // Remote media track removed
ClientEvents.AUDIO_STREAM_ADDED         // Merged audio stream available
ClientEvents.AUDIO_STREAM_REMOVED       // Merged audio stream removed

// Mute state
ClientEvents.AUDIO_MUTED                // Local audio mute state changed
ClientEvents.VIDEO_MUTED                // Local video mute state changed
ClientEvents.OUTPUT_MUTED               // Local audio output mute state changed
ClientEvents.REMOTE_AUDIO_MUTED         // Owner requests audio mute
ClientEvents.REMOTE_VIDEO_MUTED         // Owner requests video mute
ClientEvents.REMOTE_OUTPUT_MUTED        // Owner requests output mute

// Device changes
ClientEvents.AUDIO_INPUT_DEVICE_CHANGED  // Audio input device changed
ClientEvents.VIDEO_INPUT_DEVICE_CHANGED  // Video input device changed
ClientEvents.AUDIO_OUTPUT_DEVICE_CHANGED // Audio output device changed
ClientEvents.AUDIO_INPUT_MONITOR_CREATED // Audio input monitor created
ClientEvents.AUDIO_GAIN_CONTROL_CREATED  // Audio gain control created

// Screen sharing
ClientEvents.SCREEN_SHARE_STARTED       // Screen sharing started
ClientEvents.SCREEN_SHARE_STOPPED       // Screen sharing stopped

// Recording
ClientEvents.RECORDING_STARTED          // Recording started
ClientEvents.RECORDING_STOPPED          // Recording stopped
ClientEvents.RECORDING_STATE_CHANGED    // Recording state changed

// Streaming
ClientEvents.STREAMING_STARTED          // Live streaming started
ClientEvents.STREAMING_STOPPED          // Live streaming stopped
ClientEvents.STREAMING_USER_CHANGED     // Featured user in stream changed

// Transcription
ClientEvents.TRANSCRIPTION_RECEIVED     // Transcription text received
ClientEvents.TRANSCRIPTION_STARTED      // Transcription service started
ClientEvents.TRANSCRIPTION_STOPPED      // Transcription service stopped

// Chat and data
ClientEvents.RECEIVE_CHAT_MESSAGE       // Chat message received
ClientEvents.DATA_MESSAGE               // Data message received

// Waiting room
ClientEvents.ADMIT_WAITING_ROOM         // User admitted from waiting room
ClientEvents.REJECT_WAITING_ROOM        // User rejected from waiting room

// Wait for host
ClientEvents.WAIT_FOR_HOST_STARTED      // Waiting for host began
ClientEvents.WAIT_FOR_HOST_ROOM_READY   // Host started, room ready
ClientEvents.WAIT_FOR_HOST_TIMEOUT      // Waiting for host timed out
ClientEvents.WAIT_FOR_HOST_CANCELLED    // Waiting for host cancelled

// Audio quality
ClientEvents.FEEDBACK_DETECTED          // Audio feedback detected
ClientEvents.FEEDBACK_STOPPED           // Audio feedback stopped
ClientEvents.AUDIO_VALIDATION_FAILED    // Audio validation failed
ClientEvents.AUDIO_VALIDATION_WARNING   // Audio validation warning
ClientEvents.CONSTRAINTS_RELAXED        // Media constraints relaxed
```

### Client Methods

```javascript
// Connection
await client.connect();
await client.disconnect();

// Room management
await client.joinRoom(roomId, odid, displayName, options);
await client.leaveRoom();

// Media controls
client.enableVideo(enabled);
client.enableAudio(enabled);
await client.switchVideoDevice(deviceId);
await client.switchAudioDevice(deviceId);

// Screen sharing
await client.startScreenShare();
await client.stopScreenShare();
```

## Requirements

- Modern browser with WebRTC support (Chrome 74+, Firefox 68+, Safari 14.1+, Edge 79+)
- No peer dependencies — all WebRTC internals are bundled

## Documentation

Full API documentation: https://sdk.hiyve.dev/hiyve-rtc-client/latest/

## License

Commercial - IWantToPractice, LLC 2025
