npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

webrtc2-utils

v1.0.0

Published

WebRTC2 Utils - Cross-platform WebRTC utility functions for device detection, media management, error handling, and performance optimization

Readme

@webrtc2/utils - WebRTC Utility Functions

npm version TypeScript Cross-Platform

Cross-platform WebRTC utility functions - Device detection, media management, error handling, and performance optimization for React Native, Web, and Electron.

🚀 WebRTC Utilities Made Simple

@webrtc2/utils provides essential utilities for WebRTC development:

  • 📱 Device Detection: Platform, browser, and device capabilities
  • 🎥 Media Management: Stream handling, device switching, constraints
  • ⚡ Performance Optimization: Memory management, connection monitoring
  • 🐛 Error Handling: WebRTC-specific error types and recovery
  • 🔧 Connection Utilities: ICE helpers, signaling tools
  • 📊 Analytics: Performance metrics and debugging tools

📦 Installation

npm install @webrtc2/utils

🎯 Device Detection

Platform Detection

import { 
  detectPlatform, 
  isMobile, 
  isDesktop, 
  isReactNative,
  isElectron,
  getBrowserInfo 
} from '@webrtc2/utils';

// Detect current platform
const platform = detectPlatform();
console.log('Platform:', platform); // 'web' | 'react-native' | 'electron'

// Platform checks
if (isMobile()) {
  console.log('Running on mobile device');
}

if (isReactNative()) {
  console.log('Running in React Native');
}

if (isElectron()) {
  console.log('Running in Electron');
}

// Browser information
const browserInfo = getBrowserInfo();
console.log('Browser:', browserInfo);
// { name: 'Chrome', version: '91.0.4472.124', webrtcSupported: true }

WebRTC Capability Detection

import { 
  checkWebRTCSupport, 
  getWebRTCCapabilities,
  canUseGetUserMedia,
  canUseGetDisplayMedia 
} from '@webrtc2/utils';

// Check WebRTC support
const webrtcSupport = checkWebRTCSupport();
console.log('WebRTC Support:', webrtcSupport);
// { supported: true, getUserMedia: true, RTCPeerConnection: true, ... }

// Get detailed capabilities
const capabilities = await getWebRTCCapabilities();
console.log('Capabilities:', capabilities);
// { video: { codecs: ['VP8', 'VP9'], maxResolution: {...} }, ... }

// Feature-specific checks
if (canUseGetUserMedia()) {
  console.log('Can access camera/microphone');
}

if (canUseGetDisplayMedia()) {
  console.log('Can share screen');
}

🎥 Media Management

Stream Utilities

import { 
  createMediaStream,
  cloneMediaStream,
  stopMediaStream,
  getStreamInfo,
  optimizeStreamForPlatform 
} from '@webrtc2/utils';

// Create optimized media stream
const stream = await createMediaStream({
  video: { width: 1280, height: 720 },
  audio: true
});

// Get stream information
const streamInfo = getStreamInfo(stream);
console.log('Stream info:', streamInfo);
// { videoTracks: 1, audioTracks: 1, active: true, ... }

// Platform-specific optimization
const optimizedStream = optimizeStreamForPlatform(stream, 'mobile');

// Clean up stream
stopMediaStream(stream);

Device Management

import { 
  enumerateDevices,
  getDefaultDevices,
  switchCamera,
  switchMicrophone,
  DeviceManager 
} from '@webrtc2/utils';

// Enumerate available devices
const devices = await enumerateDevices();
console.log('Available devices:', devices);

// Get default devices
const defaultDevices = await getDefaultDevices();
console.log('Default camera:', defaultDevices.camera);
console.log('Default microphone:', defaultDevices.microphone);

// Device manager for easy switching
const deviceManager = new DeviceManager();

// Switch to different camera
await deviceManager.switchCamera('camera-id-123');

// Switch microphone
await deviceManager.switchMicrophone('mic-id-456');

// Listen for device changes
deviceManager.on('device-change', (devices) => {
  console.log('Devices changed:', devices);
});

⚡ Performance Optimization

Memory Management

import { 
  WebRTCMemoryManager,
  cleanupPeerConnection,
  monitorMemoryUsage 
} from '@webrtc2/utils';

// Memory manager for WebRTC resources
const memoryManager = new WebRTCMemoryManager({
  maxConnections: 10,
  cleanupInterval: 30000,
  autoCleanup: true
});

// Add peer connection to management
memoryManager.addPeerConnection(peerConnection);

// Manual cleanup
cleanupPeerConnection(peerConnection);

// Monitor memory usage
const memoryMonitor = monitorMemoryUsage();
memoryMonitor.on('high-memory', (usage) => {
  console.warn('High memory usage detected:', usage);
});

Connection Optimization

import { 
  optimizeConnectionForPlatform,
  getOptimalVideoConstraints,
  getOptimalAudioConstraints,
  adaptBitrateForConnection 
} from '@webrtc2/utils';

// Platform-specific optimization
const config = optimizeConnectionForPlatform('mobile');
console.log('Optimized config:', config);

// Get optimal media constraints
const videoConstraints = getOptimalVideoConstraints('mobile');
const audioConstraints = getOptimalAudioConstraints('mobile');

// Adaptive bitrate based on connection
const connection = { /* RTCPeerConnection */ };
await adaptBitrateForConnection(connection, 'slow-2g');

🐛 Error Handling

WebRTC Error Types

import { 
  WebRTCError,
  WebRTCErrorHandler,
  isWebRTCError,
  handleWebRTCError,
  ErrorRecovery 
} from '@webrtc2/utils';

// Error handler with recovery
const errorHandler = new WebRTCErrorHandler({
  autoReconnect: true,
  maxRetries: 3,
  retryDelay: 2000
});

