@displayxr/inline3d 1.47.6 → 1.49.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.
@@ -196,14 +196,23 @@ tile while its content keeps running (for a video: sound, no picture). To put bl
196
196
  tile, give it to an element **behind** the canvas. A cover you mean to hide the tile with (rule 5,
197
197
  rule 11) is the one deliberate exception, and it comes off on a signal.
198
198
 
199
- ### 10. No `backdrop-filter` on anything drawn over the weave
200
-
201
- Rule 7 covers the canvas and its ancestors. This one covers the **siblings on top of it**: a
202
- control bar, a caption, a badge, a menu. `backdrop-filter` is defined as a function of what is
203
- behind the element, and behind it is the interlaced weave. A blur reads the interlaced pixels
204
- and smears them, and the 3D image is disturbed across the element's **whole box**, not only
205
- where the element is opaque (seen on the panel, 24 September). Use a plain translucent tint
206
- (`background: rgba(0, 0, 0, 0.55)`) instead. The SDK's own player chrome follows this rule.
199
+ ### 10. `backdrop-filter` over the weave: only on DisplayXR Browser 0.1.16+, never over a whole tile
200
+
201
+ Rule 7 covers the canvas and its ancestors, and is unchanged. This one covers the **siblings on
202
+ top of it**: a control bar, a caption, a badge, a menu. `backdrop-filter` is defined as a function
203
+ of what is behind the element, and behind it is the interlaced weave. On browsers before
204
+ DisplayXR Browser 0.1.16 the blur reads the interlaced pixels and smears them, and the 3D image is
205
+ disturbed across the element's **whole box**, not only where it is opaque (seen on the panel, 24
206
+ September). From 0.1.16 the compositor draws the tile **mono inside each frost rect**
207
+ (displayxr-browser#120), so frosted chrome over a tile looks right: the frosted region is flat,
208
+ the rest of the tile stays 3D. [`samples/composition`](../samples/composition/) (its sticky
209
+ header) is the validated case.
210
+
211
+ - Frost a **partial** region only (a bar, a pill). Never frost a whole tile while it is visible:
212
+ the whole tile goes mono under it.
213
+ - If the page must also run on older browsers, use a plain translucent tint
214
+ (`background: rgba(0, 0, 0, 0.55)`) there. The SDK's own chrome (player, call) keeps its
215
+ near-solid tint so one build works on every generation.
207
216
 
208
217
  ### 11. Treat a resize as a fresh-canvas moment
209
218
 
@@ -331,11 +340,14 @@ for exactly that reason). It cannot check the join. On a DisplayXR display:
331
340
  Found on hardware in a production photo app after the rules above were written. Each one looked
332
341
  like a runtime or browser bug on the panel and turned out to be the page.
333
342
 
