@robono/calling-react-native 0.8.0 → 0.9.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -9,3 +9,7 @@ export { callingInk, resolveCallingDesign, defaultCallingAppearance, validateCal
9
9
  export type { CallingAppearance, CallingPresentation, SoundChoice, SoundEvent } from './appearance.js';
10
10
  export { CallingConnectionDetails, callDiagnosticsText, CallingUIProvider, useCallingUI, CallingLayout, CallingBrand, CallingAvatar, CallingContact, CallingStatus, CallingIdentity, CallingVideo, CallingActionButton, CallingAudioControls, CallingIncomingControls, CallingControls, } from './components.js';
11
11
  export type { CallingUIProviderProps, CallingUIValue, CallingScreenComponents, CallingAction, CallingActionModel, CallingSectionProps, CallingLayoutProps, CallingAvatarProps, CallingContactProps, CallingStatusProps, CallingActionButtonProps, } from './components.js';
12
+ export { CallingRecordingControls, callRecordingText } from './recording.js';
13
+ export { createCallDeviceCheck, type CallDeviceCheck, type CallDeviceCheckState, type CallDeviceCheckAdapter } from './device-check.js';
14
+ export { CallDeviceCheckPanel, callDeviceCheckText } from './device-check-panel.js';
15
+ export { createCallBackgrounds, type CallBackgrounds, type CallBackground, type CallBackgroundState, type CallBackgroundSession } from './background-effects.js';
package/dist/index.js CHANGED
@@ -23,3 +23,7 @@ export { CallingScreen, CallingOverlay, useCalling } from './screens.js';
23
23
  export { CallHistoryItem } from './history.js';
24
24
  export { callingInk, resolveCallingDesign, defaultCallingAppearance, validateCallingAppearance, soundCatalog } from './appearance.js';
25
25
  export { CallingConnectionDetails, callDiagnosticsText, CallingUIProvider, useCallingUI, CallingLayout, CallingBrand, CallingAvatar, CallingContact, CallingStatus, CallingIdentity, CallingVideo, CallingActionButton, CallingAudioControls, CallingIncomingControls, CallingControls, } from './components.js';
26
+ export { CallingRecordingControls, callRecordingText } from './recording.js';
27
+ export { createCallDeviceCheck } from './device-check.js';
28
+ export { CallDeviceCheckPanel, callDeviceCheckText } from './device-check-panel.js';
29
+ export { createCallBackgrounds } from './background-effects.js';
@@ -2,6 +2,7 @@ import { type MessengerCallingTransport } from '@robono/calling/messenger';
2
2
  import { type GroupCallingController } from './groups.js';
3
3
  import { type CallingAppearance } from './appearance.js';
4
4
  import type { CallingController, CallingOptions, Contact } from './types.js';
5
+ import type { CallDeviceCheck } from './device-check.js';
5
6
  export interface MessengerCallingState {
6
7
  direct: CallingController | null;
7
8
  group: GroupCallingController | null;
@@ -25,10 +26,19 @@ export interface MessengerCallingOptions {
25
26
  adapters: (appearance: CallingAppearance) => MessengerCallAdapters;
26
27
  resolveContact?: (conversationId: string) => Contact | null;
27
28
  resolveMember?: (appId: string, userId: string) => Contact | null;
29
+ deviceCheck?: (active: () => boolean) => CallDeviceCheck;
28
30
  onUnansweredCall?: CallingOptions['onUnansweredCall'];
29
31
  }
30
32
  /** Account-scoped calls. Owns renewal, listeners and cleanup across navigation. */
31
33
  export declare function createMessengerCalling(options: MessengerCallingOptions): {
34
+ deviceCheck: {
35
+ getSnapshot: () => import("./device-check.js").CallDeviceCheckState;
36
+ subscribe(fn: () => void): () => void;
37
+ start(kind?: "voice" | "video"): Promise<void>;
38
+ speaker(): Promise<void>;
39
+ close: () => Promise<void>;
40
+ dispose(): Promise<void>;
41
+ } | undefined;
32
42
  start: () => Promise<void>;
33
43
  getSnapshot: () => MessengerCallingState;
34
44
  subscribe(fn: () => void): () => void;
package/dist/messenger.js CHANGED
@@ -12,6 +12,9 @@ export function createMessengerCalling(options) {
12
12
  const listeners = new Set();
13
13
  const emit = (patch) => { state = { ...state, ...patch }; listeners.forEach(fn => fn()); };
14
14
  const active = () => [state.direct, state.group].some(c => c && !['idle', 'error'].includes(c.getSnapshot().phase));
15
+ const deviceCheck = options.deviceCheck?.(active);
16
+ const watchCheck = (controller) => controller.subscribe(() => { if (deviceCheck?.getSnapshot().phase !== 'idle' && active())
17
+ void deviceCheck?.close(); });
15
18
  const release = async () => {
16
19
  clearTimeout(timer);
17
20
  const controllers = [state.direct, state.group], old = transport, owned = adapters;
@@ -62,12 +65,14 @@ export function createMessengerCalling(options) {
62
65
  const directAdapter = make();
63
66
  const direct = createCallingController({ ...directAdapter, request: session.request, appearanceRevision: session.revision, resolveContact: options.resolveContact, onUnansweredCall: call => { emit({ unanswered: { id: call.id, conversationId: call.connectionId } }); options.onUnansweredCall?.(call); } });
64
67
  emit({ direct, appearance, features: session.features });
68
+ detach.push(watchCheck(direct));
65
69
  const directDetach = directAdapter.attach?.(direct);
66
70
  if (directDetach)
67
71
  detach.push(directDetach);
68
72
  if (session.features.groups) {
69
73
  const groupAdapter = make(), group = createGroupCallingController({ ...groupAdapter, request: session.request, appearanceRevision: session.revision, resolveGroup: options.resolveContact, resolveMember: options.resolveMember });
70
74
  emit({ group });
75
+ detach.push(watchCheck(group));
71
76
  const groupDetach = groupAdapter.attach?.(group);
72
77
  if (groupDetach)
73
78
  detach.push(groupDetach);
@@ -84,7 +89,7 @@ export function createMessengerCalling(options) {
84
89
  return pending;
85
90
  };
86
91
  return {
87
- start, getSnapshot: () => state, subscribe(fn) { listeners.add(fn); return () => { listeners.delete(fn); }; },
92
+ deviceCheck, start, getSnapshot: () => state, subscribe(fn) { listeners.add(fn); return () => { listeners.delete(fn); }; },
88
93
  isActive: active,
89
94
  reportError(message) { if (!closed)
90
95
  emit({ error: message }); },
@@ -116,6 +121,7 @@ export function createMessengerCalling(options) {
116
121
  async call(conversationId, kind, group = false) {
117
122
  // Retain the browser's user activation before awaiting admission.
118
123
  adapters.forEach(a => a.prime?.());
124
+ await deviceCheck?.close();
119
125
  await start();
120
126
  if (active())
121
127
  throw Error('Finish the current call first.');
@@ -127,6 +133,6 @@ export function createMessengerCalling(options) {
127
133
  await state.direct.call(conversationId, undefined, { kind });
128
134
  },
129
135
  async dispose() { if (closed)
130
- return; closed = true; clearTimeout(timer); await pending?.catch(() => { }); await release(); listeners.clear(); },
136
+ return; closed = true; clearTimeout(timer); await deviceCheck?.dispose(); await pending?.catch(() => { }); await release(); listeners.clear(); },
131
137
  };
132
138
  }
package/dist/native.d.ts CHANGED
@@ -24,3 +24,15 @@ export declare function createNativeCallAdapters(options: NativeAdapterOptions):
24
24
  media: MediaAdapter;
25
25
  audio: CallAudio;
26
26
  };
27
+ /** Foreground-only checks use the same native route policy as calls. */
28
+ export declare function createNativeCallDeviceCheck(options: {
29
+ active: () => boolean;
30
+ restoreAudio: () => Promise<void>;
31
+ }): {
32
+ getSnapshot: () => import("./device-check.js").CallDeviceCheckState;
33
+ subscribe(fn: () => void): () => void;
34
+ start(kind?: "voice" | "video"): Promise<void>;
35
+ speaker(): Promise<void>;
36
+ close: () => Promise<void>;
37
+ dispose(): Promise<void>;
38
+ };
package/dist/native.js CHANGED
@@ -1,3 +1,5 @@
1
+ import { createNativeCallBackgrounds } from './background-native.js';
2
+ import { createCallDeviceCheck } from './device-check.js';
1
3
  import { createNativeCountdown } from './countdown-native.js';
2
4
  import { PermissionsAndroid, Platform, NativeModules, AppState } from 'react-native';
3
5
  import { mediaDevices, MediaStream, RTCPeerConnection } from 'react-native-webrtc';
@@ -11,6 +13,7 @@ let audioOwner = null;
11
13
  export function isNativeCallAudioActive() { return audioOwner !== null; }
12
14
  /** Import this entry point only when choosing the supplied native audio adapter. */
13
15
  export function createNativeCallAdapters(options) {
16
+ const backgrounds = createNativeCallBackgrounds();
14
17
  if (Platform.OS !== 'ios' && Platform.OS !== 'android')
15
18
  throw Error('native_platform_required');
16
19
  let players;
@@ -146,13 +149,14 @@ export function createNativeCallAdapters(options) {
146
149
  audioOwner = null;
147
150
  }
148
151
  },
149
- dispose() { disposed = true; countdown.dispose(); pause(); if (players)
152
+ dispose() { disposed = true; backgrounds.dispose(); countdown.dispose(); pause(); if (players)
150
153
  Object.values(players).forEach(player => player.remove()); players = undefined; },
151
154
  });
152
155
  const countdown = createNativeCountdown({ ready: () => audio.ready(), ownsAudio: () => audioOwner === owner && !disposed && session === 'call', schedule: options.runtime?.schedule, warnings: options.runtime?.warnings, onError: options.onError });
153
156
  audio.countdown = countdown.update;
154
157
  audio.robonoAdapter = true;
155
158
  const media = {
159
+ backgrounds,
156
160
  robonoAdapter: true,
157
161
  createId: randomUUID,
158
162
  createPeerConnection: config => new RTCPeerConnection(config),
@@ -252,8 +256,51 @@ export function createNativeCallAdapters(options) {
252
256
  throw Error('call_cancelled');
253
257
  }
254
258
  route();
255
- return stream;
259
+ return backgrounds.attach(stream, current);
256
260
  },
257
261
  };
258
262
  return { media, audio };
259
263
  }
264
+ /** Foreground-only checks use the same native route policy as calls. */
265
+ export function createNativeCallDeviceCheck(options) {
266
+ const owner = Symbol('device-check');
267
+ let player;
268
+ return createCallDeviceCheck({ active: options.active,
269
+ createPeerConnection: () => new RTCPeerConnection({ iceServers: [] }),
270
+ async open(kind, isCurrent) {
271
+ if (audioOwner || !isCurrent() || AppState.currentState !== 'active')
272
+ throw Error('audio_busy');
273
+ audioOwner = owner;
274
+ if (Platform.OS === 'android') {
275
+ const permissions = [PermissionsAndroid.PERMISSIONS.RECORD_AUDIO, ...(kind === 'video' ? [PermissionsAndroid.PERMISSIONS.CAMERA] : [])];
276
+ const granted = await PermissionsAndroid.requestMultiple(permissions);
277
+ if (permissions.some(p => granted[p] !== PermissionsAndroid.RESULTS.GRANTED))
278
+ throw Error('device_permission_denied');
279
+ }
280
+ if (!isCurrent() || AppState.currentState !== 'active')
281
+ throw Error('device_check_cancelled');
282
+ await setAudioModeAsync({ allowsRecording: true, playsInSilentMode: true, shouldPlayInBackground: false, shouldRouteThroughEarpiece: true, interruptionMode: 'mixWithOthers' });
283
+ if (!isCurrent() || audioOwner !== owner || AppState.currentState !== 'active')
284
+ throw Error('device_check_cancelled');
285
+ InCallManager.start({ media: 'audio' });
286
+ InCallManager.setForceSpeakerphoneOn(null);
287
+ const stream = await mediaDevices.getUserMedia({ audio: true, video: kind === 'video' ? { facingMode: 'user', width: 640, height: 480, frameRate: 20 } : false });
288
+ if (!isCurrent()) {
289
+ stream.getTracks().forEach(t => t.stop());
290
+ throw Error('device_check_cancelled');
291
+ }
292
+ return stream;
293
+ },
294
+ async playTone() { if (audioOwner !== owner)
295
+ throw Error('audio_busy'); player ??= createAudioPlayer(require('../assets/bell.wav'), { keepAudioSessionActive: true }); if (player.currentTime > 0)
296
+ await player.seekTo(0); player.play(); },
297
+ async release() { player?.pause(); player?.remove(); player = undefined; if (audioOwner !== owner)
298
+ return; try {
299
+ InCallManager.stop();
300
+ await options.restoreAudio();
301
+ }
302
+ finally {
303
+ if (audioOwner === owner)
304
+ audioOwner = null;
305
+ } }, });
306
+ }
@@ -0,0 +1,27 @@
1
+ import React from 'react';
2
+ export declare const callRecordingText: {
3
+ you: string;
4
+ caller: string;
5
+ captions: string;
6
+ captionNotice: string;
7
+ captionUnavailable: string;
8
+ record: string;
9
+ audio: string;
10
+ video: string;
11
+ request: string;
12
+ notice: string;
13
+ allow: string;
14
+ decline: string;
15
+ waiting: string;
16
+ preparing: string;
17
+ active: string;
18
+ stop: string;
19
+ saved: string;
20
+ failed: string;
21
+ declined: string;
22
+ cancelled: string;
23
+ error: string;
24
+ close: string;
25
+ };
26
+ /** Shared web/phone controls. A persistent notice is shown throughout capture. */
27
+ export declare function CallingRecordingControls(): React.JSX.Element | null;
@@ -0,0 +1,29 @@
1
+ import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
2
+ import { useEffect, useRef, useState } from 'react';
3
+ import { Pressable, Text, View } from 'react-native';
4
+ import { useCallingUI } from './components.js';
5
+ import { RobonoIcon } from './visual/RobonoIcon.js';
6
+ export const callRecordingText = { you: 'You', caller: 'Caller', captions: 'Include automatic captions and a saved transcript', captionNotice: 'This includes automatic captions and a saved transcript.', captionUnavailable: 'Captions are unavailable. The call recording continues.', record: 'Record call', audio: 'Record audio', video: 'Record video', request: 'Allow this call to be recorded?', notice: 'The company requesting the recording can save this call. Everyone must agree.', allow: 'Allow', decline: 'Decline', waiting: 'Waiting for everyone to agree', preparing: 'Preparing recording', active: 'Recording', stop: 'Stop recording', saved: 'Recording saved', failed: 'Recording could not be saved', declined: 'Recording declined', cancelled: 'Recording cancelled', error: 'Recording is unavailable. Try again.', close: 'Close recording options' };
7
+ /** Shared web/phone controls. A persistent notice is shown throughout capture. */
8
+ export function CallingRecordingControls() {
9
+ const { state, recordingController: controller, recordingLabels, theme, typography } = useCallingUI();
10
+ const text = { ...callRecordingText, ...recordingLabels }, snapshot = state.recording, r = snapshot?.recording;
11
+ const [includeCaptions, setIncludeCaptions] = useState(false);
12
+ const [choose, setChoose] = useState(false), [busy, setBusy] = useState(false), [failure, setFailure] = useState(false);
13
+ const mounted = useRef(true), operation = useRef(0);
14
+ useEffect(() => { mounted.current = true; return () => { mounted.current = false; operation.current++; }; }, []);
15
+ useEffect(() => { operation.current++; setChoose(false); setIncludeCaptions(false); setFailure(false); setBusy(false); }, [state.call?.id, state.phase === 'idle']);
16
+ if (!controller || !snapshot?.available || !['connected', 'held'].includes(state.phase))
17
+ return null;
18
+ const own = state.call?.self ?? state.groupMembers?.find(p => p.local)?.id;
19
+ const consent = r?.state === 'awaiting_consent' && !r.consents.find(p => p.participant === own)?.accepted;
20
+ const active = r && ['awaiting_consent', 'preparing', 'recording', 'stopping'].includes(r.state);
21
+ const run = (work, interrupt = false) => { if (busy && !interrupt)
22
+ return; const current = ++operation.current; setBusy(true); setFailure(false); void work().catch(() => { if (mounted.current && current === operation.current)
23
+ setFailure(true); }).finally(() => { if (mounted.current && current === operation.current)
24
+ setBusy(false); }); };
25
+ const button = (label, action, primary = false, interrupt = false) => _jsx(Pressable, { accessibilityRole: "button", accessibilityLabel: label, accessibilityState: { disabled: busy && !interrupt }, disabled: busy && !interrupt, onPress: action, style: { minHeight: 44, paddingHorizontal: 14, justifyContent: 'center', borderRadius: 12, backgroundColor: primary ? theme.accent : theme.control }, children: _jsx(Text, { style: [typography(15), { color: primary ? theme.background : theme.foreground, fontWeight: '600' }], children: label }) }, label);
26
+ return _jsxs(View, { testID: "calling-recording", style: { width: '100%', maxWidth: 480, alignSelf: 'center', paddingHorizontal: 12, paddingVertical: 6, gap: 6 }, children: [consent ? _jsxs(View, { style: { backgroundColor: theme.control, borderRadius: 16, padding: 14, gap: 8 }, children: [_jsx(Text, { style: [typography(17), { color: theme.foreground, fontWeight: '600' }], children: text.request }), _jsxs(Text, { style: [typography(14), { color: theme.secondary }], children: [text.notice, r?.transcribe ? ' ' + text.captionNotice : ''] }), _jsxs(View, { style: { flexDirection: 'row', gap: 8, justifyContent: 'flex-end' }, children: [button(text.decline, () => run(() => controller.consent(false), true), false, true), button(text.allow, () => run(() => controller.consent(true)), true)] })] }) : active ? _jsxs(View, { style: { flexDirection: 'row', alignItems: 'center', justifyContent: 'center', gap: 10 }, children: [_jsx(View, { style: { width: 9, height: 9, borderRadius: 5, backgroundColor: r.state === 'recording' ? '#EE4848' : theme.accent } }), _jsx(Text, { accessibilityLiveRegion: "polite", style: [typography(15), { color: theme.foreground, flex: 1 }], children: r.state === 'recording' ? text.active : r.state === 'awaiting_consent' ? text.waiting : text.preparing }), button(text.stop, () => run(() => controller.stop(), true), false, true)] }) : _jsxs(_Fragment, { children: [r && ['complete', 'failed', 'declined', 'cancelled'].includes(r.state) && _jsx(Text, { accessibilityLiveRegion: "polite", style: [typography(14), { color: r.state === 'failed' ? theme.accent : theme.secondary, textAlign: 'center' }], children: r.state === 'complete' ? text.saved : r.state === 'failed' ? text.failed : r.state === 'declined' ? text.declined : text.cancelled }), choose ? _jsxs(View, { style: { backgroundColor: theme.control, borderRadius: 14, padding: 10, gap: 6 }, children: [_jsx(Pressable, { accessibilityRole: "button", accessibilityLabel: text.close, onPress: () => setChoose(false), style: { alignSelf: 'flex-end', width: 44, height: 44, alignItems: 'center', justifyContent: 'center' }, children: _jsx(RobonoIcon, { name: "close", size: 22, color: theme.foreground }) }), _jsx(Text, { style: [typography(14), { color: theme.secondary }], children: text.notice }), snapshot.capabilities?.captions && _jsxs(Pressable, { accessibilityRole: "checkbox", "aria-checked": includeCaptions, accessibilityState: { checked: includeCaptions }, accessibilityLabel: text.captions, onPress: () => setIncludeCaptions(v => !v), style: { minHeight: 44, flexDirection: 'row', gap: 10, alignItems: 'center' }, children: [_jsx(View, { style: { width: 20, height: 20, borderWidth: 1, borderRadius: 4, borderColor: theme.accent, backgroundColor: includeCaptions ? theme.accent : 'transparent' } }), _jsx(Text, { style: [typography(14), { color: theme.foreground, flex: 1 }], children: text.captions })] }), _jsxs(View, { style: { flexDirection: 'row', gap: 8, justifyContent: 'center' }, children: [snapshot.capabilities?.audio !== false && button(text.audio, () => run(async () => { await controller.start({ mode: 'audio', transcribe: includeCaptions }); if (mounted.current)
27
+ setChoose(false); }), true), state.kind === 'video' && snapshot.capabilities?.video !== false && button(text.video, () => run(async () => { await controller.start({ mode: 'video', transcribe: includeCaptions }); if (mounted.current)
28
+ setChoose(false); }), true)] })] }) : state.phase === 'connected' && snapshot.capabilities?.available === true && _jsxs(Pressable, { accessibilityRole: "button", accessibilityLabel: text.record, onPress: () => setChoose(true), style: { minHeight: 44, alignItems: 'center', justifyContent: 'center', flexDirection: 'row', gap: 8 }, children: [_jsx(RobonoIcon, { name: "circle-dot", size: 20, color: theme.foreground }), _jsx(Text, { style: [typography(14), { color: theme.foreground }], children: text.record })] })] }), r?.transcript?.captions.length ? _jsx(View, { accessibilityLiveRegion: "polite", style: { backgroundColor: '#111111dd', borderRadius: 12, padding: 10, gap: 4 }, children: r.transcript.captions.slice(-2).map(caption => _jsxs(Text, { numberOfLines: 3, style: [typography(16), { color: '#ffffff' }], children: [state.groupMembers?.find(m => m.id === caption.participant)?.name ?? (caption.participant === own ? text.you : state.contact?.name ?? text.caller), ": ", caption.text] }, caption.participant + ':' + caption.sequence)) }) : null, r?.transcript?.state === 'unavailable' && _jsx(Text, { accessibilityRole: "alert", style: [typography(14), { color: theme.secondary }], children: text.captionUnavailable }), (failure || snapshot.error) && _jsx(Text, { accessibilityRole: "alert", style: [typography(14), { color: theme.accent, textAlign: 'center' }], children: text.error })] });
29
+ }
package/dist/screens.js CHANGED
@@ -4,6 +4,7 @@ import { AppState, Modal, StatusBar, useColorScheme } from 'react-native';
4
4
  import { SafeAreaProvider } from 'react-native-safe-area-context';
5
5
  import { callingInk, resolveCallingDesign } from './appearance.js';
6
6
  import { CallingUIProvider, useCallingUI, CallingLayout, CallingIdentity, CallingControls, CallingVideo } from './components.js';
7
+ import { CallingRecordingControls } from './recording.js';
7
8
  /** The ready-made screen is composed from the same public parts available to apps. */
8
9
  export function CallingScreen(props) {
9
10
  return _jsx(CallingUIProvider, { ...props, children: _jsx(CallingScreenContent, {}) });
@@ -14,7 +15,7 @@ function CallingScreenContent() {
14
15
  const Identity = components.Identity || CallingIdentity;
15
16
  const Controls = components.Controls || CallingControls;
16
17
  const Video = components.Video || CallingVideo;
17
- return _jsxs(Layout, { children: [_jsx(Identity, {}), _jsx(Video, {}), _jsx(Controls, {})] });
18
+ return _jsxs(Layout, { children: [_jsx(Identity, {}), _jsx(Video, {}), _jsx(CallingRecordingControls, {}), _jsx(Controls, {})] });
18
19
  }
19
20
  export function useCalling(controller) {
20
21
  return useSyncExternalStore(controller.subscribe, controller.getSnapshot, controller.getSnapshot);
@@ -30,5 +31,5 @@ export function CallingOverlay({ controller, ...props }) {
30
31
  return () => sub.remove();
31
32
  }, [controller]);
32
33
  const active = state.phase !== 'idle';
33
- return _jsx(Modal, { visible: active, presentationStyle: "fullScreen", animationType: "none", onRequestClose: () => { void controller.hangUp().catch(() => { }); }, children: active && _jsxs(SafeAreaProvider, { children: [_jsx(StatusBar, { barStyle: callingInk(props.theme?.background || design.colors.background) === '#000000' ? 'dark-content' : 'light-content' }), _jsx(CallingScreen, { ...props, getDiagnostics: controller.getDiagnostics, state: state, onResume: () => { void controller.resume().catch(() => { }); }, onAnswer: () => { void controller.answer().catch(() => { }); }, onHangUp: () => { void controller.hangUp().catch(() => { }); }, onMute: value => controller.mute(value), onScreenShare: controller.startScreenSharing ? () => { void (state.screenSharing ? controller.stopScreenSharing?.() : controller.startScreenSharing?.())?.catch(() => { }); } : undefined, onCamera: controller.setCamera ? value => controller.setCamera?.(value) : undefined, onSwitchCamera: controller.switchCamera ? () => { void controller.switchCamera?.(); } : undefined, onSpeaker: value => controller.setSpeaker(value), onClose: () => controller.dismissError() })] }) });
34
+ return _jsx(Modal, { visible: active, presentationStyle: "fullScreen", animationType: "none", onRequestClose: () => { void controller.hangUp().catch(() => { }); }, children: active && _jsxs(SafeAreaProvider, { children: [_jsx(StatusBar, { barStyle: callingInk(props.theme?.background || design.colors.background) === '#000000' ? 'dark-content' : 'light-content' }), _jsx(CallingScreen, { ...props, backgrounds: controller.backgrounds, recordingController: controller.client?.recording, getDiagnostics: controller.getDiagnostics, state: state, onResume: () => { void controller.resume().catch(() => { }); }, onAnswer: () => { void controller.answer().catch(() => { }); }, onHangUp: () => { void controller.hangUp().catch(() => { }); }, onMute: value => controller.mute(value), onScreenShare: controller.startScreenSharing ? () => { void (state.screenSharing ? controller.stopScreenSharing?.() : controller.startScreenSharing?.())?.catch(() => { }); } : undefined, onCamera: controller.setCamera ? value => controller.setCamera?.(value) : undefined, onSwitchCamera: controller.switchCamera ? () => { void controller.switchCamera?.(); } : undefined, onSpeaker: value => controller.setSpeaker(value), onClose: () => controller.dismissError() })] }) });
34
35
  }
package/dist/types.d.ts CHANGED
@@ -5,6 +5,7 @@ export interface Contact {
5
5
  avatarUri?: string;
6
6
  }
7
7
  export interface CallingState {
8
+ recording?: import('@robono/calling/recording').CallRecordingState;
8
9
  resumePending?: boolean;
9
10
  resumeError?: string | null;
10
11
  group?: boolean;
@@ -61,6 +62,7 @@ export interface CallAudio {
61
62
  resume?(): Promise<void>;
62
63
  }
63
64
  export type MediaAdapter = Required<Pick<ConstructorParameters<typeof RobonoCallingClient>[0], 'getUserMedia' | 'createPeerConnection' | 'createRemoteStream' | 'createId'>> & {
65
+ backgrounds?: import('./background-effects.js').CallBackgrounds;
64
66
  robonoAdapter?: boolean;
65
67
  getDisplayMedia?: (context?: {
66
68
  isCurrent: () => boolean;
@@ -82,6 +84,7 @@ export interface CallingOptions {
82
84
  }) => void;
83
85
  }
84
86
  export interface CallingController {
87
+ backgrounds?: import('./background-effects.js').CallBackgrounds;
85
88
  getDiagnostics?(): Promise<import('@robono/calling').CallDiagnostics>;
86
89
  reportComponents?(components: string[]): void;
87
90
  readonly client: RobonoCallingClient;
@@ -1,2 +1,2 @@
1
- export declare const mobileVersion = "0.8.0";
2
- export declare const engineVersion = "0.5.0";
1
+ export declare const mobileVersion = "0.9.1";
2
+ export declare const engineVersion = "0.6.0";
package/dist/versions.js CHANGED
@@ -1,3 +1,3 @@
1
1
  // Generated from the package manifests by build.mjs.
2
- export const mobileVersion = "0.8.0";
3
- export const engineVersion = "0.5.0";
2
+ export const mobileVersion = "0.9.1";
3
+ export const engineVersion = "0.6.0";
@@ -0,0 +1,100 @@
1
+ #import <React/RCTBridgeModule.h>
2
+ #import <Vision/Vision.h>
3
+ #import <CoreImage/CoreImage.h>
4
+ #import <ImageIO/ImageIO.h>
5
+ #import <WebRTC/RTCCVPixelBuffer.h>
6
+ #import <WebRTC/RTCVideoFrame.h>
7
+ #import <react-native-webrtc/ProcessorProvider.h>
8
+ #import <react-native-webrtc/VideoFrameProcessor.h>
9
+
10
+ /** Processes the camera before WebRTC encodes it. No image leaves the device. */
11
+ @interface RobonoBlurProcessor : NSObject <VideoFrameProcessorDelegate>
12
+ @property(nonatomic,strong) CIContext *context;
13
+ @property(nonatomic,strong) VNGeneratePersonSegmentationRequest *request;
14
+ @property(nonatomic,strong) CIImage *mask;
15
+ @property(nonatomic) int64_t maskTime;
16
+ @property(nonatomic) NSInteger rotation;
17
+ @property(nonatomic) CGSize size;
18
+ @property(nonatomic,strong) RTCCVPixelBuffer *neutral;
19
+ @end
20
+
21
+ @implementation RobonoBlurProcessor
22
+ - (instancetype)init {
23
+ if ((self=[super init])) {
24
+ self.context=[CIContext contextWithOptions:@{kCIContextCacheIntermediates:@NO}];
25
+ CVPixelBufferRef pixel=NULL;
26
+ if (CVPixelBufferCreate(kCFAllocatorDefault,16,16,kCVPixelFormatType_32BGRA,(__bridge CFDictionaryRef)@{(NSString *)kCVPixelBufferIOSurfacePropertiesKey:@{}},&pixel)!=kCVReturnSuccess) return nil;
27
+ [self.context render:[[CIImage imageWithColor:[CIColor colorWithRed:0.12 green:0.12 blue:0.12]] imageByCroppingToRect:CGRectMake(0,0,16,16)] toCVPixelBuffer:pixel];
28
+ self.neutral=[[RTCCVPixelBuffer alloc] initWithPixelBuffer:pixel];CVPixelBufferRelease(pixel);
29
+ }
30
+ return self;
31
+ }
32
+ - (void)reset {
33
+ @synchronized(self) { self.mask=nil;self.request=nil;self.maskTime=0;[self.context clearCaches]; }
34
+ }
35
+ - (RTCVideoFrame *)capturer:(RTCVideoCapturer *)capturer didCaptureVideoFrame:(RTCVideoFrame *)frame {
36
+ @synchronized(self) {
37
+ @autoreleasepool {
38
+ CGRect extent=CGRectMake(0,0,frame.buffer.width,frame.buffer.height);
39
+ if (extent.size.width<1 || extent.size.height<1) return [[RTCVideoFrame alloc] initWithBuffer:self.neutral rotation:frame.rotation timeStampNs:frame.timeStampNs];
40
+ CIImage *source=nil;
41
+ CVPixelBufferRef input=NULL;
42
+ if ([frame.buffer isKindOfClass:RTCCVPixelBuffer.class]) {
43
+ input=((RTCCVPixelBuffer *)frame.buffer).pixelBuffer;
44
+ source=[CIImage imageWithCVPixelBuffer:input];
45
+ }
46
+ CIImage *fallback=[[CIImage imageWithColor:[CIColor colorWithRed:0.12 green:0.12 blue:0.12]] imageByCroppingToRect:extent];
47
+ CIImage *background=source?[[[source imageByClampingToExtent] imageByApplyingFilter:@"CIGaussianBlur" withInputParameters:@{kCIInputRadiusKey:@18}] imageByCroppingToRect:extent]:fallback;
48
+ if (self.rotation!=frame.rotation || !CGSizeEqualToSize(self.size,extent.size)) {self.mask=nil;self.maskTime=0;self.request=nil;}
49
+ self.rotation=frame.rotation;self.size=extent.size;
50
+ if (input && (self.maskTime==0 || frame.timeStampNs-self.maskTime>=100000000)) {
51
+ if (!self.request) {
52
+ self.request=[VNGeneratePersonSegmentationRequest new];
53
+ self.request.qualityLevel=VNGeneratePersonSegmentationRequestQualityLevelBalanced;
54
+ self.request.outputPixelFormat=kCVPixelFormatType_OneComponent8;
55
+ }
56
+ CGImagePropertyOrientation orientation=frame.rotation==90?kCGImagePropertyOrientationRight:frame.rotation==180?kCGImagePropertyOrientationDown:frame.rotation==270?kCGImagePropertyOrientationLeft:kCGImagePropertyOrientationUp;
57
+ NSError *error=nil;
58
+ VNImageRequestHandler *handler=[[VNImageRequestHandler alloc] initWithCVPixelBuffer:input orientation:orientation options:@{}];
59
+ if ([handler performRequests:@[self.request] error:&error] && self.request.results.firstObject) {
60
+ CIImage *mask=[CIImage imageWithCVPixelBuffer:((VNPixelBufferObservation *)self.request.results.firstObject).pixelBuffer];
61
+ CGImagePropertyOrientation inverse=frame.rotation==90?kCGImagePropertyOrientationLeft:frame.rotation==180?kCGImagePropertyOrientationDown:frame.rotation==270?kCGImagePropertyOrientationRight:kCGImagePropertyOrientationUp;
62
+ mask=[mask imageByApplyingOrientation:inverse];
63
+ mask=[mask imageByApplyingTransform:CGAffineTransformMakeTranslation(-mask.extent.origin.x,-mask.extent.origin.y)];
64
+ self.mask=[mask imageByApplyingTransform:CGAffineTransformMakeScale(extent.size.width/mask.extent.size.width,extent.size.height/mask.extent.size.height)];
65
+ self.maskTime=frame.timeStampNs;
66
+ } else {self.mask=nil;self.maskTime=frame.timeStampNs;}
67
+ }
68
+ CIImage *result=background;
69
+ if (source && self.mask && frame.timeStampNs-self.maskTime<500000000) result=[source imageByApplyingFilter:@"CIBlendWithMask" withInputParameters:@{kCIInputBackgroundImageKey:background,kCIInputMaskImageKey:self.mask}];
70
+ CVPixelBufferRef output=NULL;
71
+ NSDictionary *attributes=@{(NSString *)kCVPixelBufferIOSurfacePropertiesKey:@{},(NSString *)kCVPixelBufferMetalCompatibilityKey:@YES};
72
+ if (CVPixelBufferCreate(kCFAllocatorDefault,(size_t)extent.size.width,(size_t)extent.size.height,kCVPixelFormatType_32BGRA,(__bridge CFDictionaryRef)attributes,&output)!=kCVReturnSuccess) {
73
+ return [[RTCVideoFrame alloc] initWithBuffer:self.neutral rotation:frame.rotation timeStampNs:frame.timeStampNs];
74
+ }
75
+ CGColorSpaceRef color=CGColorSpaceCreateDeviceRGB();
76
+ [self.context render:[result imageByCroppingToRect:extent] toCVPixelBuffer:output bounds:extent colorSpace:color];
77
+ CGColorSpaceRelease(color);
78
+ RTCVideoFrame *processed=[[RTCVideoFrame alloc] initWithBuffer:[[RTCCVPixelBuffer alloc] initWithPixelBuffer:output] rotation:frame.rotation timeStampNs:frame.timeStampNs];
79
+ CVPixelBufferRelease(output);
80
+ return processed;
81
+ }
82
+ }
83
+ }
84
+ @end
85
+
86
+ @interface RobonoVideoBackgrounds : NSObject <RCTBridgeModule>
87
+ @end
88
+ @implementation RobonoVideoBackgrounds
89
+ RCT_EXPORT_MODULE();
90
+ static RobonoBlurProcessor *blur;
91
+ + (BOOL)requiresMainQueueSetup { return NO; }
92
+ - (NSDictionary *)constantsToExport { return @{@"blur":@YES}; }
93
+ RCT_EXPORT_METHOD(prepare:(RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject) {
94
+ static dispatch_once_t once;
95
+ dispatch_once(&once, ^{blur=[RobonoBlurProcessor new];if(blur)[ProcessorProvider addProcessor:blur forName:@"robono-background-blur"];});
96
+ if(!blur){reject(@"background_unavailable",@"Background processing is unavailable.",nil);return;}
97
+ resolve(@YES);
98
+ }
99
+ RCT_REMAP_METHOD(release, releaseBackgroundResources) { [blur reset]; }
100
+ @end
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@robono/calling-react-native",
3
- "version": "0.8.0",
3
+ "version": "0.9.1",
4
4
  "description": "Optional branded calling screens, sounds and native audio adapters for Robono calling.",
5
5
  "type": "module",
6
6
  "sideEffects": false,
@@ -81,7 +81,7 @@
81
81
  "@types/react": "~19.2.2"
82
82
  },
83
83
  "peerDependencies": {
84
- "@robono/calling": "^0.5.0",
84
+ "@robono/calling": "^0.6.0",
85
85
  "react": ">=18.2 <20",
86
86
  "react-native": ">=0.76 <1",
87
87
  "react-native-svg": ">=15 <16",