@robono/calling-react-native 0.7.0 → 0.9.0

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.
@@ -7,3 +7,11 @@ android {
7
7
  }
8
8
  dependencies { implementation 'com.facebook.react:react-android' }
9
9
  dependencies { implementation 'com.google.firebase:firebase-messaging:25.0.1' }
10
+ if (findProject(':react-native-webrtc') != null) {
11
+ dependencies {
12
+ implementation project(':react-native-webrtc')
13
+ implementation 'com.google.mlkit:segmentation-selfie:16.0.0-beta6'
14
+ }
15
+ } else {
16
+ android.sourceSets.main.java.exclude '**/VideoBackgrounds.java'
17
+ }
@@ -1,4 +1,5 @@
1
1
  # The native screen-sharing adapter accesses this optional peer reflectively.
2
+ -keep class com.robono.calling.VideoBackgrounds { public <init>(com.facebook.react.bridge.ReactApplicationContext); }
2
3
  -keep class com.oney.WebRTCModule.WebRTCModuleOptions {
3
4
  public static com.oney.WebRTCModule.WebRTCModuleOptions getInstance();
4
5
  public boolean enableMediaProjectionService;
@@ -9,7 +9,11 @@ import java.util.List;
9
9
 
10
10
  public final class CallingPackage implements ReactPackage {
11
11
  public List<NativeModule> createNativeModules(ReactApplicationContext context) {
12
- return java.util.Arrays.asList(new CallingRuntime(context),new SystemCalling(context),new CallingPictureInPicture(context));
12
+ List<NativeModule> modules=new java.util.ArrayList<>(java.util.Arrays.asList(new CallingRuntime(context),new SystemCalling(context),new CallingPictureInPicture(context)));
13
+ try { modules.add((NativeModule)Class.forName("com.robono.calling.VideoBackgrounds").getConstructor(ReactApplicationContext.class).newInstance(context)); }
14
+ catch(ClassNotFoundException absent) { /* Optional custom-media/presentation-only installation. */ }
15
+ catch(ReflectiveOperationException failure) { throw new IllegalStateException("Could not load the video background adapter",failure); }
16
+ return modules;
13
17
  }
14
18
  public List<ViewManager> createViewManagers(ReactApplicationContext context) { return Collections.emptyList(); }
15
19
  }
@@ -0,0 +1,101 @@
1
+ package com.robono.calling;
2
+
3
+ import com.facebook.react.bridge.ReactApplicationContext;
4
+ import com.facebook.react.bridge.ReactContextBaseJavaModule;
5
+ import com.facebook.react.bridge.ReactMethod;
6
+ import com.facebook.react.bridge.Promise;
7
+ import com.oney.WebRTCModule.videoEffects.ProcessorProvider;
8
+ import com.oney.WebRTCModule.videoEffects.VideoFrameProcessor;
9
+ import com.google.mlkit.vision.common.InputImage;
10
+ import com.google.mlkit.vision.segmentation.Segmentation;
11
+ import com.google.mlkit.vision.segmentation.Segmenter;
12
+ import com.google.mlkit.vision.segmentation.selfie.SelfieSegmenterOptions;
13
+ import org.webrtc.VideoFrame;
14
+ import org.webrtc.JavaI420Buffer;
15
+ import org.webrtc.SurfaceTextureHelper;
16
+ import java.nio.ByteBuffer;
17
+ import java.util.Map;
18
+ import java.util.Collections;
19
+ import java.util.ArrayList;
20
+ import java.lang.ref.WeakReference;
21
+
22
+ /** Local camera processing, upstream of preview, WebRTC and call recording. */
23
+ public final class VideoBackgrounds extends ReactContextBaseJavaModule {
24
+ private final ArrayList<WeakReference<Blur>> processors=new ArrayList<>();
25
+ public VideoBackgrounds(ReactApplicationContext context){super(context);}
26
+ @Override public String getName(){return "RobonoVideoBackgrounds";}
27
+ @Override public Map<String,Object> getConstants(){return Collections.singletonMap("blur",true);}
28
+ @ReactMethod public void prepare(Promise promise){
29
+ synchronized(processors){ProcessorProvider.addProcessor("robono-background-blur",()->{Blur value=new Blur();synchronized(processors){processors.add(new WeakReference<>(value));}return value;});}
30
+ promise.resolve(true);
31
+ }
32
+ @ReactMethod public void release(){synchronized(processors){for(WeakReference<Blur> reference:processors){Blur value=reference.get();if(value!=null)value.close();}processors.clear();}}
33
+ @Override public void invalidate(){release();super.invalidate();}
34
+
35
+ private static final class Mask {
36
+ final float[] values;final int width,height,rotation;final long timestamp;
37
+ Mask(float[] values,int width,int height,int rotation,long timestamp){this.values=values;this.width=width;this.height=height;this.rotation=rotation;this.timestamp=timestamp;}
38
+ float alpha(float x,float y){
39
+ float u=rotation==90?1-y:rotation==180?1-x:rotation==270?y:x;
40
+ float v=rotation==90?x:rotation==180?1-y:rotation==270?1-x:y;
41
+ float px=Math.max(0,Math.min(width-1,u*(width-1))),py=Math.max(0,Math.min(height-1,v*(height-1)));
42
+ int a=(int)px,b=(int)py,c=Math.min(a+1,width-1),d=Math.min(b+1,height-1);float fx=px-a,fy=py-b;
43
+ float confidence=(values[b*width+a]*(1-fx)+values[b*width+c]*fx)*(1-fy)+(values[d*width+a]*(1-fx)+values[d*width+c]*fx)*fy;
44
+ return Math.max(0,Math.min(1,(confidence-.15f)/.7f));
45
+ }
46
+ }
47
+ private static final class Blur implements VideoFrameProcessor {
48
+ final Segmenter segmenter=Segmentation.getClient(new SelfieSegmenterOptions.Builder().setDetectorMode(SelfieSegmenterOptions.STREAM_MODE).enableRawSizeMask().build());
49
+ volatile boolean busy=false,closed=false;volatile Mask mask;long lastRequest=0;
50
+ final byte[][] originals=new byte[3][],scratch=new byte[3][],blurred=new byte[3][];
51
+ synchronized void close(){closed=true;mask=null;segmenter.close();}
52
+ void recognize(VideoFrame.I420Buffer image,int rotation,long timestamp){
53
+ if(closed||busy||timestamp-lastRequest<100000000)return;busy=true;lastRequest=timestamp;
54
+ int width=image.getWidth(),height=image.getHeight();float scale=Math.min(1,256f/Math.max(width,height));
55
+ int w=Math.max(2,((int)(width*scale))&~1),h=Math.max(2,((int)(height*scale))&~1);
56
+ VideoFrame.Buffer small=image.cropAndScale(0,0,width,height,w,h);VideoFrame.I420Buffer yuv=small.toI420();
57
+ try{
58
+ byte[] nv21=new byte[w*h*3/2];ByteBuffer y=yuv.getDataY(),u=yuv.getDataU(),v=yuv.getDataV();
59
+ for(int row=0;row<h;row++)for(int col=0;col<w;col++)nv21[row*w+col]=y.get(row*yuv.getStrideY()+col);
60
+ for(int row=0;row<h/2;row++)for(int col=0;col<w/2;col++){int n=w*h+row*w+col*2;nv21[n]=v.get(row*yuv.getStrideV()+col);nv21[n+1]=u.get(row*yuv.getStrideU()+col);}
61
+ segmenter.process(InputImage.fromByteArray(nv21,w,h,rotation,InputImage.IMAGE_FORMAT_NV21))
62
+ .addOnSuccessListener(Runnable::run,result->{if(!closed){ByteBuffer values=result.getBuffer();values.rewind();float[] data=new float[result.getWidth()*result.getHeight()];values.asFloatBuffer().get(data);mask=new Mask(data,result.getWidth(),result.getHeight(),rotation,timestamp);}})
63
+ .addOnFailureListener(Runnable::run,error->{mask=null;})
64
+ .addOnCompleteListener(Runnable::run,task->{busy=false;});
65
+ }catch(Exception error){busy=false;mask=null;}finally{yuv.release();small.release();}
66
+ }
67
+ // Two separable box passes approximate a soft blur without a GPU readback.
68
+ static void box(byte[] src,byte[] temp,byte[] dst,int w,int h,int radius){
69
+ int size=radius*2+1;
70
+ for(int y=0;y<h;y++){int sum=0,offset=y*w;for(int k=-radius;k<=radius;k++)sum+=src[offset+Math.max(0,Math.min(w-1,k))]&255;
71
+ for(int x=0;x<w;x++){temp[offset+x]=(byte)(sum/size);sum-=(src[offset+Math.max(0,x-radius)]&255);sum+=(src[offset+Math.min(w-1,x+radius+1)]&255);}}
72
+ for(int x=0;x<w;x++){int sum=0;for(int k=-radius;k<=radius;k++)sum+=temp[Math.max(0,Math.min(h-1,k))*w+x]&255;
73
+ for(int y=0;y<h;y++){dst[y*w+x]=(byte)(sum/size);sum-=(temp[Math.max(0,y-radius)*w+x]&255);sum+=(temp[Math.min(h-1,y+radius+1)*w+x]&255);}}
74
+ }
75
+ @Override public synchronized VideoFrame process(VideoFrame frame,SurfaceTextureHelper helper){
76
+ int sourceW=frame.getBuffer().getWidth(),sourceH=frame.getBuffer().getHeight();float scale=Math.min(1,640f/Math.max(sourceW,sourceH));
77
+ int width=Math.max(2,((int)(sourceW*scale))&~1),height=Math.max(2,((int)(sourceH*scale))&~1);
78
+ VideoFrame.Buffer scaled=frame.getBuffer().cropAndScale(0,0,sourceW,sourceH,width,height);VideoFrame.I420Buffer input=scaled.toI420();
79
+ JavaI420Buffer output=JavaI420Buffer.allocate(width,height);
80
+ try{
81
+ recognize(input,frame.getRotation(),frame.getTimestampNs());Mask current=mask;
82
+ if(closed||current==null||current.rotation!=frame.getRotation()||frame.getTimestampNs()-current.timestamp>500000000)current=null;
83
+ ByteBuffer[] in={input.getDataY(),input.getDataU(),input.getDataV()},out={output.getDataY(),output.getDataU(),output.getDataV()};
84
+ int[] inputStride={input.getStrideY(),input.getStrideU(),input.getStrideV()},outputStride={output.getStrideY(),output.getStrideU(),output.getStrideV()};
85
+ for(int p=0;p<3;p++){
86
+ int w=p==0?width:width/2,h=p==0?height:height/2,n=w*h;
87
+ if(originals[p]==null||originals[p].length!=n){originals[p]=new byte[n];scratch[p]=new byte[n];blurred[p]=new byte[n];}
88
+ for(int y=0;y<h;y++)for(int x=0;x<w;x++)originals[p][y*w+x]=in[p].get(y*inputStride[p]+x);
89
+ int radius=Math.max(2,w/40);box(originals[p],scratch[p],blurred[p],w,h,radius);
90
+ for(int y=0;y<h;y++)for(int x=0;x<w;x++){float alpha=current==null?0:current.alpha((x+.5f)/w,(y+.5f)/h);int i=y*w+x;out[p].put(y*outputStride[p]+x,(byte)Math.round((originals[p][i]&255)*alpha+(blurred[p][i]&255)*(1-alpha)));}
91
+ }
92
+ return new VideoFrame(output,frame.getRotation(),frame.getTimestampNs());
93
+ }catch(RuntimeException error){
94
+ // Return a neutral frame, not the unprocessed camera, on failure.
95
+ for(int i=0;i<output.getDataY().capacity();i++)output.getDataY().put(i,(byte)32);
96
+ for(ByteBuffer plane:new ByteBuffer[]{output.getDataU(),output.getDataV()})for(int i=0;i<plane.capacity();i++)plane.put(i,(byte)128);
97
+ return new VideoFrame(output,frame.getRotation(),frame.getTimestampNs());
98
+ }finally{input.release();scaled.release();}
99
+ }
100
+ }
101
+ }
@@ -1,7 +1,7 @@
1
1
  import React, { type ReactNode } from 'react';
2
2
  import type { CallHistoryEntry } from '@robono/calling';
3
3
  /** A call record, aligned with its caller. Separate from the text-bubble component. */
4
- export declare function CallRecord({ entry, incomingColor, outgoingColor, textColor, secondaryColor, onCallBack, label, children, showTime }: {
4
+ export interface CallRecordProps {
5
5
  entry: CallHistoryEntry;
6
6
  incomingColor: string;
7
7
  outgoingColor: string;
@@ -16,4 +16,5 @@ export declare function CallRecord({ entry, incomingColor, outgoingColor, textCo
16
16
  };
17
17
  children?: ReactNode;
18
18
  showTime?: boolean;
19
- }): React.JSX.Element;
19
+ }
20
+ export declare function CallRecord({ entry, incomingColor, outgoingColor, textColor, secondaryColor, onCallBack, label, children, showTime }: CallRecordProps): React.JSX.Element;
@@ -2,7 +2,6 @@ import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-run
2
2
  import React from 'react';
3
3
  import { Pressable, StyleSheet, Text, View } from 'react-native';
4
4
  import { RobonoIcon } from './visual/RobonoIcon.js';
5
- /** A call record, aligned with its caller. Separate from the text-bubble component. */
6
5
  export function CallRecord({ entry, incomingColor, outgoingColor, textColor = '#ffffff', secondaryColor, onCallBack, label, children, showTime = false }) {
7
6
  const description = label(entry);
8
7
  const incoming = entry.role === 'callee';
@@ -29,6 +29,8 @@ export interface CallingPresentation {
29
29
  }
30
30
  export declare const callingPresentation: CallingPresentation;
31
31
  export declare const callingText: {
32
+ backgroundBlur: string;
33
+ backgroundUnavailable: string;
32
34
  call: string;
33
35
  videoCall: string;
34
36
  incomingVideo: string;
@@ -19,6 +19,8 @@ export const callingPresentation = {
19
19
  controlShape: "round", showAvatar: true, showCallDescription: true,
20
20
  };
21
21
  export const callingText = {
22
+ backgroundBlur: "Background blur",
23
+ backgroundUnavailable: "Background processing is unavailable. Turn blur off to restore the normal camera.",
22
24
  call: "Voice call",
23
25
  videoCall: "Video call",
24
26
  incomingVideo: "Incoming video call",
@@ -0,0 +1,24 @@
1
+ export type CallBackground = 'off' | 'blur';
2
+ export interface CallBackgroundState {
3
+ available: boolean;
4
+ mode: CallBackground;
5
+ pending: boolean;
6
+ error: string | null;
7
+ }
8
+ export interface CallBackgroundSession {
9
+ stream: MediaStream;
10
+ set(mode: CallBackground): Promise<void>;
11
+ close(): void;
12
+ }
13
+ /** One local preference shared by camera tracks; screen sharing never enters it. */
14
+ export declare function createCallBackgrounds(adapter: {
15
+ available: boolean;
16
+ install(stream: MediaStream, signal: AbortSignal): Promise<CallBackgroundSession>;
17
+ }): {
18
+ getSnapshot: () => CallBackgroundState;
19
+ subscribe(fn: () => void): () => void;
20
+ set(mode: CallBackground): Promise<void>;
21
+ attach(stream: MediaStream, isCurrent?: () => boolean): Promise<MediaStream>;
22
+ dispose(): void;
23
+ };
24
+ export type CallBackgrounds = ReturnType<typeof createCallBackgrounds>;
@@ -0,0 +1,84 @@
1
+ /** One local preference shared by camera tracks; screen sharing never enters it. */
2
+ export function createCallBackgrounds(adapter) {
3
+ let state = { available: adapter.available, mode: 'off', pending: false, error: null }, generation = 0, disposed = false;
4
+ const pending = new Map(), sessions = new Set(), listeners = new Set();
5
+ const emit = (patch) => { state = { ...state, ...patch }; for (const fn of listeners)
6
+ fn(); };
7
+ return {
8
+ getSnapshot: () => state, subscribe(fn) { listeners.add(fn); return () => { listeners.delete(fn); }; },
9
+ async set(mode) {
10
+ if (disposed || !state.available || !['off', 'blur'].includes(mode))
11
+ throw Error('background_unavailable');
12
+ const version = ++generation;
13
+ emit({ mode, pending: true, error: null });
14
+ try {
15
+ await Promise.all([...sessions].map(session => session.set(mode)));
16
+ }
17
+ catch (error) {
18
+ if (version === generation && !disposed)
19
+ emit({ error: 'Background processing is unavailable. Turn blur off to restore the normal camera.' });
20
+ throw error;
21
+ }
22
+ finally {
23
+ if (version === generation && !disposed)
24
+ emit({ pending: false });
25
+ }
26
+ },
27
+ async attach(stream, isCurrent = () => true) {
28
+ if (!stream.getVideoTracks().length || !state.available)
29
+ return stream;
30
+ if (disposed || !isCurrent()) {
31
+ stream.getTracks().forEach(track => track.stop());
32
+ throw Error('call_cancelled');
33
+ }
34
+ const cancellation = new AbortController();
35
+ pending.set(stream, cancellation);
36
+ let session;
37
+ const cancelled = new Promise((_, reject) => cancellation.signal.addEventListener('abort', () => reject(Error('call_cancelled')), { once: true }));
38
+ const check = setInterval(() => { if (disposed || !isCurrent())
39
+ cancellation.abort(); }, 100);
40
+ const deadline = setTimeout(() => cancellation.abort(), 15000);
41
+ try {
42
+ const installation = adapter.install(stream, cancellation.signal).then(value => { if (cancellation.signal.aborted) {
43
+ value.close();
44
+ throw Error('call_cancelled');
45
+ } return value; });
46
+ session = await Promise.race([installation, cancelled]);
47
+ if (disposed || !isCurrent())
48
+ throw Error('call_cancelled');
49
+ sessions.add(session);
50
+ await Promise.race([session.set(state.mode), cancelled]);
51
+ if (disposed || !isCurrent())
52
+ throw Error('call_cancelled');
53
+ const selected = session;
54
+ for (const track of selected.stream.getVideoTracks()) {
55
+ const stop = track.stop.bind(track);
56
+ let stopped = false;
57
+ track.stop = () => { if (stopped)
58
+ return; stopped = true; sessions.delete(selected); stop(); selected.close(); };
59
+ track.addEventListener?.('ended', () => { sessions.delete(selected); selected.close(); }, { once: true });
60
+ }
61
+ return selected.stream;
62
+ }
63
+ catch (error) {
64
+ cancellation.abort();
65
+ if (session)
66
+ sessions.delete(session);
67
+ session?.close();
68
+ stream.getTracks().forEach(track => track.stop());
69
+ throw error;
70
+ }
71
+ finally {
72
+ clearInterval(check);
73
+ clearTimeout(deadline);
74
+ pending.delete(stream);
75
+ }
76
+ },
77
+ dispose() { if (disposed)
78
+ return; disposed = true; generation++; for (const [stream, cancellation] of pending) {
79
+ cancellation.abort();
80
+ stream.getTracks().forEach(track => track.stop());
81
+ } pending.clear(); for (const session of sessions)
82
+ session.close(); sessions.clear(); listeners.clear(); },
83
+ };
84
+ }
@@ -0,0 +1,7 @@
1
+ export declare function createNativeCallBackgrounds(): {
2
+ getSnapshot: () => import("./background-effects.js").CallBackgroundState;
3
+ subscribe(fn: () => void): () => void;
4
+ set(mode: import("./background-effects.js").CallBackground): Promise<void>;
5
+ attach(stream: MediaStream, isCurrent?: () => boolean): Promise<MediaStream>;
6
+ dispose(): void;
7
+ };
@@ -0,0 +1,41 @@
1
+ import { NativeModules, Platform } from 'react-native';
2
+ import { createCallBackgrounds } from './background-effects.js';
3
+ export function createNativeCallBackgrounds() {
4
+ const native = NativeModules.RobonoVideoBackgrounds;
5
+ return createCallBackgrounds({ available: native?.blur === true,
6
+ async install(stream) {
7
+ await native.prepare();
8
+ let closed = false, applied = 'off';
9
+ const tracks = stream.getVideoTracks();
10
+ return { stream, async set(mode) {
11
+ if (closed || mode === applied)
12
+ return;
13
+ for (const track of tracks) {
14
+ if (track.readyState === 'ended')
15
+ continue;
16
+ const enabled = track.enabled;
17
+ track.enabled = false;
18
+ try {
19
+ if (mode === 'off' && Platform.OS === 'android') {
20
+ // WebRTC 124's empty-list processor releases its input twice. Null removes
21
+ // the processor entirely, the native API's supported off path.
22
+ NativeModules.WebRTCModule.mediaStreamTrackSetVideoEffects(track.id, null);
23
+ }
24
+ else
25
+ track._setVideoEffects(mode === 'blur' ? ['robono-background-blur'] : []);
26
+ }
27
+ finally {
28
+ track.enabled = enabled;
29
+ }
30
+ }
31
+ applied = mode;
32
+ if (mode === 'off')
33
+ native.release();
34
+ }, close() { if (closed)
35
+ return; closed = true; for (const track of tracks) {
36
+ if (track.readyState !== 'ended')
37
+ track.stop();
38
+ } native.release(); } };
39
+ },
40
+ });
41
+ }
@@ -1,5 +1,6 @@
1
1
  import React, { type ComponentType, type ReactNode } from 'react';
2
2
  import { type StyleProp, type TextStyle, type ViewStyle } from 'react-native';
3
+ import type { CallDiagnostics } from '@robono/calling';
3
4
  import { callingText, callingIcons, resolveCallingDesign, type CallingAppearance } from './appearance.js';
4
5
  import type { CallingState } from './types.js';
5
6
  export interface CallingTheme {
@@ -66,6 +67,14 @@ export interface CallingScreenComponents {
66
67
  ActionButton?: ComponentType<CallingActionButtonProps>;
67
68
  }
68
69
  export interface CallingScreenProps {
70
+ backgrounds?: import('./background-effects.js').CallBackgrounds;
71
+ recordingController?: import('@robono/calling/recording').CallRecordingController;
72
+ recordingLabels?: Partial<typeof import('./recording.js').callRecordingText>;
73
+ /** Supplied automatically by connected overlays; read only while details are open. */
74
+ getDiagnostics?(): Promise<CallDiagnostics>;
75
+ diagnostics?: false | {
76
+ labels?: Partial<typeof callDiagnosticsText>;
77
+ };
69
78
  /** Allow the connected remote video to use the operating system floating window. */
70
79
  pictureInPicture?: boolean;
71
80
  state: CallingState;
@@ -97,6 +106,11 @@ export interface CallingScreenProps {
97
106
  components?: CallingScreenComponents;
98
107
  }
99
108
  export interface CallingUIValue {
109
+ backgrounds?: CallingScreenProps['backgrounds'];
110
+ recordingController?: CallingScreenProps['recordingController'];
111
+ recordingLabels?: CallingScreenProps['recordingLabels'];
112
+ getDiagnostics?: CallingScreenProps['getDiagnostics'];
113
+ diagnostics?: CallingScreenProps['diagnostics'];
100
114
  pictureInPicture: boolean;
101
115
  renderVideo?: CallingScreenProps['renderVideo'];
102
116
  state: Readonly<CallingState>;
@@ -134,6 +148,21 @@ export declare function CallingActionButton({ action, style, iconStyle, labelSty
134
148
  export declare function CallingAudioControls({ style }?: CallingSectionProps): React.JSX.Element | null;
135
149
  export declare function CallingIncomingControls({ style }?: CallingSectionProps): React.JSX.Element | null;
136
150
  export declare function CallingControls({ style }?: CallingSectionProps): React.JSX.Element;
151
+ export declare const callDiagnosticsText: {
152
+ details: string;
153
+ checking: string;
154
+ unavailable: string;
155
+ good: string;
156
+ fair: string;
157
+ poor: string;
158
+ delay: string;
159
+ loss: string;
160
+ video: string;
161
+ participant: string;
162
+ explanation: string;
163
+ };
164
+ /** Small on-demand panel. Never records audio, submits logs or changes call controls. */
165
+ export declare function CallingConnectionDetails(): React.JSX.Element | null;
137
166
  /** Video uses the same SDK layout, labels and controls on native and web. */
138
167
  export declare function CallingVideo({ style }?: CallingSectionProps): React.JSX.Element | null;
139
168
  export {};
@@ -1,6 +1,6 @@
1
1
  import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
2
- import { createContext, useContext, useEffect, useState } from 'react';
3
- import { Image, Platform, Pressable, ScrollView, StyleSheet, Text, View, useColorScheme } from 'react-native';
2
+ import { createContext, useContext, useEffect, useRef, useState } from 'react';
3
+ import { AppState, Image, Platform, Pressable, ScrollView, StyleSheet, Text, View, useColorScheme } from 'react-native';
4
4
  import { RobonoIcon } from './visual/RobonoIcon.js';
5
5
  import { SafeAreaInsetsContext } from 'react-native-safe-area-context';
6
6
  import { callingText, callingInk, resolveCallingDesign } from './appearance.js';
@@ -52,6 +52,8 @@ export function CallingUIProvider({ children, ...props }) {
52
52
  };
53
53
  const fontFamily = Platform.OS === 'ios' ? design.fontFamily.ios : Platform.OS === 'android' ? design.fontFamily.android : design.fontFamily.web;
54
54
  const value = {
55
+ backgrounds: props.backgrounds, recordingController: props.recordingController, recordingLabels: props.recordingLabels,
56
+ getDiagnostics: props.getDiagnostics, diagnostics: props.diagnostics,
55
57
  state: s, pictureInPicture: props.pictureInPicture !== false, renderVideo: props.renderVideo, appearance: props.appearance, theme: c, labels: t, design,
56
58
  insets: props.insets || safeArea, components: props.components || {},
57
59
  title: s.contact?.name || t.contact,
@@ -130,7 +132,7 @@ export function CallingIncomingControls({ style } = {}) {
130
132
  }
131
133
  /** Essential controls stay visible; secondary tools open above the dock. */
132
134
  function CallingConferenceControls({ style }) {
133
- const { actions, components, state, theme, labels, typography, design } = useCallingUI();
135
+ const { actions, components, state, theme, labels, typography, design, getDiagnostics, diagnostics } = useCallingUI();
134
136
  const Button = components.ActionButton || CallingActionButton;
135
137
  const [expanded, setExpanded] = useState(false);
136
138
  const secondary = (state.kind === 'video' ? ['speaker', 'flip', 'share'] : []).filter(action => actions[action].visible);
@@ -138,7 +140,7 @@ function CallingConferenceControls({ style }) {
138
140
  const icon = { width: 48, height: 48 };
139
141
  const label = typography(12);
140
142
  useEffect(() => { setExpanded(false); }, [state.phase]);
141
- return _jsxs(View, { style: [{ position: 'relative', zIndex: 2, paddingVertical: 8 }, style], children: [expanded && _jsx(View, { testID: "calling-more-tools", style: { marginBottom: 12, width: '100%', maxWidth: 420, alignSelf: 'center', borderRadius: 18, padding: 16, backgroundColor: theme.control }, children: _jsx(View, { style: { flexDirection: 'row', justifyContent: 'space-evenly', gap: 12 }, children: secondary.map(action => _jsx(Button, { action: action, style: compact, iconStyle: icon, labelStyle: label }, action)) }) }), _jsxs(View, { testID: "calling-main-controls", style: { flexDirection: 'row', alignItems: 'flex-start', justifyContent: 'center', gap: 12, maxWidth: 420, width: '100%', alignSelf: 'center' }, children: [_jsx(Button, { action: "mute", style: compact, iconStyle: icon, labelStyle: label }), actions.camera.visible && _jsx(Button, { action: "camera", style: compact, iconStyle: icon, labelStyle: label }), state.kind !== 'video' && _jsx(Button, { action: "speaker", style: compact, iconStyle: icon, labelStyle: label }), secondary.length > 0 && _jsxs(Pressable, { accessibilityRole: "button", accessibilityLabel: labels.more, accessibilityState: { expanded }, onPress: () => setExpanded(value => !value), style: [styles.button, compact], children: [_jsx(View, { style: [styles.circle, icon, { borderRadius: design.controlRadius, backgroundColor: expanded ? theme.foreground : theme.control }], children: _jsx(RobonoIcon, { name: "more", size: 24, color: expanded ? theme.background : theme.foreground }) }), _jsx(Text, { style: [label, { color: theme.foreground, textAlign: 'center' }], children: labels.more })] }), _jsx(Button, { action: "end", style: [compact, { marginLeft: 8 }], iconStyle: icon, labelStyle: label })] })] });
143
+ return _jsxs(View, { style: [{ position: 'relative', zIndex: 2, paddingVertical: 8 }, style], children: [expanded && _jsxs(View, { testID: "calling-more-tools", style: { marginBottom: 12, width: '100%', maxWidth: 420, alignSelf: 'center', borderRadius: 18, padding: 16, backgroundColor: theme.control }, children: [_jsx(View, { style: { flexDirection: 'row', justifyContent: 'space-evenly', gap: 12 }, children: secondary.map(action => _jsx(Button, { action: action, style: compact, iconStyle: icon, labelStyle: label }, action)) }), _jsx(CallingBackgroundControl, {}), _jsx(CallingConnectionDetails, {})] }), _jsxs(View, { testID: "calling-main-controls", style: { flexDirection: 'row', alignItems: 'flex-start', justifyContent: 'center', gap: 12, maxWidth: 420, width: '100%', alignSelf: 'center' }, children: [_jsx(Button, { action: "mute", style: compact, iconStyle: icon, labelStyle: label }), actions.camera.visible && _jsx(Button, { action: "camera", style: compact, iconStyle: icon, labelStyle: label }), state.kind !== 'video' && _jsx(Button, { action: "speaker", style: compact, iconStyle: icon, labelStyle: label }), (secondary.length > 0 || getDiagnostics && diagnostics !== false && state.phase === 'connected') && _jsxs(Pressable, { accessibilityRole: "button", accessibilityLabel: labels.more, accessibilityState: { expanded }, onPress: () => setExpanded(value => !value), style: [styles.button, compact], children: [_jsx(View, { style: [styles.circle, icon, { borderRadius: design.controlRadius, backgroundColor: expanded ? theme.foreground : theme.control }], children: _jsx(RobonoIcon, { name: "more", size: 24, color: expanded ? theme.background : theme.foreground }) }), _jsx(Text, { style: [label, { color: theme.foreground, textAlign: 'center' }], children: labels.more })] }), _jsx(Button, { action: "end", style: [compact, { marginLeft: 8 }], iconStyle: icon, labelStyle: label })] })] });
142
144
  }
143
145
  export function CallingControls({ style } = {}) {
144
146
  const { actions, components, state } = useCallingUI();
@@ -149,7 +151,60 @@ export function CallingControls({ style } = {}) {
149
151
  return _jsxs(View, { style: [{ flexDirection: 'row', justifyContent: 'center', alignItems: 'center', gap: 24, paddingVertical: 8 }, style], children: [actions.resume.visible && _jsx(Button, { action: "resume" }), _jsx(Button, { action: "end", iconStyle: { width: 48, height: 48 }, labelStyle: { fontSize: 12 } })] });
150
152
  if ((state.kind === 'video' || state.group) && ['outgoing', 'connecting', 'connected'].includes(state.phase))
151
153
  return _jsx(CallingConferenceControls, { style: style });
152
- return _jsxs(View, { style: [styles.controls, style], children: [actions.resume.visible && _jsx(Button, { action: "resume" }), actions.mute.visible && _jsx(Audio, {}), actions.close.visible ? _jsx(Button, { action: "close" }) : state.phase === 'incoming' ? _jsx(Incoming, {}) : _jsx(View, { style: styles.row, children: _jsx(Button, { action: "end" }) })] });
154
+ return _jsxs(View, { style: [styles.controls, style], children: [actions.resume.visible && _jsx(Button, { action: "resume" }), actions.mute.visible && _jsx(Audio, {}), _jsx(CallingConnectionDetails, {}), actions.close.visible ? _jsx(Button, { action: "close" }) : state.phase === 'incoming' ? _jsx(Incoming, {}) : _jsx(View, { style: styles.row, children: _jsx(Button, { action: "end" }) })] });
155
+ }
156
+ export const callDiagnosticsText = {
157
+ details: 'Connection details', checking: 'Checking connection…', unavailable: 'Measurements unavailable',
158
+ good: 'Connection looks good', fair: 'Connection may affect the call', poor: 'Connection is struggling',
159
+ delay: 'Round-trip delay', loss: 'Lost incoming data', video: 'Incoming video', participant: 'Participant',
160
+ explanation: 'Estimates from this device. Missing measurements are not treated as zero.',
161
+ };
162
+ /** Small on-demand panel. Never records audio, submits logs or changes call controls. */
163
+ export function CallingConnectionDetails() {
164
+ const { getDiagnostics, diagnostics, state, theme, typography } = useCallingUI();
165
+ const labels = { ...callDiagnosticsText, ...(diagnostics === false ? {} : diagnostics?.labels) };
166
+ const [expanded, setExpanded] = useState(false), [sample, setSample] = useState(null), [unavailable, setUnavailable] = useState(false);
167
+ const [foreground, setForeground] = useState(AppState.currentState !== 'background' && AppState.currentState !== 'inactive');
168
+ const read = useRef(getDiagnostics);
169
+ read.current = getDiagnostics;
170
+ useEffect(() => { const sub = AppState.addEventListener('change', value => setForeground(value === 'active')); return () => sub.remove(); }, []);
171
+ useEffect(() => { setExpanded(false); setSample(null); }, [state.call?.id, state.connectedAt, state.phase]);
172
+ const enabled = !!getDiagnostics && diagnostics !== false && state.phase === 'connected';
173
+ useEffect(() => {
174
+ if (!enabled || !expanded || !foreground) {
175
+ setSample(null);
176
+ return;
177
+ }
178
+ let current = true, timer;
179
+ setUnavailable(false);
180
+ const refresh = async () => { try {
181
+ const result = await read.current();
182
+ if (current) {
183
+ setSample(result);
184
+ setUnavailable(!result.peers.length);
185
+ }
186
+ }
187
+ catch {
188
+ if (current) {
189
+ setSample(null);
190
+ setUnavailable(true);
191
+ }
192
+ }
193
+ finally {
194
+ if (current)
195
+ timer = setTimeout(refresh, 2000);
196
+ } };
197
+ void refresh();
198
+ return () => { current = false; clearTimeout(timer); };
199
+ }, [enabled, expanded, foreground, state.call?.id, state.connectedAt]);
200
+ if (!enabled)
201
+ return null;
202
+ const textStyle = [typography(14), { color: theme.foreground }];
203
+ return _jsxs(View, { style: { width: '100%', maxWidth: 420, alignSelf: 'center' }, children: [_jsxs(Pressable, { accessibilityRole: "button", accessibilityState: { expanded }, accessibilityLabel: labels.details, onPress: () => setExpanded(v => !v), style: { minHeight: 44, alignItems: 'center', justifyContent: 'center', flexDirection: 'row', gap: 8 }, children: [_jsx(RobonoIcon, { name: "activity", size: 18, color: theme.accent }), _jsx(Text, { style: [...textStyle, { color: theme.accent }], children: labels.details })] }), expanded && _jsxs(ScrollView, { testID: "calling-connection-details", style: { maxHeight: 220, backgroundColor: theme.control, borderRadius: 12 }, contentContainerStyle: { padding: 12, gap: 12 }, children: [(!sample?.peers.length) && _jsx(Text, { style: textStyle, children: unavailable ? labels.unavailable : labels.checking }), sample?.peers.map((peer, index) => {
204
+ const losses = peer.media.map(m => m.receiveLossPercent).filter((n) => n !== null), video = peer.media.find(m => m.kind === 'video' && m.width && m.height);
205
+ const title = peer.participant === null ? null : state.groupMembers?.find(m => m.id === peer.participant)?.name ?? `${labels.participant} ${index + 1}`;
206
+ return _jsxs(View, { style: { gap: 5 }, children: [title && _jsx(Text, { style: [...textStyle, { fontWeight: '600' }], children: title }), _jsx(Text, { style: textStyle, children: peer.quality === 'unknown' ? labels.unavailable : labels[peer.quality] }), _jsxs(Text, { style: [typography(13), { color: theme.secondary }], children: [labels.delay, ": ", peer.roundTripMs === null ? '—' : `${Math.round(peer.roundTripMs)} ms`, " \u00B7 ", labels.loss, ": ", losses.length ? `${Math.max(...losses).toFixed(1)}%` : '—'] }), video && _jsxs(Text, { style: [typography(13), { color: theme.secondary }], children: [labels.video, ": ", video.width, " \u00D7 ", video.height, video.framesPerSecond === null ? '' : ` · ${Math.round(video.framesPerSecond)} fps`] })] }, peer.participant ?? index);
207
+ }), _jsx(Text, { style: [typography(12), { color: theme.secondary }], children: labels.explanation })] })] });
153
208
  }
154
209
  const styles = StyleSheet.create({
155
210
  screen: { flexGrow: 1, paddingHorizontal: 24, justifyContent: 'space-between', gap: 40 },
@@ -184,3 +239,11 @@ export function CallingVideo({ style } = {}) {
184
239
  return _jsxs(View, { style: [{ flex: 1, minHeight: 100, borderRadius: 16, overflow: 'hidden', backgroundColor: theme.control }, style], children: [visible && state.remoteStream ? renderVideo({ stream: state.remoteStream, local: false, screen: state.remoteScreenSharing, pictureInPicture: pictureInPicture && state.phase === 'connected', style: { width: '100%', height: '100%' } }) :
185
240
  _jsxs(View, { style: { flex: 1, alignItems: 'center', justifyContent: 'center', gap: 16 }, children: [_jsx(CallingAvatar, { size: 80 }), _jsx(Text, { style: [typography(16), { color: theme.secondary }], children: state.phase === 'held' ? labels.held : labels.connecting })] }), visible && (state.screenSharing || state.remoteScreenSharing) && _jsx(Text, { style: [typography(13), { position: 'absolute', top: 8, left: 8, padding: 6, borderRadius: 5, color: '#ffffff', backgroundColor: '#000000b0' }], children: labels.sharingScreen }), visible && state.localStream && (state.screenSharing || state.cameraEnabled !== false) && _jsx(View, { style: { position: 'absolute', right: 10, bottom: 10, width: 86, height: 114, borderRadius: 10, overflow: 'hidden' }, children: renderVideo({ stream: state.displayStream || state.localStream, local: true, screen: state.screenSharing, style: { width: '100%', height: '100%' } }) })] });
186
241
  }
242
+ function CallingBackgroundControl() {
243
+ const { backgrounds, state, theme, typography, labels } = useCallingUI();
244
+ const [value, setValue] = useState(() => backgrounds?.getSnapshot());
245
+ useEffect(() => { setValue(backgrounds?.getSnapshot()); return backgrounds?.subscribe(() => setValue(backgrounds.getSnapshot())); }, [backgrounds]);
246
+ if (!backgrounds || !value?.available || state.kind !== 'video' || state.screenSharing || !state.localStream?.getVideoTracks().length)
247
+ return null;
248
+ return _jsxs(View, { style: { gap: 4 }, children: [_jsxs(Pressable, { accessibilityRole: "switch", accessibilityLabel: labels.backgroundBlur, accessibilityState: { checked: value.mode === 'blur', busy: value.pending }, onPress: () => { void backgrounds.set(value.mode === 'blur' ? 'off' : 'blur').catch(() => { }); }, style: { minHeight: 44, flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between', gap: 10 }, children: [_jsx(Text, { style: [typography(15), { color: theme.foreground }], children: labels.backgroundBlur }), _jsx(View, { style: { width: 38, height: 22, borderRadius: 11, padding: 3, backgroundColor: value.mode === 'blur' ? theme.accent : theme.secondary, alignItems: value.mode === 'blur' ? 'flex-end' : 'flex-start' }, children: _jsx(View, { style: { width: 16, height: 16, borderRadius: 8, backgroundColor: '#ffffff' } }) })] }), value.error && _jsx(Text, { accessibilityRole: "alert", style: [typography(13), { color: theme.secondary }], children: labels.backgroundUnavailable })] });
249
+ }
@@ -56,7 +56,7 @@ export function createController({ createClient, request, media, audio, resolveC
56
56
  const newIncoming = active && call.role === 'callee' && state.call?.id !== call.id;
57
57
  const previousPhase = state.phase;
58
58
  const cue = phase === 'connected' && previousPhase === 'held' ? 'resumed' : phase === 'idle' && call?.state === 'ended' && state.call?.id === call.id ? (call.reason === 'declined' ? 'declined' : ['no_answer', 'cancelled'].includes(call.reason) ? 'unanswered' : undefined) : undefined;
59
- publish({ screenSharing: !!next.screenSharing, screenSharePending: !!next.screenSharePending, displayStream: next.displayStream, canScreenShare: !!call?.screenSharingAvailable && phase === 'connected', remoteScreenSharing: !!call?.sharing?.some((value, i) => i !== call.self && value), phase, kind: active ? call.kind || 'voice' : state.kind || 'voice', cameraEnabled: next.cameraEnabled !== false, canCamera: !!state.localStream?.getVideoTracks().length && ['outgoing', 'connecting', 'connected'].includes(phase), call: active && !terminalError ? call : null, contact, muted: next.muted,
59
+ publish({ recording: next.recording, screenSharing: !!next.screenSharing, screenSharePending: !!next.screenSharePending, displayStream: next.displayStream, canScreenShare: !!call?.screenSharingAvailable && phase === 'connected', remoteScreenSharing: !!call?.sharing?.some((value, i) => i !== call.self && value), phase, kind: active ? call.kind || 'voice' : state.kind || 'voice', cameraEnabled: next.cameraEnabled !== false, canCamera: !!state.localStream?.getVideoTracks().length && ['outgoing', 'connecting', 'connected'].includes(phase), call: active && !terminalError ? call : null, contact, muted: next.muted,
60
60
  ...(newIncoming ? { speaker: false } : {}),
61
61
  error: next.error, localHeld: !!next.localHeld,
62
62
  ...(phase !== 'held' ? { resumeError: null, resumePending: false } : {}),
@@ -107,6 +107,8 @@ export function createController({ createClient, request, media, audio, resolveC
107
107
  };
108
108
  return {
109
109
  client,
110
+ backgrounds: media.backgrounds,
111
+ getDiagnostics: () => client.getDiagnostics(),
110
112
  getSnapshot: () => state,
111
113
  subscribe(listener) { listeners.add(listener); return () => listeners.delete(listener); },
112
114
  async listen() { if (disposed)
@@ -0,0 +1,22 @@
1
+ import React from 'react';
2
+ import type { CallDeviceCheck } from './device-check.js';
3
+ export declare const callDeviceCheckText: {
4
+ deviceError: string;
5
+ soundError: string;
6
+ microphone: string;
7
+ speak: string;
8
+ unavailable: string;
9
+ opening: string;
10
+ audio: string;
11
+ video: string;
12
+ speaker: string;
13
+ heard: string;
14
+ private: string;
15
+ retry: string;
16
+ };
17
+ export declare function CallDeviceCheckPanel({ check, renderVideo, accent, labels }: {
18
+ check: CallDeviceCheck;
19
+ renderVideo?: (stream: MediaStream) => React.ReactNode;
20
+ accent?: string;
21
+ labels?: Partial<typeof callDeviceCheckText>;
22
+ }): React.JSX.Element;
@@ -0,0 +1,9 @@
1
+ import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
2
+ import { useSyncExternalStore } from 'react';
3
+ import { Pressable, Text, View } from 'react-native';
4
+ export const callDeviceCheckText = { deviceError: 'Allow microphone and camera access in your device settings, then try again.', soundError: 'Sound could not play. Check your volume and selected headphones or speaker.', microphone: 'Microphone', speak: 'Speak to see the microphone level.', unavailable: 'Your device does not report a microphone level.', opening: 'Opening your devices…', audio: 'Check microphone', video: 'Check camera too', speaker: 'Play test sound', heard: 'Did you hear the sound? Check your volume or headphones if not.', private: 'This check stays on your device. Nothing is sent or saved.', retry: 'Try again' };
5
+ export function CallDeviceCheckPanel({ check, renderVideo, accent = '#FF8A2C', labels = {} }) {
6
+ const state = useSyncExternalStore(check.subscribe, check.getSnapshot, check.getSnapshot), text = { ...callDeviceCheckText, ...labels };
7
+ const button = (label, action) => _jsx(Pressable, { accessibilityRole: "button", accessibilityLabel: label, disabled: state.phase === 'opening', onPress: () => void action().catch(() => { }), style: { minHeight: 44, borderRadius: 12, backgroundColor: '#242424', paddingHorizontal: 16, justifyContent: 'center', opacity: state.phase === 'opening' ? .5 : 1 }, children: _jsx(Text, { style: { fontSize: 16, color: accent, fontWeight: '600' }, children: label }) }, label);
8
+ return _jsxs(View, { testID: "calling-device-check", style: { gap: 16 }, children: [_jsx(Text, { style: { color: '#aaa', fontSize: 15 }, children: text.private }), _jsxs(View, { style: { flexDirection: 'row', flexWrap: 'wrap', gap: 8 }, children: [button(text.audio, () => check.start('voice')), button(text.video, () => check.start('video'))] }), state.phase === 'opening' && _jsx(Text, { accessibilityLiveRegion: "polite", style: { color: '#fff', fontSize: 16 }, children: text.opening }), state.stream && state.kind === 'video' && renderVideo && _jsx(View, { style: { height: 240, overflow: 'hidden', borderRadius: 14, backgroundColor: '#151515' }, children: renderVideo(state.stream) }), state.phase === 'ready' && _jsxs(_Fragment, { children: [_jsx(Text, { style: { color: '#fff', fontSize: 17, fontWeight: '600' }, children: text.microphone }), _jsx(View, { accessibilityRole: "progressbar", accessibilityLabel: text.microphone, accessibilityValue: { min: 0, max: 100, now: Math.round((state.level ?? 0) * 100) }, style: { height: 12, borderRadius: 6, overflow: 'hidden', backgroundColor: '#333' }, children: _jsx(View, { style: { height: 12, width: `${Math.round(Math.sqrt(state.level ?? 0) * 100)}%`, backgroundColor: accent } }) }), _jsx(Text, { style: { color: '#aaa', fontSize: 15 }, children: state.level === null ? text.unavailable : text.speak }), button(text.speaker, () => check.speaker()), state.heard && _jsx(Text, { style: { color: '#aaa', fontSize: 15 }, children: text.heard })] }), state.error && _jsx(Text, { accessibilityRole: "alert", style: { color: '#fff', fontSize: 16 }, children: state.phase === 'error' ? text.deviceError : text.soundError })] });
9
+ }
@@ -0,0 +1,25 @@
1
+ /** Local-only device checks. No invitation, server connection or recording is made. */
2
+ export interface CallDeviceCheckState {
3
+ phase: 'idle' | 'opening' | 'ready' | 'error';
4
+ kind: 'voice' | 'video';
5
+ stream: MediaStream | null;
6
+ level: number | null;
7
+ heard: boolean;
8
+ error: string | null;
9
+ }
10
+ export interface CallDeviceCheckAdapter {
11
+ open(kind: 'voice' | 'video', isCurrent: () => boolean): Promise<MediaStream>;
12
+ createPeerConnection(): RTCPeerConnection;
13
+ playTone(): Promise<void>;
14
+ release(): Promise<void>;
15
+ active?(): boolean;
16
+ }
17
+ export declare function createCallDeviceCheck(adapter: CallDeviceCheckAdapter): {
18
+ getSnapshot: () => CallDeviceCheckState;
19
+ subscribe(fn: () => void): () => void;
20
+ start(kind?: "voice" | "video"): Promise<void>;
21
+ speaker(): Promise<void>;
22
+ close: () => Promise<void>;
23
+ dispose(): Promise<void>;
24
+ };
25
+ export type CallDeviceCheck = ReturnType<typeof createCallDeviceCheck>;