334
- - **No `backdrop-filter` on chrome that sits over the weave.** Rule 7 covers effects on the canvas
335
- and its ancestors. A frosted bar or button placed *over* a woven tile is a different element, but
336
- on a lenticular laptop panel it visibly disturbs the 3D image across that element's whole rect.
337
- Use a plain translucent tint instead (a solid `rgba()` background). Keep an A/B switch for the
338
- blurred variant if the design wants it back, and judge it on the panel, not on a 2D monitor.
343
+ - **`backdrop-filter` on chrome that sits over the weave (superseded for 0.1.16+).** Rule 7 covers
344
+ effects on the canvas and its ancestors. A frosted bar or button placed *over* a woven tile is a
345
+ different element; on browsers before DisplayXR Browser 0.1.16 it visibly disturbed the 3D image
346
+ across that element's whole rect on a lenticular laptop panel, and the fix was a plain
347
+ translucent tint. Since 0.1.16 the compositor draws the tile mono inside each frost rect
348
+ (displayxr-browser#120), so partial frosted chrome is fine there (`samples/composition` is the
349
+ validated case); still never frost a whole visible tile ([rule 10](#10-backdrop-filter-over-the-weave-only-on-displayxr-browser-0116-never-over-a-whole-tile)).
350
+ Judge it on the panel, not on a 2D monitor.
339
351
  - **Nothing opaque above the woven canvas.** Stacking order still applies: an element with an
340
352
  opaque background painted *above* the canvas hides it, and on a draw-order browser that is
341
353
  exactly what you get. The classic case is a full-bleed video plane under a page `<main>` with
@@ -37,7 +37,7 @@ import { mountCall, dxrSignaling } from '../inline3d-call.js';
37
37
 
38
38
  /** Every call event is re-dispatched as `dxr-call:<type>`; `dxr-call:ready` carries the handle. */
39
39
  export const CALL_EVENT_PREFIX = 'dxr-call:';
40
- const CALL_EVENTS = ['joined', 'left', 'peer', 'peerleft', 'state', 'display', 'speaker', 'quality', 'error', 'warning'];
40
+ const CALL_EVENTS = ['joined', 'left', 'peer', 'peerleft', 'state', 'display', 'speaker', 'quality', 'error', 'warning', 'name', 'message', 'signal', 'weave', 'speaking', 'content'];
41
41
  const TAG = '[inline3d/call] <dxr-call>';
42
42
 
43
43
  /** A boolean attribute: present is true, unless its value spells "false"/"0"/"off"/"no". */
@@ -70,9 +70,12 @@ const str = (v) => (v === null || v === undefined || String(v).trim() === '' ? u
70
70
  * | `mono3d="off"` | `mono3D: 'off'` |
71
71
  * | `no-audio` | `audio: false` |
72
72
  * | `no-self-view` | `selfView: false` |
73
+ * | `self-content-view` | `selfContentView: true` |
73
74
  * | `no-auto-converge` | `autoConverge: false` |
75
+ * | `no-send-convergence`| `sendConvergence: false` |
74
76
  * | `cursor="depth"` | `cursor: 'depth'` |
75
- * | `tile-aspect` | `theme.tileAspect` (a number, or `w/h`) |
77
+ * | `tile-aspect` | `theme.tileAspect` (a number, `w/h`, or `fill`) |
78
+ * | `name` | `name` (your display name) |
76
79
  * | `invite-base` | `invite.base` |
77
80
  * | `browser-url` | `landing.browserUrl` |
78
81
  * | `debug` | `debug: true` |
@@ -101,10 +104,13 @@ export function attrsToOpts(source) {
101
104
  if (m3 && /^(off|false|0|no)$/i.test(m3)) o.mono3D = 'off';
102
105
  if (isOn(get('no-audio'))) o.audio = false;
103
106
  if (isOn(get('no-self-view'))) o.selfView = false;
107
+ if (isOn(get('self-content-view'))) o.selfContentView = true;
104
108
  if (isOn(get('no-auto-converge'))) o.autoConverge = false;
109
+ if (isOn(get('no-send-convergence'))) o.sendConvergence = false;
105
110
  if (str(get('cursor')) === 'depth') o.cursor = 'depth';
106
111
  // The C2 groups (RFC 0003 §2): the attribute names are the C1 ones, the option shapes are new.
107
- const theme = { accent: str(get('accent')), tileAspect: num(get('tile-aspect')) };
112
+ put('name', str(get('name')));
113
+ const theme = { accent: str(get('accent')), tileAspect: str(get('tile-aspect')) === 'fill' ? 'fill' : num(get('tile-aspect')) };
108
114
  if (theme.accent !== undefined || theme.tileAspect !== undefined) o.theme = Object.fromEntries(Object.entries(theme).filter(([, v]) => v !== undefined));
109
115
  if (str(get('invite-base'))) o.invite = { base: str(get('invite-base')) };
110
116
  if (str(get('browser-url'))) o.landing = { browserUrl: str(get('browser-url')) };
@@ -3,7 +3,7 @@
3
3
  // 1.29 spellings accepted for one release with a warning. Pure (no DOM, no network) — see
4
4
  // test/call.test.mjs. Internal: importable by path, not part of the `./call` entry.
5
5
 
6
- import { isValidRoomId, parseInviteLink, DEFAULT_MAX_PEERS } from './wire.js';
6
+ import { isValidRoomId, parseInviteLink, DEFAULT_MAX_PEERS, sanitizeName } from './wire.js';
7
7
  import { clampMaxPeers } from './transport.js';
8
8
  import { normalizeMono3D } from './lift.js';
9
9
  import { dxrSignaling } from './signaling.js';
@@ -53,7 +53,10 @@ export function normalizeCallOptions(opts = {}) {
53
53
  const ui = opts.ui === undefined ? true : opts.ui === 'tiles' ? 'tiles' : !!opts.ui;
54
54
  const chrome = ui === true;
55
55
  const tileAspect = theme.tileAspect !== undefined ? theme.tileAspect : opts.tileAspect;
56
- const aspect = typeof tileAspect === 'number' && tileAspect > 0.3 && tileAspect < 4 ? tileAspect : 16 / 9;
56
+ // 'fill': each tile's per-eye aspect is its own stage box (the page sizes the tiles).
57
+ const aspect = tileAspect === 'fill' ? 'fill' : typeof tileAspect === 'number' && tileAspect > 0.3 && tileAspect < 4 ? tileAspect : 16 / 9;
58
+ const layout = opts.layout === 'speaker' ? 'speaker' : opts.layout === 'none' ? 'none' : 'grid';
59
+ const tileCover = opts.tileCover === 'auto' || opts.tileCover === 'off' ? opts.tileCover : layout === 'none' ? 'auto' : 'off';
57
60
  let room = opts.room === undefined || opts.room === null ? 'auto' : opts.room;
58
61
  if (room !== 'auto' && !isValidRoomId(room)) {
59
62
  const fromLink = parseInviteLink(room);
@@ -90,6 +93,10 @@ export function normalizeCallOptions(opts = {}) {
90
93
  // peer's eyes and shift the eyes so it sits at the display plane. The depth slider stays an
91
94
  // offset on top. Off = the pair as sent (plus any `hint`).
92
95
  autoConverge: opts.autoConverge === undefined ? true : !!opts.autoConverge,
96
+ // Sender side of auto-convergence (docs/call.md): with a stereo camera, measure that disparity
97
+ // on this side's own raw frames and send it to every peer (`conv` on the data channel), so
98
+ // receivers apply it instead of measuring the compressed frames. Off = receivers measure.
99
+ sendConvergence: opts.sendConvergence === undefined ? true : !!opts.sendConvergence,
93
100
  // `cursor: 'depth'` (runtime ADR-046 on a pair): the arrow comes in front of a person who pops
94
101
  // out of the screen under it, measured off each stereo tile's two halves; else the plain OS
95
102
  // arrow on the plane. Off by default (zero cost).
@@ -102,12 +109,22 @@ export function normalizeCallOptions(opts = {}) {
102
109
  // Concurrent lifted tiles (`liftOptions.max`). Default = maxPeers (4): every mono peer can be lifted.
103
110
  maxLifted: Number.isFinite(+maxLiftedRaw) && maxLiftedRaw !== null && maxLiftedRaw !== undefined ? Math.max(0, Math.min(DEFAULT_MAX_PEERS, Math.floor(+maxLiftedRaw))) : DEFAULT_MAX_PEERS,
104
111
  // 'grid' | 'speaker' | 'none' (the page lays the tiles out; handle.tile(id) finds them).
105
- layout: opts.layout === 'speaker' ? 'speaker' : opts.layout === 'none' ? 'none' : 'grid',
112
+ layout,
113
+ // The core's rect cover on every woven tile (and a stereo self view): 'auto' covers a tile
114
+ // across a resize or move until it is woven again. Default 'auto' with layout: 'none' (the
115
+ // page moves and resizes the tiles), 'off' otherwise (the module's own layout).
116
+ tileCover,
117
+ // This side's display name (hello.name), sanitised; null = none.
118
+ name: sanitizeName(opts.name),
119
+ // Devices no camera probe opens (openCamera's `exclude`); false = not even the built-in list.
120
+ cameraExclude: opts.cameraExclude === false ? false : Array.isArray(opts.cameraExclude) ? [...opts.cameraExclude] : undefined,
106
121
  // true: full chrome | 'tiles': badges + plates only | false: nothing. `chrome` = the full set.
107
122
  ui,
108
123
  chrome,
109
124
  autoJoin: opts.autoJoin === undefined ? !chrome : !!opts.autoJoin,
110
125
  selfView: opts.selfView === undefined ? true : !!opts.selfView,
126
+ // A woven preview of what this side shares (`shareContent`), as a content tile with id 'self'.
127
+ selfContentView: !!opts.selfContentView,
111
128
  tileAspect: aspect,
112
129
  // theme → the CSS custom properties written on the host, and the string table.
113
130
  cssVars,
@@ -124,6 +141,8 @@ export function normalizeCallOptions(opts = {}) {
124
141
  log: typeof opts.log === 'function' ? opts.log : opts.debug ? (tag, obj) => console.log(`${TAG} ${tag} ${JSON.stringify(obj)}`) : null,
125
142
  // Internal (tests): replaces the lift module importer behind `mono3D: 'auto'`.
126
143
  _liftImporter: typeof opts._liftImporter === 'function' ? opts._liftImporter : undefined,
144
+ // Internal (tests): replaces the sender's frame grab (camera/conv-meter.js grabLumaFrame).
145
+ _convGrab: typeof opts._convGrab === 'function' ? opts._convGrab : undefined,
127
146
  };
128
147
  }
129
148
 
@@ -0,0 +1,147 @@
1
+ // call/share.js — 3D screen share, the page side: find the running DisplayXR apps the browser
2
+ // offers as share sources, and open one as a side-by-side content track for `handle.shareContent()`.
3
+ //
4
+ // PREVIEW tier (docs/sdk-stability.md). The device contract is runtime ADR-061 /
5
+ // `XR_DXR_app_share`: the DisplayXR Browser lists each shareable app as a `videoinput` labelled
6
+ // `DisplayXR: <app> (3D)` with a `dxr-app:` device id, and the opened track describes itself in
7
+ // `getSettings().displayxrStereo` (`source: 'app'`, `appName`, `zeroDisparityShiftFrac`). Browsers
8
+ // that predate those hint fields still use the label and the id, so detection takes any one of the
9
+ // three (camera/app-share.js) and a missing `zeroDisparityShiftFrac` reads as 0 — which is what the
10
+ // runtime sends in v1 anyway: the views are DISPLAY-REFERRED (zero disparity at the sender's display
11
+ // plane), so a receiver applies that known value and never measures the frames.
12
+ //
13
+ // App devices are listed only once the page holds camera permission (ADR-061 decision 17). The
14
+ // runtime asks the user on the SENDER's machine, every start ("Share <app> with <browser>?"), when
15
+ // `openAppShare()` opens the device; a Deny rejects it (`code: 'share-denied'`). The track ends
16
+ // (`ended`) when the app exits or the share is stopped from the runtime side.
17
+
18
+ import { isAppShareDevice, appNameFromLabel, APP_SHARE_ID_PREFIX, APP_SHARE_LABEL_RE } from '../camera/app-share.js';
19
+ import { sanitizeName, CONV_MAX_FRAC } from './wire.js';
20
+
21
+ export { isAppShareDevice, appNameFromLabel, APP_SHARE_ID_PREFIX, APP_SHARE_LABEL_RE };
22
+
23
+ /** What `openAppShare` asks for by default: the runtime's default stream (ADR-061 decision 5). */
24
+ const SHARE_CONSTRAINTS = Object.freeze({ width: 2560, height: 720, frameRate: 30 });
25
+
26
+ const mdOf = (o) => (o && o.mediaDevices) || (globalThis.navigator && navigator.mediaDevices) || null;
27
+
28
+ /**
29
+ * The running apps this browser offers to share: `[{ deviceId, label, appName }]`, in the
30
+ * browser's order. Empty without camera permission (the browser lists none before it), on any
31
+ * other browser, or when nothing is shareable. Never rejects.
32
+ * @param {{ mediaDevices?: MediaDevices }} [o]
33
+ */
34
+ export async function listShareableApps(o = {}) {
35
+ const md = mdOf(o);
36
+ if (!md || typeof md.enumerateDevices !== 'function') return [];
37
+ let list = [];
38
+ try {
39
+ list = await md.enumerateDevices();
40
+ } catch {
41
+ return [];
42
+ }
43
+ return list
44
+ .filter((d) => d && d.kind === 'videoinput' && isAppShareDevice(d))
45
+ .map((d) => Object.freeze({ deviceId: d.deviceId, label: d.label || '', appName: sanitizeName(appNameFromLabel(d.label)) || sanitizeName(d.label) || null }));
46
+ }
47
+
48
+ /**
49
+ * `cb(apps)` now and whenever the list changes (`devicechange`: an app started, exited, or the
50
+ * page was just granted the camera). Returns the unsubscribe.
51
+ * @param {(apps: Array<{deviceId: string, label: string, appName: string|null}>) => void} cb
52
+ * @param {{ mediaDevices?: MediaDevices }} [o]
53
+ */
54
+ export function watchShareableApps(cb, o = {}) {
55
+ if (typeof cb !== 'function') throw new TypeError('@displayxr/inline3d/call: watchShareableApps(cb) takes a function');
56
+ const md = mdOf(o);
57
+ let last = null;
58
+ let live = true;
59
+ let seq = 0;
60
+ const run = async () => {
61
+ const mine = ++seq;
62
+ const apps = await listShareableApps({ mediaDevices: md });
63
+ if (!live || mine !== seq) return; // a newer read is in flight (devicechange bursts)
64
+ const key = JSON.stringify(apps.map((a) => [a.deviceId, a.label]));
65
+ if (key === last) return;
66
+ last = key;
67
+ try {
68
+ cb(apps);
69
+ } catch (err) {
70
+ console.error('[inline3d/call] watchShareableApps listener threw', err);
71
+ }
72
+ };
73
+ const onChange = () => void run();
74
+ if (md && typeof md.addEventListener === 'function') md.addEventListener('devicechange', onChange);
75
+ void run();
76
+ return () => {
77
+ live = false;
78
+ if (md && typeof md.removeEventListener === 'function') md.removeEventListener('devicechange', onChange);
79
+ };
80
+ }
81
+
82
+ /**
83
+ * The content descriptor of an opened share track (what `shareContent` sends): side-by-side, its
84
+ * size, the app name, and the KNOWN convergence — `frac` is the hint's `zeroDisparityShiftFrac`
85
+ * (the disparity of the sender's display plane as a fraction of the per-eye width; 0 in v1, and 0
86
+ * when the browser does not expose it yet). Pure.
87
+ * @param {MediaStreamTrack} track
88
+ * @param {string} [fallbackLabel]
89
+ */
90
+ export function describeAppShare(track, fallbackLabel = '') {
91
+ let st = {};
92
+ try {
93
+ st = (track && typeof track.getSettings === 'function' && track.getSettings()) || {};
94
+ } catch {
95
+ st = {};
96
+ }
97
+ const hint = st.displayxrStereo && typeof st.displayxrStereo === 'object' ? st.displayxrStereo : {};
98
+ const z = hint.zeroDisparityShiftFrac;
99
+ const frac = typeof z === 'number' && Number.isFinite(z) ? Math.max(-CONV_MAX_FRAC, Math.min(CONV_MAX_FRAC, z)) : 0;
100
+ const appName = sanitizeName(hint.appName) || sanitizeName(appNameFromLabel(track && track.label)) || sanitizeName(appNameFromLabel(fallbackLabel)) || null;
101
+ return {
102
+ kind: 'content',
103
+ format: hint.layout && hint.layout !== 'side-by-side' ? 'mono' : 'sbs',
104
+ width: st.width > 0 ? st.width : 0,
105
+ height: st.height > 0 ? st.height : 0,
106
+ convergence: { known: true, frac },
107
+ appName,
108
+ };
109
+ }
110
+
111
+ /**
112
+ * Open one shareable app (a `deviceId` from `listShareableApps`) as a side-by-side track. This is
113
+ * when the runtime asks the user on this machine; Deny rejects with `code: 'share-denied'`. A device
114
+ * that turns out not to be an app share is closed again (`code: 'not-app-share'`). The track is
115
+ * yours: stop it when you stop sharing (`track.stop()`), or the runtime keeps the share open.
116
+ *
117
+ * @param {string} deviceId
118
+ * @param {{ width?: number, height?: number, frameRate?: number, mediaDevices?: MediaDevices }} [o]
119
+ * @returns {Promise<{ stream: MediaStream, track: MediaStreamTrack, descriptor: ReturnType<typeof describeAppShare> }>}
120
+ */
121
+ export async function openAppShare(deviceId, o = {}) {
122
+ if (typeof deviceId !== 'string' || !deviceId) throw Object.assign(new TypeError('@displayxr/inline3d/call: openAppShare(deviceId) needs a deviceId from listShareableApps()'), { code: 'not-app-share' });
123
+ const md = mdOf(o);
124
+ if (!md || typeof md.getUserMedia !== 'function') throw Object.assign(new Error('getUserMedia is not available (insecure context?)'), { code: 'share-failed' });
125
+ const want = (v, d) => ({ ideal: Number.isFinite(v) && v > 0 ? v : d });
126
+ let stream;
127
+ try {
128
+ stream = await md.getUserMedia({
129
+ video: { deviceId: { exact: deviceId }, width: want(o.width, SHARE_CONSTRAINTS.width), height: want(o.height, SHARE_CONSTRAINTS.height), frameRate: want(o.frameRate, SHARE_CONSTRAINTS.frameRate) },
130
+ audio: false,
131
+ });
132
+ } catch (err) {
133
+ const denied = !!err && (err.name === 'NotAllowedError' || err.name === 'PermissionDeniedError' || err.name === 'SecurityError');
134
+ throw Object.assign(new Error(`could not share the app: ${(err && err.message) || err}`), { code: denied ? 'share-denied' : 'share-failed', cause: err });
135
+ }
136
+ const track = stream.getVideoTracks()[0] || null;
137
+ if (!track || !(isAppShareDevice(track) || deviceId.startsWith(APP_SHARE_ID_PREFIX))) {
138
+ stream.getTracks().forEach((t) => t.stop());
139
+ throw Object.assign(new Error('that device is not a shared DisplayXR app'), { code: 'not-app-share' });
140
+ }
141
+ try {
142
+ track.contentHint = 'detail'; // resolution over frame rate: halving an SBS width halves each eye
143
+ } catch {
144
+ /* older engines */
145
+ }
146
+ return { stream, track, descriptor: describeAppShare(track) };
147
+ }
@@ -6,7 +6,8 @@
6
6
  //
7
7
  // transport.start({ room, localStream, onPeer, onPeerLeft, onStream, onMessage, onPeerState })
8
8
  // transport.send(peerId, msg) / broadcast(msg)
9
- // transport.replaceVideoTrack(track) / setSendFormat(format)
9
+ // transport.replaceTrack(kind, track, stream, { slot }) / setSendFormat(format)
10
+ // transport.addContentTransceiver(peerId) // the content track (3D app share), see below
10
11
  // transport.peerConnection(peerId) // for getStats (null on an SFU)
11
12
  // transport.stop()
12
13
  //
@@ -24,6 +25,19 @@
24
25
  // and a late ICE candidate or answer from a dead connection is dropped instead of poisoning the
25
26
  // new one.
26
27
  //
28
+ // THE CONTENT TRACK (3D app share, docs/call.md § Sharing a 3D app): a SECOND video transceiver
29
+ // per pair, sendrecv, so either side can share into it. It exists only when BOTH hellos said
30
+ // `content: true` — the call module calls addContentTransceiver(pid) when the peer's hello says
31
+ // so (its own always does) — so an older peer is never offered a second video m-line and never
32
+ // gets a second camera sender. The offerer adds it (null track until someone shares) and
33
+ // renegotiates with a same-generation re-offer (the answerer's 'offer' case takes it on the same
34
+ // connection); a rebuild re-adds it in the first offer. It is identified as the SECOND video
35
+ // transceiver in getTransceivers() order on both ends: that order is m-line order (the offerer
36
+ // created them in that order; the answerer's are created from the offer's m-lines, and it never
37
+ // adds its own), and m-lines are never reordered or reused here — so both ends agree with no mid
38
+ // or msid bookkeeping. Sharing is then a replaceTrack on that sender only (no renegotiation), and
39
+ // its frames reach the far end's onContentStream, never the camera stream.
40
+ //
27
41
  // RECOVERY LADDER on a pair that stops working: 'disconnected' for 4 s, or 'failed' → ICE restart
28
42
  // on the SAME connection (cheap: keeps the transceivers, renegotiates candidates) → if that has
29
43
  // not connected within 10 s, tear down and rebuild with exponential backoff (1 s, 2 s, 4 s … 30 s,
@@ -44,6 +58,8 @@ const ANSWERER_WAIT_MS = 8000;
44
58
  * keeps retrying underneath it the whole time.
45
59
  */
46
60
  export const UNREACHABLE_MS = 10000;
61
+ /** The camera's share of its bitrate while this side shares content (tuneSenders). */
62
+ export const CAMERA_SHARE_FACTOR = 0.6;
47
63
 
48
64
  /**
49
65
  * Clamp the requested room size to what a full mesh can carry.
@@ -86,6 +102,9 @@ export class MeshTransport {
86
102
  this.stopped = false;
87
103
  this.sendFormat = 'mono';
88
104
  this.localStream = null;
105
+ // The content track this side shares (null = not sharing) and the stream it rides in.
106
+ this.contentTrack = null;
107
+ this.contentStream = null;
89
108
  }
90
109
 
91
110
  /** Remote peers currently in the mesh (not counting this one). */
@@ -93,10 +112,12 @@ export class MeshTransport {
93
112
  return this.peers.size;
94
113
  }
95
114
 
96
- async start({ room, localStream, sendFormat, onPeer, onPeerLeft, onStream, onMessage, onPeerState, onRefused, onSignalingState, onGhost }) {
115
+ async start({ room, localStream, sendFormat, contentTrack, contentStream, onPeer, onPeerLeft, onStream, onContentStream, onMessage, onPeerState, onRefused, onSignalingState, onGhost }) {
97
116
  this.localStream = localStream;
98
117
  this.sendFormat = sendFormat || 'mono';
99
- this.cb = { onPeer, onPeerLeft, onStream, onMessage, onPeerState, onRefused, onSignalingState, onGhost };
118
+ if (contentTrack !== undefined) this.contentTrack = contentTrack || null;
119
+ if (contentStream !== undefined) this.contentStream = contentStream || null;
120
+ this.cb = { onPeer, onPeerLeft, onStream, onContentStream, onMessage, onPeerState, onRefused, onSignalingState, onGhost };
100
121
  // Hooks can fire before join() resolves (the PeerJS adapter discovers peers while joining);
101
122
  // queue them so every one runs against a fully-initialised transport.
102
123
  const later = (fn) => (...a) => (this.ready ? fn(...a) : this._pending.push(() => fn(...a)));
@@ -178,6 +199,11 @@ export class MeshTransport {
178
199
  gen: 0,
179
200
  state: 'new',
180
201
  stream: null,
202
+ // Content (3D app share): both hellos said `content` (contentCap), and the far end's
203
+ // content track once it arrived, in its own stream.
204
+ contentCap: false,
205
+ contentStream: null,
206
+ renegotiate: false,
181
207
  attempts: 0,
182
208
  iceRestarted: false,
183
209
  absent: false,
@@ -201,6 +227,11 @@ export class MeshTransport {
201
227
  rec.iceRestarted = false;
202
228
  rec.pendingCandidates = [];
203
229
  rec.stream = null; // a new connection's tracks arrive in a new stream (a fresh srcObject)
230
+ rec.renegotiate = false;
231
+ if (rec.contentStream) {
232
+ rec.contentStream = null;
233
+ this.cb.onContentStream?.(rec.id, null);
234
+ }
204
235
  const pc = new this.PC({ iceServers: this.iceServers });
205
236
  rec.pc = pc;
206
237
  const dc = pc.createDataChannel('dxr-call', { negotiated: true, id: 0, ordered: true });
@@ -213,11 +244,20 @@ export class MeshTransport {
213
244
  pc.addTransceiver(audio || 'audio', { direction: 'sendrecv', streams });
214
245
  const vt = pc.addTransceiver(video || 'video', { direction: 'sendrecv', streams });
215
246
  this._preferCodecs(vt);
247
+ // A rebuild of a pair that already agreed on content offers its transceiver at once.
248
+ if (rec.contentCap) this._addContent(rec, pc);
216
249
  }
217
250
  pc.onicecandidate = (e) => {
218
251
  if (e.candidate) this._signal(rec, { kind: 'candidate', candidate: e.candidate.toJSON ? e.candidate.toJSON() : e.candidate });
219
252
  };
220
253
  pc.ontrack = (e) => {
254
+ if (rec.pc !== pc) return;
255
+ if (this._isContent(pc, e.transceiver, e.track)) {
256
+ // The far end's content track: its own stream, never the camera's (no eviction).
257
+ rec.contentStream = new MediaStream([e.track]);
258
+ this.cb.onContentStream?.(rec.id, rec.contentStream);
259
+ return;
260
+ }
221
261
  if (!rec.stream) rec.stream = new MediaStream();
222
262
  if (!rec.stream.getTracks().includes(e.track)) {
223
263
  for (const t of rec.stream.getTracks()) if (t.kind === e.track.kind) rec.stream.removeTrack(t);
@@ -269,12 +309,18 @@ export class MeshTransport {
269
309
  await pc.setLocalDescription(answer);
270
310
  this._signal(rec, { kind: 'answer', sdp: pc.localDescription.sdp });
271
311
  this._flushCandidates(rec);
312
+ if (rec.state === 'connected') this.tuneSenders(); // a re-offer may have added the content sender
272
313
  break;
273
314
  }
274
315
  case 'answer':
275
316
  if (!rec.offerer || gen !== rec.gen || !rec.pc || rec.pc.signalingState !== 'have-local-offer') return;
276
317
  await rec.pc.setRemoteDescription({ type: 'answer', sdp: data.sdp });
277
318
  this._flushCandidates(rec);
319
+ if (rec.renegotiate) {
320
+ // A content transceiver was added while this offer was out: offer again.
321
+ rec.renegotiate = false;
322
+ this._offer(rec).catch((err) => this.log('offer-error', { peer: rec.id, err: String(err) }));
323
+ } else if (rec.state === 'connected') this.tuneSenders();
278
324
  break;
279
325
  case 'candidate':
280
326
  if (gen !== rec.gen || !rec.pc) return;
@@ -305,11 +351,25 @@ export class MeshTransport {
305
351
  for (const c of list) rec.pc.addIceCandidate(c).catch(() => {});
306
352
  }
307
353
 
308
- /** Answerer side: put our tracks on the transceivers the offer created, and make them sendrecv. */
354
+ /**
355
+ * Answerer side: put our tracks on the transceivers the offer created, and make them sendrecv.
356
+ * The content transceiver (the second video one) never gets the camera: it gets this side's
357
+ * content track when it is sharing, else stays empty (but sendrecv, so it can share later).
358
+ */
309
359
  _attachAnswererTracks(rec) {
310
360
  const pc = rec.pc;
311
361
  const tracks = this.localStream ? this.localStream.getTracks() : [];
362
+ const content = this._contentTransceiver(pc);
363
+ if (content) {
364
+ if (this.contentTrack && content.sender.track !== this.contentTrack) {
365
+ content.sender.replaceTrack(this.contentTrack).catch(() => {});
366
+ if (this.contentStream && content.sender.setStreams) content.sender.setStreams(this.contentStream);
367
+ }
368
+ content.direction = 'sendrecv';
369
+ this._preferCodecs(content);
370
+ }
312
371
  for (const tr of pc.getTransceivers()) {
372
+ if (tr === content) continue;
313
373
  const kind = tr.receiver && tr.receiver.track ? tr.receiver.track.kind : null;
314
374
  if (!kind || tr.sender.track) continue;
315
375
  const t = tracks.find((x) => x.kind === kind);
@@ -322,6 +382,61 @@ export class MeshTransport {
322
382
  }
323
383
  }
324
384
 
385
+ // ── the content transceiver ─────────────────────────────────────────────────────────────
386
+
387
+ /** The video transceivers of a connection, in getTransceivers() (= m-line) order. */
388
+ _videoTransceivers(pc) {
389
+ if (!pc || typeof pc.getTransceivers !== 'function') return [];
390
+ return pc.getTransceivers().filter((tr) => tr && tr.receiver && tr.receiver.track && tr.receiver.track.kind === 'video');
391
+ }
392
+
393
+ /** The content transceiver: the SECOND video transceiver (see the header), or null. */
394
+ _contentTransceiver(pc) {
395
+ return this._videoTransceivers(pc)[1] || null;
396
+ }
397
+
398
+ /** Is this incoming track (ontrack) the far end's content track? */
399
+ _isContent(pc, transceiver, track) {
400
+ const ct = this._contentTransceiver(pc);
401
+ if (!ct) return false;
402
+ if (transceiver) return transceiver === ct;
403
+ return !!(track && ct.receiver && ct.receiver.track === track);
404
+ }
405
+
406
+ _addContent(rec, pc) {
407
+ if (this._contentTransceiver(pc)) return this._contentTransceiver(pc);
408
+ const streams = this.contentStream ? [this.contentStream] : [];
409
+ const tr = pc.addTransceiver(this.contentTrack || 'video', { direction: 'sendrecv', streams });
410
+ this._preferCodecs(tr);
411
+ return tr;
412
+ }
413
+
414
+ /**
415
+ * Both hellos of this pair said `content`: give it the content transceiver. Offerer only (the
416
+ * answerer gets it in the offer); idempotent. Renegotiates with a same-generation re-offer, or
417
+ * after the offer in flight is answered. False when this side cannot (answerer, unknown peer).
418
+ */
419
+ addContentTransceiver(pid) {
420
+ const rec = this.peers.get(pid);
421
+ if (!rec || this.stopped) return false;
422
+ rec.contentCap = true;
423
+ if (!rec.offerer) return false;
424
+ const pc = rec.pc;
425
+ if (!pc) return true; // the next build adds it
426
+ if (this._contentTransceiver(pc)) return true;
427
+ this._addContent(rec, pc);
428
+ this.log('content-transceiver', { peer: rec.id, gen: rec.gen });
429
+ if (pc.signalingState === 'stable') this._offer(rec).catch((err) => this.log('offer-error', { peer: rec.id, err: String(err) }));
430
+ else rec.renegotiate = true;
431
+ return true;
432
+ }
433
+
434
+ /** Does this pair carry a content transceiver right now? */
435
+ hasContent(pid) {
436
+ const rec = this.peers.get(pid);
437
+ return !!(rec && rec.pc && this._contentTransceiver(rec.pc));
438
+ }
439
+
325
440
  _preferCodecs(transceiver) {
326
441
  const caps = globalThis.RTCRtpReceiver && RTCRtpReceiver.getCapabilities && RTCRtpReceiver.getCapabilities('video');
327
442
  this._canPreferCodecs = !!(transceiver && transceiver.setCodecPreferences && caps);
@@ -402,6 +517,10 @@ export class MeshTransport {
402
517
  clearTimeout(rec.waitTimer);
403
518
  this._closePc(rec);
404
519
  this.peers.delete(rec.id);
520
+ if (rec.contentStream) {
521
+ rec.contentStream = null;
522
+ this.cb.onContentStream?.(rec.id, null);
523
+ }
405
524
  this._setState(rec, 'left');
406
525
  this.cb.onPeerLeft?.(rec.id, reason);
407
526
  this.tuneSenders();
@@ -501,6 +620,16 @@ export class MeshTransport {
501
620
  for (const pid of this.peers.keys()) this.send(pid, msg);
502
621
  }
503
622
 
623
+ /** An already-serialised message (the app channel: sized before it is sent). */
624
+ sendRaw(pid, json) {
625
+ const rec = this.peers.get(pid);
626
+ if (rec && rec.dc && rec.dc.readyState === 'open') {
627
+ rec.dc.send(json);
628
+ return true;
629
+ }
630
+ return false;
631
+ }
632
+
504
633
  peerConnection(pid) {
505
634
  const rec = this.peers.get(pid);
506
635
  return rec ? rec.pc : null;
@@ -513,12 +642,29 @@ export class MeshTransport {
513
642
 
514
643
  // ── sending ─────────────────────────────────────────────────────────────────────────────
515
644
 
516
- /** Swap the outgoing video (setCamera). No renegotiation: replaceTrack on every sender. */
517
- async replaceTrack(kind, track, stream) {
518
- if (stream) this.localStream = stream;
645
+ /**
646
+ * Swap an outgoing track. No renegotiation: replaceTrack on the senders of that slot.
647
+ * `slot: 'camera'` (default — setCamera / setMic): every sender of that kind EXCEPT the content
648
+ * one. `slot: 'content'` (shareContent / stopContent, video only): the content sender of every
649
+ * pair that has one; `track: null` stops sharing. A pair that gets its content transceiver later
650
+ * picks the current content track up then.
651
+ */
652
+ async replaceTrack(kind, track, stream, { slot = 'camera' } = {}) {
653
+ if (slot === 'content') {
654
+ this.contentTrack = track || null;
655
+ this.contentStream = track ? stream || null : null;
656
+ } else if (stream) this.localStream = stream;
519
657
  for (const rec of this.peers.values()) {
520
658
  if (!rec.pc) continue;
659
+ const content = this._contentTransceiver(rec.pc);
660
+ if (slot === 'content') {
661
+ if (!content) continue;
662
+ await content.sender.replaceTrack(track || null).catch(() => {});
663
+ if (track && stream && content.sender.setStreams) content.sender.setStreams(stream);
664
+ continue;
665
+ }
521
666
  for (const tr of rec.pc.getTransceivers()) {
667
+ if (tr === content) continue;
522
668
  const k = tr.receiver && tr.receiver.track ? tr.receiver.track.kind : null;
523
669
  if (k === kind) await tr.sender.replaceTrack(track).catch(() => {});
524
670
  }
@@ -537,16 +683,21 @@ export class MeshTransport {
537
683
  */
538
684
  async tuneSenders() {
539
685
  const n = this.peers.size;
540
- const kbps = maxBitrateKbps(this.sendFormat, n);
686
+ const sharing = !!this.contentTrack;
687
+ // While content is on, the camera yields: the shared app is what people look at.
688
+ const kbps = Math.round(maxBitrateKbps(this.sendFormat, n) * (sharing ? CAMERA_SHARE_FACTOR : 1));
689
+ const contentKbps = maxBitrateKbps('sbs', n);
541
690
  for (const rec of this.peers.values()) {
542
691
  if (!rec.pc) continue;
692
+ const ct = this._contentTransceiver(rec.pc);
543
693
  for (const s of rec.pc.getSenders()) {
544
694
  if (!s.track || s.track.kind !== 'video') continue;
695
+ const isContent = !!(ct && ct.sender === s);
545
696
  try {
546
697
  const p = s.getParameters();
547
698
  p.degradationPreference = 'maintain-resolution';
548
699
  if (!p.encodings || !p.encodings.length) p.encodings = [{}];
549
- p.encodings[0].maxBitrate = kbps * 1000;
700
+ p.encodings[0].maxBitrate = (isContent ? contentKbps : kbps) * 1000;
550
701
  await s.setParameters(p);
551
702
  } catch (err) {
552
703
  this.log('setParameters-error', { peer: rec.id, err: String(err) });
package/js/call/ui.js CHANGED
@@ -8,7 +8,12 @@
8
8
  // pill, never a plate congruent with the tile (it would match the canvas's own quad on a
9
9
  // legacy browser and take the tile out of the weave). The bottom bar and self view live in a
10
10
  // footer BELOW the grid, over no tile at all.
11
- // 2. NO `backdrop-filter`. The near-solid `--dxr-shell` (rgba(16,17,22,.92)) is the substitute.
11
+ // 2. NO `backdrop-filter` in the SDK's own chrome. The near-solid `--dxr-shell`
12
+ // (rgba(16,17,22,.92)) is its choice, and it stays. A frosted element OVER a tile is no longer
13
+ // a defect on DisplayXR Browser 0.1.16+ (browser#120: the compositor draws the tile mono
14
+ // inside each frost rect; samples/composition is the validated case) — a page's own chrome may
15
+ // use it. Never frost a WHOLE visible tile, and rule 3 (effects on the canvas or an ancestor)
16
+ // is unchanged.
12
17
  // 3. Promotion is `will-change: transform`. No CSS filter / opacity / border-radius / shadow on a
13
18
  // woven canvas OR ANY ANCESTOR of one — the tile, the grid and the host stay visually bare.
14
19
  // A speaking highlight is a separate bar UNDER the stage, not an outline around it.
@@ -143,10 +148,15 @@ const CSS = `
143
148
  .dxr-call-grid[data-layout="speaker"]{grid-template-columns:repeat(3,1fr);}
144
149
  .dxr-call-grid[data-layout="speaker"] .dxr-call-tile--main{grid-column:1/-1;}
145
150
  .dxr-call-grid[data-layout="speaker"][data-n="1"]{grid-template-columns:1fr;}
151
+ /* Shared content (3D app share): the content tile spans the row, the people form a strip under it. */
152
+ .dxr-call-grid[data-content="1"]:not([data-n="1"]){grid-template-columns:repeat(3,1fr);max-width:calc(var(--dxr-call-h)*4/3);}
153
+ .dxr-call-grid[data-content="1"] .dxr-call-tile--main{grid-column:1/-1;}
146
154
  /* layout:'none' — the module creates the tiles but does not position them: the grid box steps
147
155
  aside (display:contents) so each [data-dxr-peer] tile is laid out by the PAGE's own CSS on the
148
156
  host. A tile is never moved; it is styled in place (woven-canvas rule 2). */
149
157
  .dxr-call-grid[data-layout="none"]{display:contents;}
158
+ /* …and so do the footer and the self slot, so the page places the self tile ([data-dxr-peer="self"]). */
159
+ .dxr-call-host--none .dxr-call-foot,.dxr-call-host--none .dxr-call-self{display:contents;}
150
160
  .dxr-call-tile{position:relative;min-width:0;}
151
161
  .dxr-call-stage{position:relative;background:#000;}
152
162
  .dxr-call-stage>canvas{display:block;width:100%;height:100%;}