import React from 'react'; import { View, Text, ScrollView, Pressable, StyleSheet, TextInput, Clipboard, Switch, PanResponder } from 'react-native'; import { VideoView, useVideoPlayer } from 'expo-video'; import { LinearGradient } from 'expo-linear-gradient'; import Svg, { Path, Polyline, Rect } from 'react-native-svg'; import WebView from 'react-native-webview'; import { MentraVideoStreamReceiverView } from '@mentra/react-native-video-stream-receiver'; import { Header } from '../components/Header'; import { useScrollBottomPadding } from '../components/keyboardLayout'; import { OfflineNotice } from '../components/OfflineNotice'; import { colors } from '../components/theme'; import { isGlassesConnected, isGlassesWifiConnected, streamUptime } from '../sdkFormat'; import { STREAM_DEFAULT_URLS, STREAM_MAX_FPS, STREAM_MIN_FPS, streamPreviewTarget, type BluetoothSdkExampleModel, type StreamPreviewTarget, type StreamProtocol, } from '../useBluetoothSdkExample'; const bars = [18, 32, 48, 24, 40, 56, 30, 44, 22, 36, 50, 28, 40]; function streamSdkCall(useCloudServer: boolean, fps: number) { if (!useCloudServer) { return `const receiver = await MentraVideoStreamReceiver.startWebRtcReceiver(); const streamId = \`rn-\${Date.now()}\`; const started = await BluetoothSdk.startStream({ type: 'start_stream', streamId, streamUrl: receiver.streamUrl, video: { fps: ${fps} }, }); console.log('Stream started', started.status)`; } return `const streamId = \`rn-\${Date.now()}\`; const started = await BluetoothSdk.startStream({ type: 'start_stream', streamId, streamUrl, video: { fps: ${fps} }, }); console.log('Stream started', started.status)`; } export function StreamScreen({ sdk }: { sdk: BluetoothSdkExampleModel }) { const scrollRef = React.useRef>(null); const streamUrlInputRef = React.useRef>(null); const [resolvedConfigExpanded, setResolvedConfigExpanded] = React.useState(false); const scrollBottomPadding = useScrollBottomPadding(); const connected = isGlassesConnected(sdk.glasses); const glassesWifiConnected = isGlassesWifiConnected(sdk.glasses); const streamActive = sdk.streamRequested || sdk.streamStartedAt !== null; const streamStarting = sdk.streamStartPending && !streamActive; const streamButtonDisabled = streamStarting || ((!connected || !glassesWifiConnected) && !streamActive); const wifiRequired = connected && !glassesWifiConnected && !streamActive; const previewReady = streamActive && sdk.streamPreviewReady; const previewPending = streamActive || streamStarting; const uptime = streamUptime(sdk.streamStartedAt); const setupHint = sdk.streamCloudServerEnabled ? localStreamSetupHint(sdk.streamProtocol, sdk.streamUrl, sdk.streamStatus) : null; const previewTarget = sdk.streamCloudServerEnabled && previewReady ? streamPreviewTarget(sdk.streamProtocol, sdk.streamUrl) : null; const sdkCall = streamSdkCall(sdk.streamCloudServerEnabled, sdk.streamFps); const statusFailed = isStreamStatusFailure(sdk.streamStatus); const focusStreamUrlInput = React.useCallback(() => { scrollRef.current?.scrollToEnd({ animated: true }); requestAnimationFrame(() => { streamUrlInputRef.current?.focus(); setTimeout(() => scrollRef.current?.scrollToEnd({ animated: true }), 250); }); }, []); const handleStreamPress = React.useCallback(() => { if (sdk.streamCloudServerEnabled && !streamActive && sdk.streamUrl.includes('')) { focusStreamUrlInput(); } void sdk.toggleStream(); }, [focusStreamUrlInput, sdk, streamActive]); return (
{!connected ? ( ) : wifiRequired ? ( ) : null} {/* Live preview */} {previewTarget ? ( ) : !sdk.streamCloudServerEnabled && previewReady ? ( ) : ( )} {previewReady ? 'LIVE' : previewPending ? 'STARTING' : 'READY'} {uptime} {!previewReady ? ( {previewPending ? 'Waiting for preview' : sdk.streamCloudServerEnabled ? 'Ready · enter stream URL' : 'Ready · WebRTC to phone'} ) : null} {streamActive ? : } {!connected && !streamActive ? 'Connect glasses first' : !glassesWifiConnected && !streamActive ? 'Connect glasses to Wi-Fi' : streamStarting ? 'Starting stream...' : streamActive ? 'End stream' : 'Start stream'} {/* SDK call */} SDK CALL [styles.copyChip, pressed && styles.copyChipPressed]} onPress={() => Clipboard.setString(sdkCall)}> Copy {sdkCall} {sdk.streamStatus} uptime {uptime} · SDK keep-alive setResolvedConfigExpanded((expanded) => !expanded)} /> {/* Protocol */} DESTINATION Use cloud server {sdk.streamCloudServerEnabled ? ( <> {(['rtmp', 'srt', 'webrtc'] satisfies StreamProtocol[]).map((protocol) => ( sdk.selectProtocol(protocol)}> {protocol.toUpperCase()} ))} {streamProtocolLabel(sdk.streamProtocol)} {setupHint ? {setupHint} : null} ) : ( The phone starts a local WebRTC receiver, sends its WHIP URL to the glasses, and previews incoming frames here. )} ); } function ResolvedStreamConfigCard({ config, expanded, onToggle, }: { config: BluetoothSdkExampleModel['streamResolvedConfig']; expanded: boolean; onToggle: () => void; }) { return ( RESOLVED STREAM CONFIG {streamResolvedConfigSummary(config)} {expanded ? 'Hide' : 'Show'} {expanded ? ( {streamResolvedConfigRows(config).map((row) => ( {row.label} {row.value} ))} ) : null} ); } function FpsSlider({ disabled, max, min, onChange, value, }: { disabled: boolean; max: number; min: number; onChange: (value: number) => void; value: number; }) { const trackRef = React.useRef>(null); const trackLeftRef = React.useRef(0); const trackWidthRef = React.useRef(0); const [trackWidth, setTrackWidth] = React.useState(0); const progress = (value - min) / (max - min); const clampedProgress = Math.max(0, Math.min(1, progress)); const clampAndSnap = React.useCallback( (nextValue: number) => Math.max(min, Math.min(max, Math.round(nextValue))), [max, min], ); const updateFromPageX = React.useCallback( (pageX: number, measuredLeft = trackLeftRef.current, measuredWidth = trackWidthRef.current || trackWidth) => { if (disabled || measuredWidth <= 0) { return; } const x = pageX - measuredLeft; const ratio = Math.max(0, Math.min(1, x / measuredWidth)); onChange(clampAndSnap(min + ratio * (max - min))); }, [clampAndSnap, disabled, max, min, onChange, trackWidth], ); const measureAndUpdate = React.useCallback( (pageX: number) => { trackRef.current?.measureInWindow((left, _top, width) => { trackLeftRef.current = left; trackWidthRef.current = width; setTrackWidth(width); updateFromPageX(pageX, left, width); }); }, [updateFromPageX], ); const adjust = React.useCallback( (delta: number) => { if (!disabled) { onChange(clampAndSnap(value + delta)); } }, [clampAndSnap, disabled, onChange, value], ); const panResponder = React.useMemo( () => PanResponder.create({ onStartShouldSetPanResponder: () => !disabled, onMoveShouldSetPanResponder: () => !disabled, onPanResponderGrant: (event) => measureAndUpdate(event.nativeEvent.pageX), onPanResponderMove: (_event, gestureState) => updateFromPageX(gestureState.moveX), }), [disabled, measureAndUpdate, updateFromPageX], ); return ( STREAM FPS {value} fps adjust(-1)} /> { const width = event.nativeEvent.layout.width; trackWidthRef.current = width; setTrackWidth(width); }} style={styles.fpsTrack}> = max} label="+" onPress={() => adjust(1)} /> {min} {disabled ? Read-only while streaming : } {max} ); } function SliderStepButton({ disabled, label, onPress, }: { disabled: boolean; label: string; onPress: () => void; }) { return ( [styles.sliderStepButton, disabled && styles.sliderStepButtonDisabled, pressed && styles.copyChipPressed]}> {label} ); } function PlaceholderStreamPreview({message}: {message?: string}) { return ( {message ? ( {message} ) : ( {bars.map((height, index) => ( ))} )} ); } function LiveStreamPreview({target}: {target: StreamPreviewTarget}) { if (target.kind === 'hls') { return ; } return ( ); } function HlsStreamPreview({url}: {url: string}) { const source = React.useMemo(() => ({uri: url, contentType: 'hls' as const}), [url]); const player = useVideoPlayer(source, (videoPlayer) => { videoPlayer.muted = true; videoPlayer.play(); }); React.useEffect(() => { void player .replaceAsync(source) .then(() => { player.muted = true; player.play(); }) .catch(() => {}); }, [player, source]); return ( ); } function streamProtocolLabel(protocol: StreamProtocol) { return protocol === 'webrtc' ? 'WHIP' : protocol.toUpperCase(); } function streamResolvedConfigSummary( config: BluetoothSdkExampleModel['streamResolvedConfig'], ) { if (!config) { return 'Waiting for stream status from the glasses'; } const video = config.video; return [ config.transport?.toUpperCase(), video ? `${video.width}x${video.height}` : null, video ? `${video.fps} fps` : null, video ? bitrateLabel(video.bitrate) : null, ] .filter(Boolean) .join(' · '); } function streamResolvedConfigRows( config: BluetoothSdkExampleModel['streamResolvedConfig'], ) { if (!config) { return [{label: 'Status', value: 'No resolved config received yet'}]; } const rows = [{label: 'Transport', value: config.transport?.toUpperCase() ?? 'Unknown'}]; if (config.video) { rows.push( {label: 'Video', value: `${config.video.width} x ${config.video.height}`}, { label: 'Capture', value: config.video.captureWidth && config.video.captureHeight ? `${config.video.captureWidth} x ${config.video.captureHeight}` : 'Same as video', }, {label: 'FPS', value: `${config.video.fps}`}, {label: 'Video bitrate', value: bitrateLabel(config.video.bitrate)}, ); } if (config.audio) { rows.push( { label: 'Audio bitrate', value: config.audio.bitrate ? bitrateLabel(config.audio.bitrate) : 'Not reported', }, { label: 'Sample rate', value: config.audio.sampleRate ? `${config.audio.sampleRate} Hz` : 'Not reported', }, { label: 'Echo cancellation', value: config.audio.echoCancellation === undefined ? 'Not reported' : config.audio.echoCancellation ? 'On' : 'Off', }, { label: 'Noise suppression', value: config.audio.noiseSuppression === undefined ? 'Not reported' : config.audio.noiseSuppression ? 'On' : 'Off', }, ); } return rows; } function bitrateLabel(bitsPerSecond: number) { if (bitsPerSecond >= 1_000_000) { return `${(bitsPerSecond / 1_000_000).toFixed(1)} Mbps`; } if (bitsPerSecond >= 1_000) { return `${Math.round(bitsPerSecond / 1_000)} kbps`; } return `${bitsPerSecond} bps`; } function isStreamStatusFailure(status: string) { const normalized = status.toLowerCase(); return ( normalized.includes('failed') || normalized.includes('not reachable') || normalized.includes('required') || normalized.includes('replace') || normalized.includes('error') || normalized.includes('connect the glasses to wi-fi') || normalized.includes('connect glasses first') ); } function streamPreviewWaitingMessage(status: string) { return status.toLowerCase().includes('stalled') ? status : 'Starting stream...\nWaiting for preview'; } function localStreamSetupHint(protocol: StreamProtocol, streamUrl: string, status: string) { if (protocol !== 'rtmp' && protocol !== 'srt' && protocol !== 'webrtc') { return null; } const normalized = status.toLowerCase(); const url = streamUrl.trim(); const needsSetup = url.length === 0 || url.includes('') || url.includes('YOUR_') || normalized.includes('not reachable') || normalized.includes('replace') || normalized.includes('required'); if (!needsSetup) { return null; } if (protocol === 'rtmp') { return 'Local RTMP setup: run python3 local-demo-cloud/server.py, paste the printed RTMP publish URL here, then start streaming. The app previews the derived HLS URL; the printed ffplay command is optional for debugging.'; } if (protocol === 'srt') { return 'Local SRT setup: run python3 local-demo-cloud/server.py, paste the printed SRT publish URL here, then start streaming. The app previews the derived HLS URL; the printed SRT ffplay command is optional for debugging.'; } return 'Local WebRTC setup: run python3 local-demo-cloud/server.py, paste the printed WHIP publish URL here, then start streaming. The app previews the MediaMTX WebRTC page.'; } function StreamPlayIcon() { return ( ); } const styles = StyleSheet.create({ card: { marginHorizontal: 16, marginTop: 8, borderRadius: 28, paddingTop: 8, paddingBottom: 14, borderWidth: 1, borderColor: colors.border, paddingHorizontal: 8 }, previewWrap: { borderRadius: 22, overflow: 'hidden', height: 160 }, preview: { flex: 1, backgroundColor: '#000' }, previewFill: { ...StyleSheet.absoluteFillObject }, glow1: { position: 'absolute', top: -60, left: -40, width: 220, height: 220, borderRadius: 999, backgroundColor: 'rgba(255,255,255,0.18)' }, glow2: { position: 'absolute', bottom: -80, right: -50, width: 240, height: 240, borderRadius: 999, backgroundColor: 'rgba(125,216,158,0.25)' }, livePill: { position: 'absolute', top: 14, left: 14, flexDirection: 'row', alignItems: 'center', gap: 6, backgroundColor: 'rgba(0,0,0,0.45)', paddingVertical: 6, paddingHorizontal: 11, borderRadius: 999, borderWidth: 1, borderColor: 'rgba(255,255,255,0.18)' }, liveDot: { width: 7, height: 7, borderRadius: 999, backgroundColor: colors.redLive }, readyDot: { backgroundColor: colors.greenSoft }, liveText: { color: '#fff', fontSize: 11, fontWeight: '700', letterSpacing: 0.8 }, timer: { position: 'absolute', top: 14, right: 14, color: '#fff', fontSize: 13, fontWeight: '600' }, eqWrap: { position: 'absolute', bottom: 56, left: 0, right: 0, flexDirection: 'row', alignItems: 'flex-end', justifyContent: 'center', gap: 5, height: 56 }, eqBar: { width: 5, borderRadius: 3 }, previewMessage: { position: 'absolute', left: 24, right: 24, top: 58, color: '#fff', fontSize: 16, fontWeight: '600', lineHeight: 21, textAlign: 'center' }, previewMeta: { position: 'absolute', bottom: 14, left: 14, color: 'rgba(255,255,255,0.85)', fontSize: 11, fontWeight: '500' }, endBtn: { flexDirection: 'row', alignItems: 'center', justifyContent: 'center', borderRadius: 18, paddingVertical: 16, marginTop: 14, marginHorizontal: 6, gap: 10 }, stopSquare: { width: 12, height: 12, backgroundColor: '#fff', borderRadius: 3 }, endText: { color: '#fff', fontSize: 15, fontWeight: '600' }, disabled: { opacity: 0.45 }, sdkCard: { marginHorizontal: 16, marginTop: 12, borderRadius: 22, overflow: 'hidden', borderWidth: 1, borderColor: colors.borderSoft }, sdkBlock: { backgroundColor: '#0E1A14', paddingVertical: 14, paddingHorizontal: 16, gap: 8 }, cardHead: { flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between' }, sdkEyebrow: { color: colors.greenAccent, fontSize: 9, fontWeight: '700', letterSpacing: 1.1 }, copyChip: { flexDirection: 'row', alignItems: 'center', minHeight: 36, gap: 5, backgroundColor: 'rgba(255,255,255,0.06)', paddingVertical: 7, paddingHorizontal: 10, borderRadius: 9 }, copyChipPressed: { opacity: 0.6 }, copyText: { color: colors.consoleText, fontSize: 12, fontWeight: '600' }, sdkCode: { color: colors.consoleText, fontSize: 11, lineHeight: 16, fontFamily: 'Courier' }, statusBar: { flexDirection: 'row', alignItems: 'center', paddingVertical: 12, paddingHorizontal: 16, gap: 10 }, statusCircle: { width: 22, height: 22, borderRadius: 999, alignItems: 'center', justifyContent: 'center' }, statusCircleOk: { backgroundColor: 'rgba(52,199,89,0.16)' }, statusCircleError: { backgroundColor: 'rgba(255,59,48,0.16)' }, statusDot: { width: 8, height: 8, borderRadius: 999 }, statusDotOk: { backgroundColor: colors.greenAccent }, statusDotError: { backgroundColor: colors.red }, statusTitle: { color: colors.ink, fontSize: 12, fontWeight: '600' }, statusSub: { color: colors.muted, fontSize: 11, fontWeight: '500' }, resolvedCard: { marginHorizontal: 16, marginTop: 12, borderRadius: 18, paddingVertical: 12, paddingHorizontal: 14, borderWidth: 1, borderColor: colors.borderSoft }, resolvedHeader: { flexDirection: 'row', alignItems: 'center', gap: 12 }, resolvedSummary: { color: colors.ink, fontSize: 12, fontWeight: '600', marginTop: 4 }, resolvedChevron: { color: colors.greenAccent, fontSize: 12, fontWeight: '700' }, resolvedBody: { marginTop: 12, borderTopWidth: 1, borderTopColor: 'rgba(15,42,29,0.08)', paddingTop: 8 }, resolvedRow: { flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between', paddingVertical: 5, gap: 12 }, resolvedLabel: { color: colors.muted, fontSize: 11, fontWeight: '600' }, resolvedValue: { color: colors.ink, fontSize: 12, fontWeight: '600', textAlign: 'right', flexShrink: 1 }, protocolCard: { marginHorizontal: 16, marginTop: 12, borderRadius: 22, paddingVertical: 14, paddingHorizontal: 14, gap: 12, borderWidth: 1, borderColor: colors.borderSoft }, eyebrow: { color: colors.muted, fontSize: 10, fontWeight: '600', letterSpacing: 1.2 }, cloudToggleRow: { flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between', minHeight: 44, backgroundColor: 'rgba(15,42,29,0.04)', borderRadius: 12, paddingVertical: 9, paddingHorizontal: 12 }, cloudToggleLabel: { color: colors.ink, fontSize: 14, fontWeight: '600' }, tabs: { flexDirection: 'row', gap: 4, backgroundColor: 'rgba(15,42,29,0.05)', borderRadius: 14, padding: 4 }, protoTab: { flex: 1, minHeight: 44, paddingVertical: 12, paddingHorizontal: 8, alignItems: 'center', justifyContent: 'center', borderRadius: 10 }, protoTabActive: { backgroundColor: '#fff' }, protoText: { color: colors.muted, fontSize: 13, fontWeight: '500' }, protoTextActive: { color: colors.ink, fontWeight: '700' }, urlBar: { flexDirection: 'row', alignItems: 'center', backgroundColor: 'rgba(15,42,29,0.04)', borderRadius: 12, paddingVertical: 12, paddingHorizontal: 14, gap: 10 }, setupHint: { color: colors.muted, fontSize: 12, fontWeight: '500', lineHeight: 16, backgroundColor: 'rgba(15,42,29,0.04)', borderRadius: 12, paddingVertical: 10, paddingHorizontal: 12 }, method: { color: colors.greenAccent, fontSize: 11, fontWeight: '600', letterSpacing: 0.5 }, divider: { width: 1, height: 14, backgroundColor: 'rgba(15,42,29,0.12)' }, url: { flex: 1, color: colors.ink, fontSize: 13, fontWeight: '500' }, fpsCard: { backgroundColor: 'rgba(15,42,29,0.04)', borderRadius: 12, paddingHorizontal: 14, paddingVertical: 12 }, fpsCardDisabled: { opacity: 0.62 }, fpsHeader: { flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between' }, fpsLabel: { color: colors.muted, fontSize: 10, fontWeight: '700', letterSpacing: 1.1 }, fpsValue: { color: colors.ink, fontSize: 13, fontWeight: '700' }, fpsControlRow: { flexDirection: 'row', alignItems: 'center', gap: 10, marginTop: 8 }, fpsTrack: { flex: 1, height: 40, justifyContent: 'center' }, fpsTrackBase: { position: 'absolute', left: 0, right: 0, height: 8, borderRadius: 999, backgroundColor: 'rgba(15,42,29,0.12)' }, fpsTrackFill: { position: 'absolute', left: 0, height: 8, borderRadius: 999, backgroundColor: colors.greenAccent }, fpsThumb: { position: 'absolute', marginLeft: -14, width: 28, height: 28, borderRadius: 999, backgroundColor: '#fff', borderWidth: 2, borderColor: colors.greenAccent, shadowColor: '#000', shadowOpacity: 0.14, shadowRadius: 5, shadowOffset: {width: 0, height: 2} }, fpsRangeRow: { flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between' }, fpsRangeText: { color: colors.muted, fontSize: 11, fontWeight: '600' }, fpsHint: { color: colors.muted, fontSize: 11, fontWeight: '500' }, sliderStepButton: { width: 34, height: 34, borderRadius: 999, alignItems: 'center', justifyContent: 'center', backgroundColor: 'rgba(255,255,255,0.78)', borderWidth: 1, borderColor: 'rgba(15,42,29,0.08)' }, sliderStepButtonDisabled: { opacity: 0.4 }, sliderStepText: { color: colors.ink, fontSize: 18, lineHeight: 20, fontWeight: '800' }, sliderStepTextDisabled: { color: colors.muted }, });