// Handle different error types
errorHandler.on('permission-denied', async (error) => {
  console.error('Camera/microphone permission denied');
  // Show permission request UI
});

errorHandler.on('connection-failed', async (error) => {
  console.error('Connection failed:', error);
  // Attempt reconnection with different servers
});

errorHandler.on('ice-connection-failed', async (error) => {
  console.error('ICE connection failed');
  // Try with TURN servers
});

// Manual error handling
try {
  await someWebRTCOperation();
} catch (error) {
  if (isWebRTCError(error)) {
    await handleWebRTCError(error);
  }
}

Connection Recovery

import { 
  ConnectionRecovery,
  reconnectWithBackoff,
  checkConnectionHealth 
} from '@webrtc2/utils';

// Connection recovery manager
const recovery = new ConnectionRecovery({
  maxAttempts: 5,
  backoffStrategy: 'exponential',
  healthCheckInterval: 10000
});

// Automatic reconnection
recovery.on('connection-lost', async () => {
  console.log('Connection lost, attempting recovery...');
  await reconnectWithBackoff(peerConnection);
});

// Health monitoring
const healthCheck = checkConnectionHealth(peerConnection);
healthCheck.on('degraded', (metrics) => {
  console.warn('Connection quality degraded:', metrics);
});

🔧 Connection Utilities

ICE Utilities

import { 
  validateICEServers,
  testSTUNServer,
  testTURNServer,
  getPublicIP,
  detectNATType 
} from '@webrtc2/utils';

// Validate ICE server configuration
const iceServers = [
  { urls: 'stun:stun.l.google.com:19302' },
  { urls: 'turn:turn.example.com:3478', username: 'user', credential: 'pass' }
];

const validation = await validateICEServers(iceServers);
console.log('ICE servers valid:', validation.valid);

// Test individual servers
const stunResult = await testSTUNServer('stun:stun.l.google.com:19302');
console.log('STUN server response time:', stunResult.responseTime);

const turnResult = await testTURNServer({
  urls: 'turn:turn.example.com:3478',
  username: 'user',
  credential: 'pass'
});
console.log('TURN server accessible:', turnResult.accessible);

// Network information
const publicIP = await getPublicIP();
const natType = await detectNATType();
console.log('Public IP:', publicIP, 'NAT Type:', natType);

Signaling Utilities

import { 
  SignalingMessageValidator,
  encodeSignalingMessage,
  decodeSignalingMessage,
  createSignalingMessage 
} from '@webrtc2/utils';

// Message validation
const validator = new SignalingMessageValidator();

const isValid = validator.validate({
  type: 'offer',
  from: 'peer-1',
  to: 'peer-2',
  data: { /* SDP offer */ }
});

// Message encoding/decoding
const message = createSignalingMessage('offer', 'peer-1', 'peer-2', offerData);
const encoded = encodeSignalingMessage(message);
const decoded = decodeSignalingMessage(encoded);

📊 Analytics & Debugging

Performance Monitoring

import { 
  WebRTCAnalytics,
  ConnectionMetrics,
  MediaQualityMonitor 
} from '@webrtc2/utils';

// Analytics collection
const analytics = new WebRTCAnalytics({
  trackBitrate: true,
  trackLatency: true,
  trackPacketLoss: true,
  trackJitter: true
});

// Monitor connection metrics
analytics.on('metrics-update', (metrics: ConnectionMetrics) => {
  console.log('Connection metrics:', {
    bitrate: metrics.bitrate,
    latency: metrics.latency,
    packetLoss: metrics.packetLoss,
    jitter: metrics.jitter
  });
});

// Media quality monitoring
const qualityMonitor = new MediaQualityMonitor();
qualityMonitor.on('quality-changed', (quality) => {
  console.log('Media quality:', quality); // 'excellent' | 'good' | 'poor'
});

Debug Utilities

import { 
  WebRTCDebugger,
  logWebRTCStats,
  exportDebugInfo,
  createDebugReport 
} from '@webrtc2/utils';

// Debug helper
const debugger = new WebRTCDebugger({
  logLevel: 'debug',
  logToConsole: true,
  logToFile: true
});

// Log connection stats
await logWebRTCStats(peerConnection);

// Export debug information
const debugInfo = await exportDebugInfo(peerConnection);
console.log('Debug info:', debugInfo);

// Create comprehensive debug report
const report = await createDebugReport({
  connection: peerConnection,
  includeStats: true,
  includeConfiguration: true,
  includeMediaDevices: true
});

🌐 Cross-Platform Helpers

React Native Utilities

import { 
  ReactNativeWebRTCUtils,
  handleReactNativePermissions,
  optimizeForReactNative 
} from '@webrtc2/utils';

// React Native specific utilities
const rnUtils = new ReactNativeWebRTCUtils();

// Handle permissions
const permissions = await handleReactNativePermissions();
console.log('Permissions granted:', permissions);

// Optimize settings for React Native
const optimizedConfig = optimizeForReactNative({
  video: { width: 640, height: 480 },
  audio: true
});

Electron Utilities

import { 
  ElectronWebRTCUtils,
  getElectronScreenSources,
  handleElectronMediaAccess 
} from '@webrtc2/utils';

// Electron specific utilities
const electronUtils = new ElectronWebRTCUtils();

// Get screen sources for sharing
const screenSources = await getElectronScreenSources();
console.log('Available screens:', screenSources);

// Handle media access in Electron
await handleElectronMediaAccess();

📚 Related Packages

🤝 Contributing

We welcome contributions! Please see our Contributing Guide for details.

📄 License

MIT License - see LICENSE for details.


Keywords: WebRTC utils, WebRTC utilities, device detection, media management, WebRTC error handling, performance optimization, cross-platform WebRTC, React Native WebRTC utils, Electron WebRTC utils, WebRTC debugging